You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

39353 lines
1.2 MiB

  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. /*jshint globalstrict: false */
  18. /* globals PDFJS */
  19. // Initializing PDFJS global object (if still undefined)
  20. if (typeof PDFJS === 'undefined') {
  21. (typeof window !== 'undefined' ? window : this).PDFJS = {};
  22. }
  23. PDFJS.version = '1.1.114';
  24. PDFJS.build = '3fd44fd';
  25. (function pdfjsWrapper() {
  26. // Use strict in our context only - users might not want it
  27. 'use strict';
  28. /* -*- Mode: Java; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
  29. /* vim: set shiftwidth=2 tabstop=2 autoindent cindent expandtab: */
  30. /* Copyright 2012 Mozilla Foundation
  31. *
  32. * Licensed under the Apache License, Version 2.0 (the "License");
  33. * you may not use this file except in compliance with the License.
  34. * You may obtain a copy of the License at
  35. *
  36. * http://www.apache.org/licenses/LICENSE-2.0
  37. *
  38. * Unless required by applicable law or agreed to in writing, software
  39. * distributed under the License is distributed on an "AS IS" BASIS,
  40. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  41. * See the License for the specific language governing permissions and
  42. * limitations under the License.
  43. */
  44. /* globals Cmd, ColorSpace, Dict, MozBlobBuilder, Name, PDFJS, Ref, URL,
  45. Promise */
  46. 'use strict';
  47. var globalScope = (typeof window === 'undefined') ? this : window;
  48. var isWorker = (typeof window === 'undefined');
  49. var FONT_IDENTITY_MATRIX = [0.001, 0, 0, 0.001, 0, 0];
  50. var TextRenderingMode = {
  51. FILL: 0,
  52. STROKE: 1,
  53. FILL_STROKE: 2,
  54. INVISIBLE: 3,
  55. FILL_ADD_TO_PATH: 4,
  56. STROKE_ADD_TO_PATH: 5,
  57. FILL_STROKE_ADD_TO_PATH: 6,
  58. ADD_TO_PATH: 7,
  59. FILL_STROKE_MASK: 3,
  60. ADD_TO_PATH_FLAG: 4
  61. };
  62. var ImageKind = {
  63. GRAYSCALE_1BPP: 1,
  64. RGB_24BPP: 2,
  65. RGBA_32BPP: 3
  66. };
  67. var AnnotationType = {
  68. WIDGET: 1,
  69. TEXT: 2,
  70. LINK: 3
  71. };
  72. var StreamType = {
  73. UNKNOWN: 0,
  74. FLATE: 1,
  75. LZW: 2,
  76. DCT: 3,
  77. JPX: 4,
  78. JBIG: 5,
  79. A85: 6,
  80. AHX: 7,
  81. CCF: 8,
  82. RL: 9
  83. };
  84. var FontType = {
  85. UNKNOWN: 0,
  86. TYPE1: 1,
  87. TYPE1C: 2,
  88. CIDFONTTYPE0: 3,
  89. CIDFONTTYPE0C: 4,
  90. TRUETYPE: 5,
  91. CIDFONTTYPE2: 6,
  92. TYPE3: 7,
  93. OPENTYPE: 8,
  94. TYPE0: 9,
  95. MMTYPE1: 10
  96. };
  97. // The global PDFJS object exposes the API
  98. // In production, it will be declared outside a global wrapper
  99. // In development, it will be declared here
  100. if (!globalScope.PDFJS) {
  101. globalScope.PDFJS = {};
  102. }
  103. globalScope.PDFJS.pdfBug = false;
  104. PDFJS.VERBOSITY_LEVELS = {
  105. errors: 0,
  106. warnings: 1,
  107. infos: 5
  108. };
  109. // All the possible operations for an operator list.
  110. var OPS = PDFJS.OPS = {
  111. // Intentionally start from 1 so it is easy to spot bad operators that will be
  112. // 0's.
  113. dependency: 1,
  114. setLineWidth: 2,
  115. setLineCap: 3,
  116. setLineJoin: 4,
  117. setMiterLimit: 5,
  118. setDash: 6,
  119. setRenderingIntent: 7,
  120. setFlatness: 8,
  121. setGState: 9,
  122. save: 10,
  123. restore: 11,
  124. transform: 12,
  125. moveTo: 13,
  126. lineTo: 14,
  127. curveTo: 15,
  128. curveTo2: 16,
  129. curveTo3: 17,
  130. closePath: 18,
  131. rectangle: 19,
  132. stroke: 20,
  133. closeStroke: 21,
  134. fill: 22,
  135. eoFill: 23,
  136. fillStroke: 24,
  137. eoFillStroke: 25,
  138. closeFillStroke: 26,
  139. closeEOFillStroke: 27,
  140. endPath: 28,
  141. clip: 29,
  142. eoClip: 30,
  143. beginText: 31,
  144. endText: 32,
  145. setCharSpacing: 33,
  146. setWordSpacing: 34,
  147. setHScale: 35,
  148. setLeading: 36,
  149. setFont: 37,
  150. setTextRenderingMode: 38,
  151. setTextRise: 39,
  152. moveText: 40,
  153. setLeadingMoveText: 41,
  154. setTextMatrix: 42,
  155. nextLine: 43,
  156. showText: 44,
  157. showSpacedText: 45,
  158. nextLineShowText: 46,
  159. nextLineSetSpacingShowText: 47,
  160. setCharWidth: 48,
  161. setCharWidthAndBounds: 49,
  162. setStrokeColorSpace: 50,
  163. setFillColorSpace: 51,
  164. setStrokeColor: 52,
  165. setStrokeColorN: 53,
  166. setFillColor: 54,
  167. setFillColorN: 55,
  168. setStrokeGray: 56,
  169. setFillGray: 57,
  170. setStrokeRGBColor: 58,
  171. setFillRGBColor: 59,
  172. setStrokeCMYKColor: 60,
  173. setFillCMYKColor: 61,
  174. shadingFill: 62,
  175. beginInlineImage: 63,
  176. beginImageData: 64,
  177. endInlineImage: 65,
  178. paintXObject: 66,
  179. markPoint: 67,
  180. markPointProps: 68,
  181. beginMarkedContent: 69,
  182. beginMarkedContentProps: 70,
  183. endMarkedContent: 71,
  184. beginCompat: 72,
  185. endCompat: 73,
  186. paintFormXObjectBegin: 74,
  187. paintFormXObjectEnd: 75,
  188. beginGroup: 76,
  189. endGroup: 77,
  190. beginAnnotations: 78,
  191. endAnnotations: 79,
  192. beginAnnotation: 80,
  193. endAnnotation: 81,
  194. paintJpegXObject: 82,
  195. paintImageMaskXObject: 83,
  196. paintImageMaskXObjectGroup: 84,
  197. paintImageXObject: 85,
  198. paintInlineImageXObject: 86,
  199. paintInlineImageXObjectGroup: 87,
  200. paintImageXObjectRepeat: 88,
  201. paintImageMaskXObjectRepeat: 89,
  202. paintSolidColorImageMask: 90,
  203. constructPath: 91
  204. };
  205. // A notice for devs. These are good for things that are helpful to devs, such
  206. // as warning that Workers were disabled, which is important to devs but not
  207. // end users.
  208. function info(msg) {
  209. if (PDFJS.verbosity >= PDFJS.VERBOSITY_LEVELS.infos) {
  210. console.log('Info: ' + msg);
  211. }
  212. }
  213. // Non-fatal warnings.
  214. function warn(msg) {
  215. if (PDFJS.verbosity >= PDFJS.VERBOSITY_LEVELS.warnings) {
  216. console.log('Warning: ' + msg);
  217. }
  218. }
  219. // Fatal errors that should trigger the fallback UI and halt execution by
  220. // throwing an exception.
  221. function error(msg) {
  222. if (PDFJS.verbosity >= PDFJS.VERBOSITY_LEVELS.errors) {
  223. console.log('Error: ' + msg);
  224. console.log(backtrace());
  225. }
  226. UnsupportedManager.notify(UNSUPPORTED_FEATURES.unknown);
  227. throw new Error(msg);
  228. }
  229. function backtrace() {
  230. try {
  231. throw new Error();
  232. } catch (e) {
  233. return e.stack ? e.stack.split('\n').slice(2).join('\n') : '';
  234. }
  235. }
  236. function assert(cond, msg) {
  237. if (!cond) {
  238. error(msg);
  239. }
  240. }
  241. var UNSUPPORTED_FEATURES = PDFJS.UNSUPPORTED_FEATURES = {
  242. unknown: 'unknown',
  243. forms: 'forms',
  244. javaScript: 'javaScript',
  245. smask: 'smask',
  246. shadingPattern: 'shadingPattern',
  247. font: 'font'
  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. // Combines two URLs. The baseUrl shall be absolute URL. If the url is an
  265. // absolute URL, it will be returned as is.
  266. function combineUrl(baseUrl, url) {
  267. if (!url) {
  268. return baseUrl;
  269. }
  270. if (/^[a-z][a-z0-9+\-.]*:/i.test(url)) {
  271. return url;
  272. }
  273. var i;
  274. if (url.charAt(0) === '/') {
  275. // absolute path
  276. i = baseUrl.indexOf('://');
  277. if (url.charAt(1) === '/') {
  278. ++i;
  279. } else {
  280. i = baseUrl.indexOf('/', i + 3);
  281. }
  282. return baseUrl.substring(0, i) + url;
  283. } else {
  284. // relative path
  285. var pathLength = baseUrl.length;
  286. i = baseUrl.lastIndexOf('#');
  287. pathLength = i >= 0 ? i : pathLength;
  288. i = baseUrl.lastIndexOf('?', pathLength);
  289. pathLength = i >= 0 ? i : pathLength;
  290. var prefixLength = baseUrl.lastIndexOf('/', pathLength);
  291. return baseUrl.substring(0, prefixLength + 1) + url;
  292. }
  293. }
  294. // Validates if URL is safe and allowed, e.g. to avoid XSS.
  295. function isValidUrl(url, allowRelative) {
  296. if (!url) {
  297. return false;
  298. }
  299. // RFC 3986 (http://tools.ietf.org/html/rfc3986#section-3.1)
  300. // scheme = ALPHA *( ALPHA / DIGIT / "+" / "-" / "." )
  301. var protocol = /^[a-z][a-z0-9+\-.]*(?=:)/i.exec(url);
  302. if (!protocol) {
  303. return allowRelative;
  304. }
  305. protocol = protocol[0].toLowerCase();
  306. switch (protocol) {
  307. case 'http':
  308. case 'https':
  309. case 'ftp':
  310. case 'mailto':
  311. case 'tel':
  312. return true;
  313. default:
  314. return false;
  315. }
  316. }
  317. PDFJS.isValidUrl = isValidUrl;
  318. function shadow(obj, prop, value) {
  319. Object.defineProperty(obj, prop, { value: value,
  320. enumerable: true,
  321. configurable: true,
  322. writable: false });
  323. return value;
  324. }
  325. PDFJS.shadow = shadow;
  326. var PasswordResponses = PDFJS.PasswordResponses = {
  327. NEED_PASSWORD: 1,
  328. INCORRECT_PASSWORD: 2
  329. };
  330. var PasswordException = (function PasswordExceptionClosure() {
  331. function PasswordException(msg, code) {
  332. this.name = 'PasswordException';
  333. this.message = msg;
  334. this.code = code;
  335. }
  336. PasswordException.prototype = new Error();
  337. PasswordException.constructor = PasswordException;
  338. return PasswordException;
  339. })();
  340. PDFJS.PasswordException = PasswordException;
  341. var UnknownErrorException = (function UnknownErrorExceptionClosure() {
  342. function UnknownErrorException(msg, details) {
  343. this.name = 'UnknownErrorException';
  344. this.message = msg;
  345. this.details = details;
  346. }
  347. UnknownErrorException.prototype = new Error();
  348. UnknownErrorException.constructor = UnknownErrorException;
  349. return UnknownErrorException;
  350. })();
  351. PDFJS.UnknownErrorException = UnknownErrorException;
  352. var InvalidPDFException = (function InvalidPDFExceptionClosure() {
  353. function InvalidPDFException(msg) {
  354. this.name = 'InvalidPDFException';
  355. this.message = msg;
  356. }
  357. InvalidPDFException.prototype = new Error();
  358. InvalidPDFException.constructor = InvalidPDFException;
  359. return InvalidPDFException;
  360. })();
  361. PDFJS.InvalidPDFException = InvalidPDFException;
  362. var MissingPDFException = (function MissingPDFExceptionClosure() {
  363. function MissingPDFException(msg) {
  364. this.name = 'MissingPDFException';
  365. this.message = msg;
  366. }
  367. MissingPDFException.prototype = new Error();
  368. MissingPDFException.constructor = MissingPDFException;
  369. return MissingPDFException;
  370. })();
  371. PDFJS.MissingPDFException = MissingPDFException;
  372. var UnexpectedResponseException =
  373. (function UnexpectedResponseExceptionClosure() {
  374. function UnexpectedResponseException(msg, status) {
  375. this.name = 'UnexpectedResponseException';
  376. this.message = msg;
  377. this.status = status;
  378. }
  379. UnexpectedResponseException.prototype = new Error();
  380. UnexpectedResponseException.constructor = UnexpectedResponseException;
  381. return UnexpectedResponseException;
  382. })();
  383. PDFJS.UnexpectedResponseException = UnexpectedResponseException;
  384. var NotImplementedException = (function NotImplementedExceptionClosure() {
  385. function NotImplementedException(msg) {
  386. this.message = msg;
  387. }
  388. NotImplementedException.prototype = new Error();
  389. NotImplementedException.prototype.name = 'NotImplementedException';
  390. NotImplementedException.constructor = NotImplementedException;
  391. return NotImplementedException;
  392. })();
  393. var MissingDataException = (function MissingDataExceptionClosure() {
  394. function MissingDataException(begin, end) {
  395. this.begin = begin;
  396. this.end = end;
  397. this.message = 'Missing data [' + begin + ', ' + end + ')';
  398. }
  399. MissingDataException.prototype = new Error();
  400. MissingDataException.prototype.name = 'MissingDataException';
  401. MissingDataException.constructor = MissingDataException;
  402. return MissingDataException;
  403. })();
  404. var XRefParseException = (function XRefParseExceptionClosure() {
  405. function XRefParseException(msg) {
  406. this.message = msg;
  407. }
  408. XRefParseException.prototype = new Error();
  409. XRefParseException.prototype.name = 'XRefParseException';
  410. XRefParseException.constructor = XRefParseException;
  411. return XRefParseException;
  412. })();
  413. function bytesToString(bytes) {
  414. assert(bytes !== null && typeof bytes === 'object' &&
  415. bytes.length !== undefined, 'Invalid argument for bytesToString');
  416. var length = bytes.length;
  417. var MAX_ARGUMENT_COUNT = 8192;
  418. if (length < MAX_ARGUMENT_COUNT) {
  419. return String.fromCharCode.apply(null, bytes);
  420. }
  421. var strBuf = [];
  422. for (var i = 0; i < length; i += MAX_ARGUMENT_COUNT) {
  423. var chunkEnd = Math.min(i + MAX_ARGUMENT_COUNT, length);
  424. var chunk = bytes.subarray(i, chunkEnd);
  425. strBuf.push(String.fromCharCode.apply(null, chunk));
  426. }
  427. return strBuf.join('');
  428. }
  429. function stringToBytes(str) {
  430. assert(typeof str === 'string', 'Invalid argument for stringToBytes');
  431. var length = str.length;
  432. var bytes = new Uint8Array(length);
  433. for (var i = 0; i < length; ++i) {
  434. bytes[i] = str.charCodeAt(i) & 0xFF;
  435. }
  436. return bytes;
  437. }
  438. function string32(value) {
  439. return String.fromCharCode((value >> 24) & 0xff, (value >> 16) & 0xff,
  440. (value >> 8) & 0xff, value & 0xff);
  441. }
  442. function log2(x) {
  443. var n = 1, i = 0;
  444. while (x > n) {
  445. n <<= 1;
  446. i++;
  447. }
  448. return i;
  449. }
  450. function readInt8(data, start) {
  451. return (data[start] << 24) >> 24;
  452. }
  453. function readUint16(data, offset) {
  454. return (data[offset] << 8) | data[offset + 1];
  455. }
  456. function readUint32(data, offset) {
  457. return ((data[offset] << 24) | (data[offset + 1] << 16) |
  458. (data[offset + 2] << 8) | data[offset + 3]) >>> 0;
  459. }
  460. // Lazy test the endianness of the platform
  461. // NOTE: This will be 'true' for simulated TypedArrays
  462. function isLittleEndian() {
  463. var buffer8 = new Uint8Array(2);
  464. buffer8[0] = 1;
  465. var buffer16 = new Uint16Array(buffer8.buffer);
  466. return (buffer16[0] === 1);
  467. }
  468. Object.defineProperty(PDFJS, 'isLittleEndian', {
  469. configurable: true,
  470. get: function PDFJS_isLittleEndian() {
  471. return shadow(PDFJS, 'isLittleEndian', isLittleEndian());
  472. }
  473. });
  474. //#if !(FIREFOX || MOZCENTRAL || B2G || CHROME)
  475. //// Lazy test if the userAgant support CanvasTypedArrays
  476. function hasCanvasTypedArrays() {
  477. var canvas = document.createElement('canvas');
  478. canvas.width = canvas.height = 1;
  479. var ctx = canvas.getContext('2d');
  480. var imageData = ctx.createImageData(1, 1);
  481. return (typeof imageData.data.buffer !== 'undefined');
  482. }
  483. Object.defineProperty(PDFJS, 'hasCanvasTypedArrays', {
  484. configurable: true,
  485. get: function PDFJS_hasCanvasTypedArrays() {
  486. return shadow(PDFJS, 'hasCanvasTypedArrays', hasCanvasTypedArrays());
  487. }
  488. });
  489. var Uint32ArrayView = (function Uint32ArrayViewClosure() {
  490. function Uint32ArrayView(buffer, length) {
  491. this.buffer = buffer;
  492. this.byteLength = buffer.length;
  493. this.length = length === undefined ? (this.byteLength >> 2) : length;
  494. ensureUint32ArrayViewProps(this.length);
  495. }
  496. Uint32ArrayView.prototype = Object.create(null);
  497. var uint32ArrayViewSetters = 0;
  498. function createUint32ArrayProp(index) {
  499. return {
  500. get: function () {
  501. var buffer = this.buffer, offset = index << 2;
  502. return (buffer[offset] | (buffer[offset + 1] << 8) |
  503. (buffer[offset + 2] << 16) | (buffer[offset + 3] << 24)) >>> 0;
  504. },
  505. set: function (value) {
  506. var buffer = this.buffer, offset = index << 2;
  507. buffer[offset] = value & 255;
  508. buffer[offset + 1] = (value >> 8) & 255;
  509. buffer[offset + 2] = (value >> 16) & 255;
  510. buffer[offset + 3] = (value >>> 24) & 255;
  511. }
  512. };
  513. }
  514. function ensureUint32ArrayViewProps(length) {
  515. while (uint32ArrayViewSetters < length) {
  516. Object.defineProperty(Uint32ArrayView.prototype,
  517. uint32ArrayViewSetters,
  518. createUint32ArrayProp(uint32ArrayViewSetters));
  519. uint32ArrayViewSetters++;
  520. }
  521. }
  522. return Uint32ArrayView;
  523. })();
  524. //#else
  525. //PDFJS.hasCanvasTypedArrays = true;
  526. //#endif
  527. var IDENTITY_MATRIX = [1, 0, 0, 1, 0, 0];
  528. var Util = PDFJS.Util = (function UtilClosure() {
  529. function Util() {}
  530. var rgbBuf = ['rgb(', 0, ',', 0, ',', 0, ')'];
  531. // makeCssRgb() can be called thousands of times. Using |rgbBuf| avoids
  532. // creating many intermediate strings.
  533. Util.makeCssRgb = function Util_makeCssRgb(r, g, b) {
  534. rgbBuf[1] = r;
  535. rgbBuf[3] = g;
  536. rgbBuf[5] = b;
  537. return rgbBuf.join('');
  538. };
  539. // Concatenates two transformation matrices together and returns the result.
  540. Util.transform = function Util_transform(m1, m2) {
  541. return [
  542. m1[0] * m2[0] + m1[2] * m2[1],
  543. m1[1] * m2[0] + m1[3] * m2[1],
  544. m1[0] * m2[2] + m1[2] * m2[3],
  545. m1[1] * m2[2] + m1[3] * m2[3],
  546. m1[0] * m2[4] + m1[2] * m2[5] + m1[4],
  547. m1[1] * m2[4] + m1[3] * m2[5] + m1[5]
  548. ];
  549. };
  550. // For 2d affine transforms
  551. Util.applyTransform = function Util_applyTransform(p, m) {
  552. var xt = p[0] * m[0] + p[1] * m[2] + m[4];
  553. var yt = p[0] * m[1] + p[1] * m[3] + m[5];
  554. return [xt, yt];
  555. };
  556. Util.applyInverseTransform = function Util_applyInverseTransform(p, m) {
  557. var d = m[0] * m[3] - m[1] * m[2];
  558. var xt = (p[0] * m[3] - p[1] * m[2] + m[2] * m[5] - m[4] * m[3]) / d;
  559. var yt = (-p[0] * m[1] + p[1] * m[0] + m[4] * m[1] - m[5] * m[0]) / d;
  560. return [xt, yt];
  561. };
  562. // Applies the transform to the rectangle and finds the minimum axially
  563. // aligned bounding box.
  564. Util.getAxialAlignedBoundingBox =
  565. function Util_getAxialAlignedBoundingBox(r, m) {
  566. var p1 = Util.applyTransform(r, m);
  567. var p2 = Util.applyTransform(r.slice(2, 4), m);
  568. var p3 = Util.applyTransform([r[0], r[3]], m);
  569. var p4 = Util.applyTransform([r[2], r[1]], m);
  570. return [
  571. Math.min(p1[0], p2[0], p3[0], p4[0]),
  572. Math.min(p1[1], p2[1], p3[1], p4[1]),
  573. Math.max(p1[0], p2[0], p3[0], p4[0]),
  574. Math.max(p1[1], p2[1], p3[1], p4[1])
  575. ];
  576. };
  577. Util.inverseTransform = function Util_inverseTransform(m) {
  578. var d = m[0] * m[3] - m[1] * m[2];
  579. return [m[3] / d, -m[1] / d, -m[2] / d, m[0] / d,
  580. (m[2] * m[5] - m[4] * m[3]) / d, (m[4] * m[1] - m[5] * m[0]) / d];
  581. };
  582. // Apply a generic 3d matrix M on a 3-vector v:
  583. // | a b c | | X |
  584. // | d e f | x | Y |
  585. // | g h i | | Z |
  586. // M is assumed to be serialized as [a,b,c,d,e,f,g,h,i],
  587. // with v as [X,Y,Z]
  588. Util.apply3dTransform = function Util_apply3dTransform(m, v) {
  589. return [
  590. m[0] * v[0] + m[1] * v[1] + m[2] * v[2],
  591. m[3] * v[0] + m[4] * v[1] + m[5] * v[2],
  592. m[6] * v[0] + m[7] * v[1] + m[8] * v[2]
  593. ];
  594. };
  595. // This calculation uses Singular Value Decomposition.
  596. // The SVD can be represented with formula A = USV. We are interested in the
  597. // matrix S here because it represents the scale values.
  598. Util.singularValueDecompose2dScale =
  599. function Util_singularValueDecompose2dScale(m) {
  600. var transpose = [m[0], m[2], m[1], m[3]];
  601. // Multiply matrix m with its transpose.
  602. var a = m[0] * transpose[0] + m[1] * transpose[2];
  603. var b = m[0] * transpose[1] + m[1] * transpose[3];
  604. var c = m[2] * transpose[0] + m[3] * transpose[2];
  605. var d = m[2] * transpose[1] + m[3] * transpose[3];
  606. // Solve the second degree polynomial to get roots.
  607. var first = (a + d) / 2;
  608. var second = Math.sqrt((a + d) * (a + d) - 4 * (a * d - c * b)) / 2;
  609. var sx = first + second || 1;
  610. var sy = first - second || 1;
  611. // Scale values are the square roots of the eigenvalues.
  612. return [Math.sqrt(sx), Math.sqrt(sy)];
  613. };
  614. // Normalize rectangle rect=[x1, y1, x2, y2] so that (x1,y1) < (x2,y2)
  615. // For coordinate systems whose origin lies in the bottom-left, this
  616. // means normalization to (BL,TR) ordering. For systems with origin in the
  617. // top-left, this means (TL,BR) ordering.
  618. Util.normalizeRect = function Util_normalizeRect(rect) {
  619. var r = rect.slice(0); // clone rect
  620. if (rect[0] > rect[2]) {
  621. r[0] = rect[2];
  622. r[2] = rect[0];
  623. }
  624. if (rect[1] > rect[3]) {
  625. r[1] = rect[3];
  626. r[3] = rect[1];
  627. }
  628. return r;
  629. };
  630. // Returns a rectangle [x1, y1, x2, y2] corresponding to the
  631. // intersection of rect1 and rect2. If no intersection, returns 'false'
  632. // The rectangle coordinates of rect1, rect2 should be [x1, y1, x2, y2]
  633. Util.intersect = function Util_intersect(rect1, rect2) {
  634. function compare(a, b) {
  635. return a - b;
  636. }
  637. // Order points along the axes
  638. var orderedX = [rect1[0], rect1[2], rect2[0], rect2[2]].sort(compare),
  639. orderedY = [rect1[1], rect1[3], rect2[1], rect2[3]].sort(compare),
  640. result = [];
  641. rect1 = Util.normalizeRect(rect1);
  642. rect2 = Util.normalizeRect(rect2);
  643. // X: first and second points belong to different rectangles?
  644. if ((orderedX[0] === rect1[0] && orderedX[1] === rect2[0]) ||
  645. (orderedX[0] === rect2[0] && orderedX[1] === rect1[0])) {
  646. // Intersection must be between second and third points
  647. result[0] = orderedX[1];
  648. result[2] = orderedX[2];
  649. } else {
  650. return false;
  651. }
  652. // Y: first and second points belong to different rectangles?
  653. if ((orderedY[0] === rect1[1] && orderedY[1] === rect2[1]) ||
  654. (orderedY[0] === rect2[1] && orderedY[1] === rect1[1])) {
  655. // Intersection must be between second and third points
  656. result[1] = orderedY[1];
  657. result[3] = orderedY[2];
  658. } else {
  659. return false;
  660. }
  661. return result;
  662. };
  663. Util.sign = function Util_sign(num) {
  664. return num < 0 ? -1 : 1;
  665. };
  666. Util.appendToArray = function Util_appendToArray(arr1, arr2) {
  667. Array.prototype.push.apply(arr1, arr2);
  668. };
  669. Util.prependToArray = function Util_prependToArray(arr1, arr2) {
  670. Array.prototype.unshift.apply(arr1, arr2);
  671. };
  672. Util.extendObj = function extendObj(obj1, obj2) {
  673. for (var key in obj2) {
  674. obj1[key] = obj2[key];
  675. }
  676. };
  677. Util.getInheritableProperty = function Util_getInheritableProperty(dict,
  678. name) {
  679. while (dict && !dict.has(name)) {
  680. dict = dict.get('Parent');
  681. }
  682. if (!dict) {
  683. return null;
  684. }
  685. return dict.get(name);
  686. };
  687. Util.inherit = function Util_inherit(sub, base, prototype) {
  688. sub.prototype = Object.create(base.prototype);
  689. sub.prototype.constructor = sub;
  690. for (var prop in prototype) {
  691. sub.prototype[prop] = prototype[prop];
  692. }
  693. };
  694. Util.loadScript = function Util_loadScript(src, callback) {
  695. var script = document.createElement('script');
  696. var loaded = false;
  697. script.setAttribute('src', src);
  698. if (callback) {
  699. script.onload = function() {
  700. if (!loaded) {
  701. callback();
  702. }
  703. loaded = true;
  704. };
  705. }
  706. document.getElementsByTagName('head')[0].appendChild(script);
  707. };
  708. return Util;
  709. })();
  710. /**
  711. * PDF page viewport created based on scale, rotation and offset.
  712. * @class
  713. * @alias PDFJS.PageViewport
  714. */
  715. var PageViewport = PDFJS.PageViewport = (function PageViewportClosure() {
  716. /**
  717. * @constructor
  718. * @private
  719. * @param viewBox {Array} xMin, yMin, xMax and yMax coordinates.
  720. * @param scale {number} scale of the viewport.
  721. * @param rotation {number} rotations of the viewport in degrees.
  722. * @param offsetX {number} offset X
  723. * @param offsetY {number} offset Y
  724. * @param dontFlip {boolean} if true, axis Y will not be flipped.
  725. */
  726. function PageViewport(viewBox, scale, rotation, offsetX, offsetY, dontFlip) {
  727. this.viewBox = viewBox;
  728. this.scale = scale;
  729. this.rotation = rotation;
  730. this.offsetX = offsetX;
  731. this.offsetY = offsetY;
  732. // creating transform to convert pdf coordinate system to the normal
  733. // canvas like coordinates taking in account scale and rotation
  734. var centerX = (viewBox[2] + viewBox[0]) / 2;
  735. var centerY = (viewBox[3] + viewBox[1]) / 2;
  736. var rotateA, rotateB, rotateC, rotateD;
  737. rotation = rotation % 360;
  738. rotation = rotation < 0 ? rotation + 360 : rotation;
  739. switch (rotation) {
  740. case 180:
  741. rotateA = -1; rotateB = 0; rotateC = 0; rotateD = 1;
  742. break;
  743. case 90:
  744. rotateA = 0; rotateB = 1; rotateC = 1; rotateD = 0;
  745. break;
  746. case 270:
  747. rotateA = 0; rotateB = -1; rotateC = -1; rotateD = 0;
  748. break;
  749. //case 0:
  750. default:
  751. rotateA = 1; rotateB = 0; rotateC = 0; rotateD = -1;
  752. break;
  753. }
  754. if (dontFlip) {
  755. rotateC = -rotateC; rotateD = -rotateD;
  756. }
  757. var offsetCanvasX, offsetCanvasY;
  758. var width, height;
  759. if (rotateA === 0) {
  760. offsetCanvasX = Math.abs(centerY - viewBox[1]) * scale + offsetX;
  761. offsetCanvasY = Math.abs(centerX - viewBox[0]) * scale + offsetY;
  762. width = Math.abs(viewBox[3] - viewBox[1]) * scale;
  763. height = Math.abs(viewBox[2] - viewBox[0]) * scale;
  764. } else {
  765. offsetCanvasX = Math.abs(centerX - viewBox[0]) * scale + offsetX;
  766. offsetCanvasY = Math.abs(centerY - viewBox[1]) * scale + offsetY;
  767. width = Math.abs(viewBox[2] - viewBox[0]) * scale;
  768. height = Math.abs(viewBox[3] - viewBox[1]) * scale;
  769. }
  770. // creating transform for the following operations:
  771. // translate(-centerX, -centerY), rotate and flip vertically,
  772. // scale, and translate(offsetCanvasX, offsetCanvasY)
  773. this.transform = [
  774. rotateA * scale,
  775. rotateB * scale,
  776. rotateC * scale,
  777. rotateD * scale,
  778. offsetCanvasX - rotateA * scale * centerX - rotateC * scale * centerY,
  779. offsetCanvasY - rotateB * scale * centerX - rotateD * scale * centerY
  780. ];
  781. this.width = width;
  782. this.height = height;
  783. this.fontScale = scale;
  784. }
  785. PageViewport.prototype = /** @lends PDFJS.PageViewport.prototype */ {
  786. /**
  787. * Clones viewport with additional properties.
  788. * @param args {Object} (optional) If specified, may contain the 'scale' or
  789. * 'rotation' properties to override the corresponding properties in
  790. * the cloned viewport.
  791. * @returns {PDFJS.PageViewport} Cloned viewport.
  792. */
  793. clone: function PageViewPort_clone(args) {
  794. args = args || {};
  795. var scale = 'scale' in args ? args.scale : this.scale;
  796. var rotation = 'rotation' in args ? args.rotation : this.rotation;
  797. return new PageViewport(this.viewBox.slice(), scale, rotation,
  798. this.offsetX, this.offsetY, args.dontFlip);
  799. },
  800. /**
  801. * Converts PDF point to the viewport coordinates. For examples, useful for
  802. * converting PDF location into canvas pixel coordinates.
  803. * @param x {number} X coordinate.
  804. * @param y {number} Y coordinate.
  805. * @returns {Object} Object that contains 'x' and 'y' properties of the
  806. * point in the viewport coordinate space.
  807. * @see {@link convertToPdfPoint}
  808. * @see {@link convertToViewportRectangle}
  809. */
  810. convertToViewportPoint: function PageViewport_convertToViewportPoint(x, y) {
  811. return Util.applyTransform([x, y], this.transform);
  812. },
  813. /**
  814. * Converts PDF rectangle to the viewport coordinates.
  815. * @param rect {Array} xMin, yMin, xMax and yMax coordinates.
  816. * @returns {Array} Contains corresponding coordinates of the rectangle
  817. * in the viewport coordinate space.
  818. * @see {@link convertToViewportPoint}
  819. */
  820. convertToViewportRectangle:
  821. function PageViewport_convertToViewportRectangle(rect) {
  822. var tl = Util.applyTransform([rect[0], rect[1]], this.transform);
  823. var br = Util.applyTransform([rect[2], rect[3]], this.transform);
  824. return [tl[0], tl[1], br[0], br[1]];
  825. },
  826. /**
  827. * Converts viewport coordinates to the PDF location. For examples, useful
  828. * for converting canvas pixel location into PDF one.
  829. * @param x {number} X coordinate.
  830. * @param y {number} Y coordinate.
  831. * @returns {Object} Object that contains 'x' and 'y' properties of the
  832. * point in the PDF coordinate space.
  833. * @see {@link convertToViewportPoint}
  834. */
  835. convertToPdfPoint: function PageViewport_convertToPdfPoint(x, y) {
  836. return Util.applyInverseTransform([x, y], this.transform);
  837. }
  838. };
  839. return PageViewport;
  840. })();
  841. var PDFStringTranslateTable = [
  842. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  843. 0x2D8, 0x2C7, 0x2C6, 0x2D9, 0x2DD, 0x2DB, 0x2DA, 0x2DC, 0, 0, 0, 0, 0, 0, 0,
  844. 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,
  845. 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,
  846. 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,
  847. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0x2022, 0x2020, 0x2021, 0x2026, 0x2014,
  848. 0x2013, 0x192, 0x2044, 0x2039, 0x203A, 0x2212, 0x2030, 0x201E, 0x201C,
  849. 0x201D, 0x2018, 0x2019, 0x201A, 0x2122, 0xFB01, 0xFB02, 0x141, 0x152, 0x160,
  850. 0x178, 0x17D, 0x131, 0x142, 0x153, 0x161, 0x17E, 0, 0x20AC
  851. ];
  852. function stringToPDFString(str) {
  853. var i, n = str.length, strBuf = [];
  854. if (str[0] === '\xFE' && str[1] === '\xFF') {
  855. // UTF16BE BOM
  856. for (i = 2; i < n; i += 2) {
  857. strBuf.push(String.fromCharCode(
  858. (str.charCodeAt(i) << 8) | str.charCodeAt(i + 1)));
  859. }
  860. } else {
  861. for (i = 0; i < n; ++i) {
  862. var code = PDFStringTranslateTable[str.charCodeAt(i)];
  863. strBuf.push(code ? String.fromCharCode(code) : str.charAt(i));
  864. }
  865. }
  866. return strBuf.join('');
  867. }
  868. function stringToUTF8String(str) {
  869. return decodeURIComponent(escape(str));
  870. }
  871. function isEmptyObj(obj) {
  872. for (var key in obj) {
  873. return false;
  874. }
  875. return true;
  876. }
  877. function isBool(v) {
  878. return typeof v === 'boolean';
  879. }
  880. function isInt(v) {
  881. return typeof v === 'number' && ((v | 0) === v);
  882. }
  883. function isNum(v) {
  884. return typeof v === 'number';
  885. }
  886. function isString(v) {
  887. return typeof v === 'string';
  888. }
  889. function isName(v) {
  890. return v instanceof Name;
  891. }
  892. function isCmd(v, cmd) {
  893. return v instanceof Cmd && (cmd === undefined || v.cmd === cmd);
  894. }
  895. function isDict(v, type) {
  896. if (!(v instanceof Dict)) {
  897. return false;
  898. }
  899. if (!type) {
  900. return true;
  901. }
  902. var dictType = v.get('Type');
  903. return isName(dictType) && dictType.name === type;
  904. }
  905. function isArray(v) {
  906. return v instanceof Array;
  907. }
  908. function isStream(v) {
  909. return typeof v === 'object' && v !== null && v.getBytes !== undefined;
  910. }
  911. function isArrayBuffer(v) {
  912. return typeof v === 'object' && v !== null && v.byteLength !== undefined;
  913. }
  914. function isRef(v) {
  915. return v instanceof Ref;
  916. }
  917. /**
  918. * Promise Capability object.
  919. *
  920. * @typedef {Object} PromiseCapability
  921. * @property {Promise} promise - A promise object.
  922. * @property {function} resolve - Fullfills the promise.
  923. * @property {function} reject - Rejects the promise.
  924. */
  925. /**
  926. * Creates a promise capability object.
  927. * @alias PDFJS.createPromiseCapability
  928. *
  929. * @return {PromiseCapability} A capability object contains:
  930. * - a Promise, resolve and reject methods.
  931. */
  932. function createPromiseCapability() {
  933. var capability = {};
  934. capability.promise = new Promise(function (resolve, reject) {
  935. capability.resolve = resolve;
  936. capability.reject = reject;
  937. });
  938. return capability;
  939. }
  940. PDFJS.createPromiseCapability = createPromiseCapability;
  941. /**
  942. * Polyfill for Promises:
  943. * The following promise implementation tries to generally implement the
  944. * Promise/A+ spec. Some notable differences from other promise libaries are:
  945. * - There currently isn't a seperate deferred and promise object.
  946. * - Unhandled rejections eventually show an error if they aren't handled.
  947. *
  948. * Based off of the work in:
  949. * https://bugzilla.mozilla.org/show_bug.cgi?id=810490
  950. */
  951. (function PromiseClosure() {
  952. if (globalScope.Promise) {
  953. // Promises existing in the DOM/Worker, checking presence of all/resolve
  954. if (typeof globalScope.Promise.all !== 'function') {
  955. globalScope.Promise.all = function (iterable) {
  956. var count = 0, results = [], resolve, reject;
  957. var promise = new globalScope.Promise(function (resolve_, reject_) {
  958. resolve = resolve_;
  959. reject = reject_;
  960. });
  961. iterable.forEach(function (p, i) {
  962. count++;
  963. p.then(function (result) {
  964. results[i] = result;
  965. count--;
  966. if (count === 0) {
  967. resolve(results);
  968. }
  969. }, reject);
  970. });
  971. if (count === 0) {
  972. resolve(results);
  973. }
  974. return promise;
  975. };
  976. }
  977. if (typeof globalScope.Promise.resolve !== 'function') {
  978. globalScope.Promise.resolve = function (value) {
  979. return new globalScope.Promise(function (resolve) { resolve(value); });
  980. };
  981. }
  982. if (typeof globalScope.Promise.reject !== 'function') {
  983. globalScope.Promise.reject = function (reason) {
  984. return new globalScope.Promise(function (resolve, reject) {
  985. reject(reason);
  986. });
  987. };
  988. }
  989. if (typeof globalScope.Promise.prototype.catch !== 'function') {
  990. globalScope.Promise.prototype.catch = function (onReject) {
  991. return globalScope.Promise.prototype.then(undefined, onReject);
  992. };
  993. }
  994. return;
  995. }
  996. //#if !MOZCENTRAL
  997. var STATUS_PENDING = 0;
  998. var STATUS_RESOLVED = 1;
  999. var STATUS_REJECTED = 2;
  1000. // In an attempt to avoid silent exceptions, unhandled rejections are
  1001. // tracked and if they aren't handled in a certain amount of time an
  1002. // error is logged.
  1003. var REJECTION_TIMEOUT = 500;
  1004. var HandlerManager = {
  1005. handlers: [],
  1006. running: false,
  1007. unhandledRejections: [],
  1008. pendingRejectionCheck: false,
  1009. scheduleHandlers: function scheduleHandlers(promise) {
  1010. if (promise._status === STATUS_PENDING) {
  1011. return;
  1012. }
  1013. this.handlers = this.handlers.concat(promise._handlers);
  1014. promise._handlers = [];
  1015. if (this.running) {
  1016. return;
  1017. }
  1018. this.running = true;
  1019. setTimeout(this.runHandlers.bind(this), 0);
  1020. },
  1021. runHandlers: function runHandlers() {
  1022. var RUN_TIMEOUT = 1; // ms
  1023. var timeoutAt = Date.now() + RUN_TIMEOUT;
  1024. while (this.handlers.length > 0) {
  1025. var handler = this.handlers.shift();
  1026. var nextStatus = handler.thisPromise._status;
  1027. var nextValue = handler.thisPromise._value;
  1028. try {
  1029. if (nextStatus === STATUS_RESOLVED) {
  1030. if (typeof handler.onResolve === 'function') {
  1031. nextValue = handler.onResolve(nextValue);
  1032. }
  1033. } else if (typeof handler.onReject === 'function') {
  1034. nextValue = handler.onReject(nextValue);
  1035. nextStatus = STATUS_RESOLVED;
  1036. if (handler.thisPromise._unhandledRejection) {
  1037. this.removeUnhandeledRejection(handler.thisPromise);
  1038. }
  1039. }
  1040. } catch (ex) {
  1041. nextStatus = STATUS_REJECTED;
  1042. nextValue = ex;
  1043. }
  1044. handler.nextPromise._updateStatus(nextStatus, nextValue);
  1045. if (Date.now() >= timeoutAt) {
  1046. break;
  1047. }
  1048. }
  1049. if (this.handlers.length > 0) {
  1050. setTimeout(this.runHandlers.bind(this), 0);
  1051. return;
  1052. }
  1053. this.running = false;
  1054. },
  1055. addUnhandledRejection: function addUnhandledRejection(promise) {
  1056. this.unhandledRejections.push({
  1057. promise: promise,
  1058. time: Date.now()
  1059. });
  1060. this.scheduleRejectionCheck();
  1061. },
  1062. removeUnhandeledRejection: function removeUnhandeledRejection(promise) {
  1063. promise._unhandledRejection = false;
  1064. for (var i = 0; i < this.unhandledRejections.length; i++) {
  1065. if (this.unhandledRejections[i].promise === promise) {
  1066. this.unhandledRejections.splice(i);
  1067. i--;
  1068. }
  1069. }
  1070. },
  1071. scheduleRejectionCheck: function scheduleRejectionCheck() {
  1072. if (this.pendingRejectionCheck) {
  1073. return;
  1074. }
  1075. this.pendingRejectionCheck = true;
  1076. setTimeout(function rejectionCheck() {
  1077. this.pendingRejectionCheck = false;
  1078. var now = Date.now();
  1079. for (var i = 0; i < this.unhandledRejections.length; i++) {
  1080. if (now - this.unhandledRejections[i].time > REJECTION_TIMEOUT) {
  1081. var unhandled = this.unhandledRejections[i].promise._value;
  1082. var msg = 'Unhandled rejection: ' + unhandled;
  1083. if (unhandled.stack) {
  1084. msg += '\n' + unhandled.stack;
  1085. }
  1086. warn(msg);
  1087. this.unhandledRejections.splice(i);
  1088. i--;
  1089. }
  1090. }
  1091. if (this.unhandledRejections.length) {
  1092. this.scheduleRejectionCheck();
  1093. }
  1094. }.bind(this), REJECTION_TIMEOUT);
  1095. }
  1096. };
  1097. function Promise(resolver) {
  1098. this._status = STATUS_PENDING;
  1099. this._handlers = [];
  1100. try {
  1101. resolver.call(this, this._resolve.bind(this), this._reject.bind(this));
  1102. } catch (e) {
  1103. this._reject(e);
  1104. }
  1105. }
  1106. /**
  1107. * Builds a promise that is resolved when all the passed in promises are
  1108. * resolved.
  1109. * @param {array} array of data and/or promises to wait for.
  1110. * @return {Promise} New dependant promise.
  1111. */
  1112. Promise.all = function Promise_all(promises) {
  1113. var resolveAll, rejectAll;
  1114. var deferred = new Promise(function (resolve, reject) {
  1115. resolveAll = resolve;
  1116. rejectAll = reject;
  1117. });
  1118. var unresolved = promises.length;
  1119. var results = [];
  1120. if (unresolved === 0) {
  1121. resolveAll(results);
  1122. return deferred;
  1123. }
  1124. function reject(reason) {
  1125. if (deferred._status === STATUS_REJECTED) {
  1126. return;
  1127. }
  1128. results = [];
  1129. rejectAll(reason);
  1130. }
  1131. for (var i = 0, ii = promises.length; i < ii; ++i) {
  1132. var promise = promises[i];
  1133. var resolve = (function(i) {
  1134. return function(value) {
  1135. if (deferred._status === STATUS_REJECTED) {
  1136. return;
  1137. }
  1138. results[i] = value;
  1139. unresolved--;
  1140. if (unresolved === 0) {
  1141. resolveAll(results);
  1142. }
  1143. };
  1144. })(i);
  1145. if (Promise.isPromise(promise)) {
  1146. promise.then(resolve, reject);
  1147. } else {
  1148. resolve(promise);
  1149. }
  1150. }
  1151. return deferred;
  1152. };
  1153. /**
  1154. * Checks if the value is likely a promise (has a 'then' function).
  1155. * @return {boolean} true if value is thenable
  1156. */
  1157. Promise.isPromise = function Promise_isPromise(value) {
  1158. return value && typeof value.then === 'function';
  1159. };
  1160. /**
  1161. * Creates resolved promise
  1162. * @param value resolve value
  1163. * @returns {Promise}
  1164. */
  1165. Promise.resolve = function Promise_resolve(value) {
  1166. return new Promise(function (resolve) { resolve(value); });
  1167. };
  1168. /**
  1169. * Creates rejected promise
  1170. * @param reason rejection value
  1171. * @returns {Promise}
  1172. */
  1173. Promise.reject = function Promise_reject(reason) {
  1174. return new Promise(function (resolve, reject) { reject(reason); });
  1175. };
  1176. Promise.prototype = {
  1177. _status: null,
  1178. _value: null,
  1179. _handlers: null,
  1180. _unhandledRejection: null,
  1181. _updateStatus: function Promise__updateStatus(status, value) {
  1182. if (this._status === STATUS_RESOLVED ||
  1183. this._status === STATUS_REJECTED) {
  1184. return;
  1185. }
  1186. if (status === STATUS_RESOLVED &&
  1187. Promise.isPromise(value)) {
  1188. value.then(this._updateStatus.bind(this, STATUS_RESOLVED),
  1189. this._updateStatus.bind(this, STATUS_REJECTED));
  1190. return;
  1191. }
  1192. this._status = status;
  1193. this._value = value;
  1194. if (status === STATUS_REJECTED && this._handlers.length === 0) {
  1195. this._unhandledRejection = true;
  1196. HandlerManager.addUnhandledRejection(this);
  1197. }
  1198. HandlerManager.scheduleHandlers(this);
  1199. },
  1200. _resolve: function Promise_resolve(value) {
  1201. this._updateStatus(STATUS_RESOLVED, value);
  1202. },
  1203. _reject: function Promise_reject(reason) {
  1204. this._updateStatus(STATUS_REJECTED, reason);
  1205. },
  1206. then: function Promise_then(onResolve, onReject) {
  1207. var nextPromise = new Promise(function (resolve, reject) {
  1208. this.resolve = resolve;
  1209. this.reject = reject;
  1210. });
  1211. this._handlers.push({
  1212. thisPromise: this,
  1213. onResolve: onResolve,
  1214. onReject: onReject,
  1215. nextPromise: nextPromise
  1216. });
  1217. HandlerManager.scheduleHandlers(this);
  1218. return nextPromise;
  1219. },
  1220. catch: function Promise_catch(onReject) {
  1221. return this.then(undefined, onReject);
  1222. }
  1223. };
  1224. globalScope.Promise = Promise;
  1225. //#else
  1226. //throw new Error('DOM Promise is not present');
  1227. //#endif
  1228. })();
  1229. var StatTimer = (function StatTimerClosure() {
  1230. function rpad(str, pad, length) {
  1231. while (str.length < length) {
  1232. str += pad;
  1233. }
  1234. return str;
  1235. }
  1236. function StatTimer() {
  1237. this.started = {};
  1238. this.times = [];
  1239. this.enabled = true;
  1240. }
  1241. StatTimer.prototype = {
  1242. time: function StatTimer_time(name) {
  1243. if (!this.enabled) {
  1244. return;
  1245. }
  1246. if (name in this.started) {
  1247. warn('Timer is already running for ' + name);
  1248. }
  1249. this.started[name] = Date.now();
  1250. },
  1251. timeEnd: function StatTimer_timeEnd(name) {
  1252. if (!this.enabled) {
  1253. return;
  1254. }
  1255. if (!(name in this.started)) {
  1256. warn('Timer has not been started for ' + name);
  1257. }
  1258. this.times.push({
  1259. 'name': name,
  1260. 'start': this.started[name],
  1261. 'end': Date.now()
  1262. });
  1263. // Remove timer from started so it can be called again.
  1264. delete this.started[name];
  1265. },
  1266. toString: function StatTimer_toString() {
  1267. var i, ii;
  1268. var times = this.times;
  1269. var out = '';
  1270. // Find the longest name for padding purposes.
  1271. var longest = 0;
  1272. for (i = 0, ii = times.length; i < ii; ++i) {
  1273. var name = times[i]['name'];
  1274. if (name.length > longest) {
  1275. longest = name.length;
  1276. }
  1277. }
  1278. for (i = 0, ii = times.length; i < ii; ++i) {
  1279. var span = times[i];
  1280. var duration = span.end - span.start;
  1281. out += rpad(span['name'], ' ', longest) + ' ' + duration + 'ms\n';
  1282. }
  1283. return out;
  1284. }
  1285. };
  1286. return StatTimer;
  1287. })();
  1288. PDFJS.createBlob = function createBlob(data, contentType) {
  1289. if (typeof Blob !== 'undefined') {
  1290. return new Blob([data], { type: contentType });
  1291. }
  1292. // Blob builder is deprecated in FF14 and removed in FF18.
  1293. var bb = new MozBlobBuilder();
  1294. bb.append(data);
  1295. return bb.getBlob(contentType);
  1296. };
  1297. PDFJS.createObjectURL = (function createObjectURLClosure() {
  1298. // Blob/createObjectURL is not available, falling back to data schema.
  1299. var digits =
  1300. 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=';
  1301. return function createObjectURL(data, contentType) {
  1302. if (!PDFJS.disableCreateObjectURL &&
  1303. typeof URL !== 'undefined' && URL.createObjectURL) {
  1304. var blob = PDFJS.createBlob(data, contentType);
  1305. return URL.createObjectURL(blob);
  1306. }
  1307. var buffer = 'data:' + contentType + ';base64,';
  1308. for (var i = 0, ii = data.length; i < ii; i += 3) {
  1309. var b1 = data[i] & 0xFF;
  1310. var b2 = data[i + 1] & 0xFF;
  1311. var b3 = data[i + 2] & 0xFF;
  1312. var d1 = b1 >> 2, d2 = ((b1 & 3) << 4) | (b2 >> 4);
  1313. var d3 = i + 1 < ii ? ((b2 & 0xF) << 2) | (b3 >> 6) : 64;
  1314. var d4 = i + 2 < ii ? (b3 & 0x3F) : 64;
  1315. buffer += digits[d1] + digits[d2] + digits[d3] + digits[d4];
  1316. }
  1317. return buffer;
  1318. };
  1319. })();
  1320. function MessageHandler(name, comObj) {
  1321. this.name = name;
  1322. this.comObj = comObj;
  1323. this.callbackIndex = 1;
  1324. this.postMessageTransfers = true;
  1325. var callbacksCapabilities = this.callbacksCapabilities = {};
  1326. var ah = this.actionHandler = {};
  1327. ah['console_log'] = [function ahConsoleLog(data) {
  1328. console.log.apply(console, data);
  1329. }];
  1330. ah['console_error'] = [function ahConsoleError(data) {
  1331. console.error.apply(console, data);
  1332. }];
  1333. ah['_unsupported_feature'] = [function ah_unsupportedFeature(data) {
  1334. UnsupportedManager.notify(data);
  1335. }];
  1336. comObj.onmessage = function messageHandlerComObjOnMessage(event) {
  1337. var data = event.data;
  1338. if (data.isReply) {
  1339. var callbackId = data.callbackId;
  1340. if (data.callbackId in callbacksCapabilities) {
  1341. var callback = callbacksCapabilities[callbackId];
  1342. delete callbacksCapabilities[callbackId];
  1343. if ('error' in data) {
  1344. callback.reject(data.error);
  1345. } else {
  1346. callback.resolve(data.data);
  1347. }
  1348. } else {
  1349. error('Cannot resolve callback ' + callbackId);
  1350. }
  1351. } else if (data.action in ah) {
  1352. var action = ah[data.action];
  1353. if (data.callbackId) {
  1354. Promise.resolve().then(function () {
  1355. return action[0].call(action[1], data.data);
  1356. }).then(function (result) {
  1357. comObj.postMessage({
  1358. isReply: true,
  1359. callbackId: data.callbackId,
  1360. data: result
  1361. });
  1362. }, function (reason) {
  1363. comObj.postMessage({
  1364. isReply: true,
  1365. callbackId: data.callbackId,
  1366. error: reason
  1367. });
  1368. });
  1369. } else {
  1370. action[0].call(action[1], data.data);
  1371. }
  1372. } else {
  1373. error('Unknown action from worker: ' + data.action);
  1374. }
  1375. };
  1376. }
  1377. MessageHandler.prototype = {
  1378. on: function messageHandlerOn(actionName, handler, scope) {
  1379. var ah = this.actionHandler;
  1380. if (ah[actionName]) {
  1381. error('There is already an actionName called "' + actionName + '"');
  1382. }
  1383. ah[actionName] = [handler, scope];
  1384. },
  1385. /**
  1386. * Sends a message to the comObj to invoke the action with the supplied data.
  1387. * @param {String} actionName Action to call.
  1388. * @param {JSON} data JSON data to send.
  1389. * @param {Array} [transfers] Optional list of transfers/ArrayBuffers
  1390. */
  1391. send: function messageHandlerSend(actionName, data, transfers) {
  1392. var message = {
  1393. action: actionName,
  1394. data: data
  1395. };
  1396. this.postMessage(message, transfers);
  1397. },
  1398. /**
  1399. * Sends a message to the comObj to invoke the action with the supplied data.
  1400. * Expects that other side will callback with the response.
  1401. * @param {String} actionName Action to call.
  1402. * @param {JSON} data JSON data to send.
  1403. * @param {Array} [transfers] Optional list of transfers/ArrayBuffers.
  1404. * @returns {Promise} Promise to be resolved with response data.
  1405. */
  1406. sendWithPromise:
  1407. function messageHandlerSendWithPromise(actionName, data, transfers) {
  1408. var callbackId = this.callbackIndex++;
  1409. var message = {
  1410. action: actionName,
  1411. data: data,
  1412. callbackId: callbackId
  1413. };
  1414. var capability = createPromiseCapability();
  1415. this.callbacksCapabilities[callbackId] = capability;
  1416. try {
  1417. this.postMessage(message, transfers);
  1418. } catch (e) {
  1419. capability.reject(e);
  1420. }
  1421. return capability.promise;
  1422. },
  1423. /**
  1424. * Sends raw message to the comObj.
  1425. * @private
  1426. * @param message {Object} Raw message.
  1427. * @param transfers List of transfers/ArrayBuffers, or undefined.
  1428. */
  1429. postMessage: function (message, transfers) {
  1430. if (transfers && this.postMessageTransfers) {
  1431. this.comObj.postMessage(message, transfers);
  1432. } else {
  1433. this.comObj.postMessage(message);
  1434. }
  1435. }
  1436. };
  1437. function loadJpegStream(id, imageUrl, objs) {
  1438. var img = new Image();
  1439. img.onload = (function loadJpegStream_onloadClosure() {
  1440. objs.resolve(id, img);
  1441. });
  1442. img.onerror = (function loadJpegStream_onerrorClosure() {
  1443. objs.resolve(id, null);
  1444. warn('Error during JPEG image loading');
  1445. });
  1446. img.src = imageUrl;
  1447. }
  1448. //#if (FIREFOX || MOZCENTRAL)
  1449. //
  1450. //Components.utils.import('resource://gre/modules/Services.jsm');
  1451. //
  1452. //var EXPORTED_SYMBOLS = ['NetworkManager'];
  1453. //
  1454. //var console = {
  1455. // log: function console_log(aMsg) {
  1456. // var msg = 'network.js: ' + (aMsg.join ? aMsg.join('') : aMsg);
  1457. // Services.console.logStringMessage(msg);
  1458. // // TODO(mack): dump() doesn't seem to work here...
  1459. // dump(msg + '\n');
  1460. // }
  1461. //}
  1462. //#endif
  1463. var NetworkManager = (function NetworkManagerClosure() {
  1464. var OK_RESPONSE = 200;
  1465. var PARTIAL_CONTENT_RESPONSE = 206;
  1466. function NetworkManager(url, args) {
  1467. this.url = url;
  1468. args = args || {};
  1469. this.isHttp = /^https?:/i.test(url);
  1470. this.httpHeaders = (this.isHttp && args.httpHeaders) || {};
  1471. this.withCredentials = args.withCredentials || false;
  1472. this.getXhr = args.getXhr ||
  1473. function NetworkManager_getXhr() {
  1474. //#if B2G
  1475. // return new XMLHttpRequest({ mozSystem: true });
  1476. //#else
  1477. return new XMLHttpRequest();
  1478. //#endif
  1479. };
  1480. this.currXhrId = 0;
  1481. this.pendingRequests = {};
  1482. this.loadedRequests = {};
  1483. }
  1484. function getArrayBuffer(xhr) {
  1485. var data = xhr.response;
  1486. if (typeof data !== 'string') {
  1487. return data;
  1488. }
  1489. var length = data.length;
  1490. var array = new Uint8Array(length);
  1491. for (var i = 0; i < length; i++) {
  1492. array[i] = data.charCodeAt(i) & 0xFF;
  1493. }
  1494. return array.buffer;
  1495. }
  1496. NetworkManager.prototype = {
  1497. requestRange: function NetworkManager_requestRange(begin, end, listeners) {
  1498. var args = {
  1499. begin: begin,
  1500. end: end
  1501. };
  1502. for (var prop in listeners) {
  1503. args[prop] = listeners[prop];
  1504. }
  1505. return this.request(args);
  1506. },
  1507. requestFull: function NetworkManager_requestFull(listeners) {
  1508. return this.request(listeners);
  1509. },
  1510. request: function NetworkManager_request(args) {
  1511. var xhr = this.getXhr();
  1512. var xhrId = this.currXhrId++;
  1513. var pendingRequest = this.pendingRequests[xhrId] = {
  1514. xhr: xhr
  1515. };
  1516. xhr.open('GET', this.url);
  1517. xhr.withCredentials = this.withCredentials;
  1518. for (var property in this.httpHeaders) {
  1519. var value = this.httpHeaders[property];
  1520. if (typeof value === 'undefined') {
  1521. continue;
  1522. }
  1523. xhr.setRequestHeader(property, value);
  1524. }
  1525. if (this.isHttp && 'begin' in args && 'end' in args) {
  1526. var rangeStr = args.begin + '-' + (args.end - 1);
  1527. xhr.setRequestHeader('Range', 'bytes=' + rangeStr);
  1528. pendingRequest.expectedStatus = 206;
  1529. } else {
  1530. pendingRequest.expectedStatus = 200;
  1531. }
  1532. if (args.onProgressiveData) {
  1533. // Some legacy browsers might throw an exception.
  1534. try {
  1535. xhr.responseType = 'moz-chunked-arraybuffer';
  1536. } catch(e) {}
  1537. if (xhr.responseType === 'moz-chunked-arraybuffer') {
  1538. pendingRequest.onProgressiveData = args.onProgressiveData;
  1539. pendingRequest.mozChunked = true;
  1540. } else {
  1541. xhr.responseType = 'arraybuffer';
  1542. }
  1543. } else {
  1544. xhr.responseType = 'arraybuffer';
  1545. }
  1546. if (args.onError) {
  1547. xhr.onerror = function(evt) {
  1548. args.onError(xhr.status);
  1549. };
  1550. }
  1551. xhr.onreadystatechange = this.onStateChange.bind(this, xhrId);
  1552. xhr.onprogress = this.onProgress.bind(this, xhrId);
  1553. pendingRequest.onHeadersReceived = args.onHeadersReceived;
  1554. pendingRequest.onDone = args.onDone;
  1555. pendingRequest.onError = args.onError;
  1556. pendingRequest.onProgress = args.onProgress;
  1557. xhr.send(null);
  1558. return xhrId;
  1559. },
  1560. onProgress: function NetworkManager_onProgress(xhrId, evt) {
  1561. var pendingRequest = this.pendingRequests[xhrId];
  1562. if (!pendingRequest) {
  1563. // Maybe abortRequest was called...
  1564. return;
  1565. }
  1566. if (pendingRequest.mozChunked) {
  1567. var chunk = getArrayBuffer(pendingRequest.xhr);
  1568. pendingRequest.onProgressiveData(chunk);
  1569. }
  1570. var onProgress = pendingRequest.onProgress;
  1571. if (onProgress) {
  1572. onProgress(evt);
  1573. }
  1574. },
  1575. onStateChange: function NetworkManager_onStateChange(xhrId, evt) {
  1576. var pendingRequest = this.pendingRequests[xhrId];
  1577. if (!pendingRequest) {
  1578. // Maybe abortRequest was called...
  1579. return;
  1580. }
  1581. var xhr = pendingRequest.xhr;
  1582. if (xhr.readyState >= 2 && pendingRequest.onHeadersReceived) {
  1583. pendingRequest.onHeadersReceived();
  1584. delete pendingRequest.onHeadersReceived;
  1585. }
  1586. if (xhr.readyState !== 4) {
  1587. return;
  1588. }
  1589. if (!(xhrId in this.pendingRequests)) {
  1590. // The XHR request might have been aborted in onHeadersReceived()
  1591. // callback, in which case we should abort request
  1592. return;
  1593. }
  1594. delete this.pendingRequests[xhrId];
  1595. // success status == 0 can be on ftp, file and other protocols
  1596. if (xhr.status === 0 && this.isHttp) {
  1597. if (pendingRequest.onError) {
  1598. pendingRequest.onError(xhr.status);
  1599. }
  1600. return;
  1601. }
  1602. var xhrStatus = xhr.status || OK_RESPONSE;
  1603. // From http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.35.2:
  1604. // "A server MAY ignore the Range header". This means it's possible to
  1605. // get a 200 rather than a 206 response from a range request.
  1606. var ok_response_on_range_request =
  1607. xhrStatus === OK_RESPONSE &&
  1608. pendingRequest.expectedStatus === PARTIAL_CONTENT_RESPONSE;
  1609. if (!ok_response_on_range_request &&
  1610. xhrStatus !== pendingRequest.expectedStatus) {
  1611. if (pendingRequest.onError) {
  1612. pendingRequest.onError(xhr.status);
  1613. }
  1614. return;
  1615. }
  1616. this.loadedRequests[xhrId] = true;
  1617. var chunk = getArrayBuffer(xhr);
  1618. if (xhrStatus === PARTIAL_CONTENT_RESPONSE) {
  1619. var rangeHeader = xhr.getResponseHeader('Content-Range');
  1620. var matches = /bytes (\d+)-(\d+)\/(\d+)/.exec(rangeHeader);
  1621. var begin = parseInt(matches[1], 10);
  1622. pendingRequest.onDone({
  1623. begin: begin,
  1624. chunk: chunk
  1625. });
  1626. } else if (pendingRequest.onProgressiveData) {
  1627. pendingRequest.onDone(null);
  1628. } else {
  1629. pendingRequest.onDone({
  1630. begin: 0,
  1631. chunk: chunk
  1632. });
  1633. }
  1634. },
  1635. hasPendingRequests: function NetworkManager_hasPendingRequests() {
  1636. for (var xhrId in this.pendingRequests) {
  1637. return true;
  1638. }
  1639. return false;
  1640. },
  1641. getRequestXhr: function NetworkManager_getXhr(xhrId) {
  1642. return this.pendingRequests[xhrId].xhr;
  1643. },
  1644. isStreamingRequest: function NetworkManager_isStreamingRequest(xhrId) {
  1645. return !!(this.pendingRequests[xhrId].onProgressiveData);
  1646. },
  1647. isPendingRequest: function NetworkManager_isPendingRequest(xhrId) {
  1648. return xhrId in this.pendingRequests;
  1649. },
  1650. isLoadedRequest: function NetworkManager_isLoadedRequest(xhrId) {
  1651. return xhrId in this.loadedRequests;
  1652. },
  1653. abortAllRequests: function NetworkManager_abortAllRequests() {
  1654. for (var xhrId in this.pendingRequests) {
  1655. this.abortRequest(xhrId | 0);
  1656. }
  1657. },
  1658. abortRequest: function NetworkManager_abortRequest(xhrId) {
  1659. var xhr = this.pendingRequests[xhrId].xhr;
  1660. delete this.pendingRequests[xhrId];
  1661. xhr.abort();
  1662. }
  1663. };
  1664. return NetworkManager;
  1665. })();
  1666. var ChunkedStream = (function ChunkedStreamClosure() {
  1667. function ChunkedStream(length, chunkSize, manager) {
  1668. this.bytes = new Uint8Array(length);
  1669. this.start = 0;
  1670. this.pos = 0;
  1671. this.end = length;
  1672. this.chunkSize = chunkSize;
  1673. this.loadedChunks = [];
  1674. this.numChunksLoaded = 0;
  1675. this.numChunks = Math.ceil(length / chunkSize);
  1676. this.manager = manager;
  1677. this.progressiveDataLength = 0;
  1678. this.lastSuccessfulEnsureByteChunk = -1; // a single-entry cache
  1679. }
  1680. // required methods for a stream. if a particular stream does not
  1681. // implement these, an error should be thrown
  1682. ChunkedStream.prototype = {
  1683. getMissingChunks: function ChunkedStream_getMissingChunks() {
  1684. var chunks = [];
  1685. for (var chunk = 0, n = this.numChunks; chunk < n; ++chunk) {
  1686. if (!this.loadedChunks[chunk]) {
  1687. chunks.push(chunk);
  1688. }
  1689. }
  1690. return chunks;
  1691. },
  1692. getBaseStreams: function ChunkedStream_getBaseStreams() {
  1693. return [this];
  1694. },
  1695. allChunksLoaded: function ChunkedStream_allChunksLoaded() {
  1696. return this.numChunksLoaded === this.numChunks;
  1697. },
  1698. onReceiveData: function ChunkedStream_onReceiveData(begin, chunk) {
  1699. var end = begin + chunk.byteLength;
  1700. assert(begin % this.chunkSize === 0, 'Bad begin offset: ' + begin);
  1701. // Using this.length is inaccurate here since this.start can be moved
  1702. // See ChunkedStream.moveStart()
  1703. var length = this.bytes.length;
  1704. assert(end % this.chunkSize === 0 || end === length,
  1705. 'Bad end offset: ' + end);
  1706. this.bytes.set(new Uint8Array(chunk), begin);
  1707. var chunkSize = this.chunkSize;
  1708. var beginChunk = Math.floor(begin / chunkSize);
  1709. var endChunk = Math.floor((end - 1) / chunkSize) + 1;
  1710. var curChunk;
  1711. for (curChunk = beginChunk; curChunk < endChunk; ++curChunk) {
  1712. if (!this.loadedChunks[curChunk]) {
  1713. this.loadedChunks[curChunk] = true;
  1714. ++this.numChunksLoaded;
  1715. }
  1716. }
  1717. },
  1718. onReceiveProgressiveData:
  1719. function ChunkedStream_onReceiveProgressiveData(data) {
  1720. var position = this.progressiveDataLength;
  1721. var beginChunk = Math.floor(position / this.chunkSize);
  1722. this.bytes.set(new Uint8Array(data), position);
  1723. position += data.byteLength;
  1724. this.progressiveDataLength = position;
  1725. var endChunk = position >= this.end ? this.numChunks :
  1726. Math.floor(position / this.chunkSize);
  1727. var curChunk;
  1728. for (curChunk = beginChunk; curChunk < endChunk; ++curChunk) {
  1729. if (!this.loadedChunks[curChunk]) {
  1730. this.loadedChunks[curChunk] = true;
  1731. ++this.numChunksLoaded;
  1732. }
  1733. }
  1734. },
  1735. ensureByte: function ChunkedStream_ensureByte(pos) {
  1736. var chunk = Math.floor(pos / this.chunkSize);
  1737. if (chunk === this.lastSuccessfulEnsureByteChunk) {
  1738. return;
  1739. }
  1740. if (!this.loadedChunks[chunk]) {
  1741. throw new MissingDataException(pos, pos + 1);
  1742. }
  1743. this.lastSuccessfulEnsureByteChunk = chunk;
  1744. },
  1745. ensureRange: function ChunkedStream_ensureRange(begin, end) {
  1746. if (begin >= end) {
  1747. return;
  1748. }
  1749. if (end <= this.progressiveDataLength) {
  1750. return;
  1751. }
  1752. var chunkSize = this.chunkSize;
  1753. var beginChunk = Math.floor(begin / chunkSize);
  1754. var endChunk = Math.floor((end - 1) / chunkSize) + 1;
  1755. for (var chunk = beginChunk; chunk < endChunk; ++chunk) {
  1756. if (!this.loadedChunks[chunk]) {
  1757. throw new MissingDataException(begin, end);
  1758. }
  1759. }
  1760. },
  1761. nextEmptyChunk: function ChunkedStream_nextEmptyChunk(beginChunk) {
  1762. var chunk, n;
  1763. for (chunk = beginChunk, n = this.numChunks; chunk < n; ++chunk) {
  1764. if (!this.loadedChunks[chunk]) {
  1765. return chunk;
  1766. }
  1767. }
  1768. // Wrap around to beginning
  1769. for (chunk = 0; chunk < beginChunk; ++chunk) {
  1770. if (!this.loadedChunks[chunk]) {
  1771. return chunk;
  1772. }
  1773. }
  1774. return null;
  1775. },
  1776. hasChunk: function ChunkedStream_hasChunk(chunk) {
  1777. return !!this.loadedChunks[chunk];
  1778. },
  1779. get length() {
  1780. return this.end - this.start;
  1781. },
  1782. get isEmpty() {
  1783. return this.length === 0;
  1784. },
  1785. getByte: function ChunkedStream_getByte() {
  1786. var pos = this.pos;
  1787. if (pos >= this.end) {
  1788. return -1;
  1789. }
  1790. this.ensureByte(pos);
  1791. return this.bytes[this.pos++];
  1792. },
  1793. getUint16: function ChunkedStream_getUint16() {
  1794. var b0 = this.getByte();
  1795. var b1 = this.getByte();
  1796. if (b0 === -1 || b1 === -1) {
  1797. return -1;
  1798. }
  1799. return (b0 << 8) + b1;
  1800. },
  1801. getInt32: function ChunkedStream_getInt32() {
  1802. var b0 = this.getByte();
  1803. var b1 = this.getByte();
  1804. var b2 = this.getByte();
  1805. var b3 = this.getByte();
  1806. return (b0 << 24) + (b1 << 16) + (b2 << 8) + b3;
  1807. },
  1808. // returns subarray of original buffer
  1809. // should only be read
  1810. getBytes: function ChunkedStream_getBytes(length) {
  1811. var bytes = this.bytes;
  1812. var pos = this.pos;
  1813. var strEnd = this.end;
  1814. if (!length) {
  1815. this.ensureRange(pos, strEnd);
  1816. return bytes.subarray(pos, strEnd);
  1817. }
  1818. var end = pos + length;
  1819. if (end > strEnd) {
  1820. end = strEnd;
  1821. }
  1822. this.ensureRange(pos, end);
  1823. this.pos = end;
  1824. return bytes.subarray(pos, end);
  1825. },
  1826. peekByte: function ChunkedStream_peekByte() {
  1827. var peekedByte = this.getByte();
  1828. this.pos--;
  1829. return peekedByte;
  1830. },
  1831. peekBytes: function ChunkedStream_peekBytes(length) {
  1832. var bytes = this.getBytes(length);
  1833. this.pos -= bytes.length;
  1834. return bytes;
  1835. },
  1836. getByteRange: function ChunkedStream_getBytes(begin, end) {
  1837. this.ensureRange(begin, end);
  1838. return this.bytes.subarray(begin, end);
  1839. },
  1840. skip: function ChunkedStream_skip(n) {
  1841. if (!n) {
  1842. n = 1;
  1843. }
  1844. this.pos += n;
  1845. },
  1846. reset: function ChunkedStream_reset() {
  1847. this.pos = this.start;
  1848. },
  1849. moveStart: function ChunkedStream_moveStart() {
  1850. this.start = this.pos;
  1851. },
  1852. makeSubStream: function ChunkedStream_makeSubStream(start, length, dict) {
  1853. this.ensureRange(start, start + length);
  1854. function ChunkedStreamSubstream() {}
  1855. ChunkedStreamSubstream.prototype = Object.create(this);
  1856. ChunkedStreamSubstream.prototype.getMissingChunks = function() {
  1857. var chunkSize = this.chunkSize;
  1858. var beginChunk = Math.floor(this.start / chunkSize);
  1859. var endChunk = Math.floor((this.end - 1) / chunkSize) + 1;
  1860. var missingChunks = [];
  1861. for (var chunk = beginChunk; chunk < endChunk; ++chunk) {
  1862. if (!this.loadedChunks[chunk]) {
  1863. missingChunks.push(chunk);
  1864. }
  1865. }
  1866. return missingChunks;
  1867. };
  1868. var subStream = new ChunkedStreamSubstream();
  1869. subStream.pos = subStream.start = start;
  1870. subStream.end = start + length || this.end;
  1871. subStream.dict = dict;
  1872. return subStream;
  1873. },
  1874. isStream: true
  1875. };
  1876. return ChunkedStream;
  1877. })();
  1878. var ChunkedStreamManager = (function ChunkedStreamManagerClosure() {
  1879. function ChunkedStreamManager(length, chunkSize, url, args) {
  1880. this.stream = new ChunkedStream(length, chunkSize, this);
  1881. this.length = length;
  1882. this.chunkSize = chunkSize;
  1883. this.url = url;
  1884. this.disableAutoFetch = args.disableAutoFetch;
  1885. var msgHandler = this.msgHandler = args.msgHandler;
  1886. if (args.chunkedViewerLoading) {
  1887. msgHandler.on('OnDataRange', this.onReceiveData.bind(this));
  1888. msgHandler.on('OnDataProgress', this.onProgress.bind(this));
  1889. this.sendRequest = function ChunkedStreamManager_sendRequest(begin, end) {
  1890. msgHandler.send('RequestDataRange', { begin: begin, end: end });
  1891. };
  1892. } else {
  1893. var getXhr = function getXhr() {
  1894. //#if B2G
  1895. // return new XMLHttpRequest({ mozSystem: true });
  1896. //#else
  1897. return new XMLHttpRequest();
  1898. //#endif
  1899. };
  1900. this.networkManager = new NetworkManager(this.url, {
  1901. getXhr: getXhr,
  1902. httpHeaders: args.httpHeaders,
  1903. withCredentials: args.withCredentials
  1904. });
  1905. this.sendRequest = function ChunkedStreamManager_sendRequest(begin, end) {
  1906. this.networkManager.requestRange(begin, end, {
  1907. onDone: this.onReceiveData.bind(this),
  1908. onProgress: this.onProgress.bind(this)
  1909. });
  1910. };
  1911. }
  1912. this.currRequestId = 0;
  1913. this.chunksNeededByRequest = {};
  1914. this.requestsByChunk = {};
  1915. this.callbacksByRequest = {};
  1916. this.progressiveDataLength = 0;
  1917. this._loadedStreamCapability = createPromiseCapability();
  1918. if (args.initialData) {
  1919. this.onReceiveData({chunk: args.initialData});
  1920. }
  1921. }
  1922. ChunkedStreamManager.prototype = {
  1923. onLoadedStream: function ChunkedStreamManager_getLoadedStream() {
  1924. return this._loadedStreamCapability.promise;
  1925. },
  1926. // Get all the chunks that are not yet loaded and groups them into
  1927. // contiguous ranges to load in as few requests as possible
  1928. requestAllChunks: function ChunkedStreamManager_requestAllChunks() {
  1929. var missingChunks = this.stream.getMissingChunks();
  1930. this.requestChunks(missingChunks);
  1931. return this._loadedStreamCapability.promise;
  1932. },
  1933. requestChunks: function ChunkedStreamManager_requestChunks(chunks,
  1934. callback) {
  1935. var requestId = this.currRequestId++;
  1936. var chunksNeeded;
  1937. var i, ii;
  1938. this.chunksNeededByRequest[requestId] = chunksNeeded = {};
  1939. for (i = 0, ii = chunks.length; i < ii; i++) {
  1940. if (!this.stream.hasChunk(chunks[i])) {
  1941. chunksNeeded[chunks[i]] = true;
  1942. }
  1943. }
  1944. if (isEmptyObj(chunksNeeded)) {
  1945. if (callback) {
  1946. callback();
  1947. }
  1948. return;
  1949. }
  1950. this.callbacksByRequest[requestId] = callback;
  1951. var chunksToRequest = [];
  1952. for (var chunk in chunksNeeded) {
  1953. chunk = chunk | 0;
  1954. if (!(chunk in this.requestsByChunk)) {
  1955. this.requestsByChunk[chunk] = [];
  1956. chunksToRequest.push(chunk);
  1957. }
  1958. this.requestsByChunk[chunk].push(requestId);
  1959. }
  1960. if (!chunksToRequest.length) {
  1961. return;
  1962. }
  1963. var groupedChunksToRequest = this.groupChunks(chunksToRequest);
  1964. for (i = 0; i < groupedChunksToRequest.length; ++i) {
  1965. var groupedChunk = groupedChunksToRequest[i];
  1966. var begin = groupedChunk.beginChunk * this.chunkSize;
  1967. var end = Math.min(groupedChunk.endChunk * this.chunkSize, this.length);
  1968. this.sendRequest(begin, end);
  1969. }
  1970. },
  1971. getStream: function ChunkedStreamManager_getStream() {
  1972. return this.stream;
  1973. },
  1974. // Loads any chunks in the requested range that are not yet loaded
  1975. requestRange: function ChunkedStreamManager_requestRange(
  1976. begin, end, callback) {
  1977. end = Math.min(end, this.length);
  1978. var beginChunk = this.getBeginChunk(begin);
  1979. var endChunk = this.getEndChunk(end);
  1980. var chunks = [];
  1981. for (var chunk = beginChunk; chunk < endChunk; ++chunk) {
  1982. chunks.push(chunk);
  1983. }
  1984. this.requestChunks(chunks, callback);
  1985. },
  1986. requestRanges: function ChunkedStreamManager_requestRanges(ranges,
  1987. callback) {
  1988. ranges = ranges || [];
  1989. var chunksToRequest = [];
  1990. for (var i = 0; i < ranges.length; i++) {
  1991. var beginChunk = this.getBeginChunk(ranges[i].begin);
  1992. var endChunk = this.getEndChunk(ranges[i].end);
  1993. for (var chunk = beginChunk; chunk < endChunk; ++chunk) {
  1994. if (chunksToRequest.indexOf(chunk) < 0) {
  1995. chunksToRequest.push(chunk);
  1996. }
  1997. }
  1998. }
  1999. chunksToRequest.sort(function(a, b) { return a - b; });
  2000. this.requestChunks(chunksToRequest, callback);
  2001. },
  2002. // Groups a sorted array of chunks into as few continguous larger
  2003. // chunks as possible
  2004. groupChunks: function ChunkedStreamManager_groupChunks(chunks) {
  2005. var groupedChunks = [];
  2006. var beginChunk = -1;
  2007. var prevChunk = -1;
  2008. for (var i = 0; i < chunks.length; ++i) {
  2009. var chunk = chunks[i];
  2010. if (beginChunk < 0) {
  2011. beginChunk = chunk;
  2012. }
  2013. if (prevChunk >= 0 && prevChunk + 1 !== chunk) {
  2014. groupedChunks.push({ beginChunk: beginChunk,
  2015. endChunk: prevChunk + 1 });
  2016. beginChunk = chunk;
  2017. }
  2018. if (i + 1 === chunks.length) {
  2019. groupedChunks.push({ beginChunk: beginChunk,
  2020. endChunk: chunk + 1 });
  2021. }
  2022. prevChunk = chunk;
  2023. }
  2024. return groupedChunks;
  2025. },
  2026. onProgress: function ChunkedStreamManager_onProgress(args) {
  2027. var bytesLoaded = (this.stream.numChunksLoaded * this.chunkSize +
  2028. args.loaded);
  2029. this.msgHandler.send('DocProgress', {
  2030. loaded: bytesLoaded,
  2031. total: this.length
  2032. });
  2033. },
  2034. onReceiveData: function ChunkedStreamManager_onReceiveData(args) {
  2035. var chunk = args.chunk;
  2036. var isProgressive = args.begin === undefined;
  2037. var begin = isProgressive ? this.progressiveDataLength : args.begin;
  2038. var end = begin + chunk.byteLength;
  2039. var beginChunk = Math.floor(begin / this.chunkSize);
  2040. var endChunk = end < this.length ? Math.floor(end / this.chunkSize) :
  2041. Math.ceil(end / this.chunkSize);
  2042. if (isProgressive) {
  2043. this.stream.onReceiveProgressiveData(chunk);
  2044. this.progressiveDataLength = end;
  2045. } else {
  2046. this.stream.onReceiveData(begin, chunk);
  2047. }
  2048. if (this.stream.allChunksLoaded()) {
  2049. this._loadedStreamCapability.resolve(this.stream);
  2050. }
  2051. var loadedRequests = [];
  2052. var i, requestId;
  2053. for (chunk = beginChunk; chunk < endChunk; ++chunk) {
  2054. // The server might return more chunks than requested
  2055. var requestIds = this.requestsByChunk[chunk] || [];
  2056. delete this.requestsByChunk[chunk];
  2057. for (i = 0; i < requestIds.length; ++i) {
  2058. requestId = requestIds[i];
  2059. var chunksNeeded = this.chunksNeededByRequest[requestId];
  2060. if (chunk in chunksNeeded) {
  2061. delete chunksNeeded[chunk];
  2062. }
  2063. if (!isEmptyObj(chunksNeeded)) {
  2064. continue;
  2065. }
  2066. loadedRequests.push(requestId);
  2067. }
  2068. }
  2069. // If there are no pending requests, automatically fetch the next
  2070. // unfetched chunk of the PDF
  2071. if (!this.disableAutoFetch && isEmptyObj(this.requestsByChunk)) {
  2072. var nextEmptyChunk;
  2073. if (this.stream.numChunksLoaded === 1) {
  2074. // This is a special optimization so that after fetching the first
  2075. // chunk, rather than fetching the second chunk, we fetch the last
  2076. // chunk.
  2077. var lastChunk = this.stream.numChunks - 1;
  2078. if (!this.stream.hasChunk(lastChunk)) {
  2079. nextEmptyChunk = lastChunk;
  2080. }
  2081. } else {
  2082. nextEmptyChunk = this.stream.nextEmptyChunk(endChunk);
  2083. }
  2084. if (isInt(nextEmptyChunk)) {
  2085. this.requestChunks([nextEmptyChunk]);
  2086. }
  2087. }
  2088. for (i = 0; i < loadedRequests.length; ++i) {
  2089. requestId = loadedRequests[i];
  2090. var callback = this.callbacksByRequest[requestId];
  2091. delete this.callbacksByRequest[requestId];
  2092. if (callback) {
  2093. callback();
  2094. }
  2095. }
  2096. this.msgHandler.send('DocProgress', {
  2097. loaded: this.stream.numChunksLoaded * this.chunkSize,
  2098. total: this.length
  2099. });
  2100. },
  2101. onError: function ChunkedStreamManager_onError(err) {
  2102. this._loadedStreamCapability.reject(err);
  2103. },
  2104. getBeginChunk: function ChunkedStreamManager_getBeginChunk(begin) {
  2105. var chunk = Math.floor(begin / this.chunkSize);
  2106. return chunk;
  2107. },
  2108. getEndChunk: function ChunkedStreamManager_getEndChunk(end) {
  2109. if (end % this.chunkSize === 0) {
  2110. return end / this.chunkSize;
  2111. }
  2112. // 0 -> 0
  2113. // 1 -> 1
  2114. // 99 -> 1
  2115. // 100 -> 1
  2116. // 101 -> 2
  2117. var chunk = Math.floor((end - 1) / this.chunkSize) + 1;
  2118. return chunk;
  2119. }
  2120. };
  2121. return ChunkedStreamManager;
  2122. })();
  2123. // The maximum number of bytes fetched per range request
  2124. var RANGE_CHUNK_SIZE = 65536;
  2125. // TODO(mack): Make use of PDFJS.Util.inherit() when it becomes available
  2126. var BasePdfManager = (function BasePdfManagerClosure() {
  2127. function BasePdfManager() {
  2128. throw new Error('Cannot initialize BaseManagerManager');
  2129. }
  2130. BasePdfManager.prototype = {
  2131. onLoadedStream: function BasePdfManager_onLoadedStream() {
  2132. throw new NotImplementedException();
  2133. },
  2134. ensureDoc: function BasePdfManager_ensureDoc(prop, args) {
  2135. return this.ensure(this.pdfDocument, prop, args);
  2136. },
  2137. ensureXRef: function BasePdfManager_ensureXRef(prop, args) {
  2138. return this.ensure(this.pdfDocument.xref, prop, args);
  2139. },
  2140. ensureCatalog: function BasePdfManager_ensureCatalog(prop, args) {
  2141. return this.ensure(this.pdfDocument.catalog, prop, args);
  2142. },
  2143. getPage: function BasePdfManager_pagePage(pageIndex) {
  2144. return this.pdfDocument.getPage(pageIndex);
  2145. },
  2146. cleanup: function BasePdfManager_cleanup() {
  2147. return this.pdfDocument.cleanup();
  2148. },
  2149. ensure: function BasePdfManager_ensure(obj, prop, args) {
  2150. return new NotImplementedException();
  2151. },
  2152. requestRange: function BasePdfManager_ensure(begin, end) {
  2153. return new NotImplementedException();
  2154. },
  2155. requestLoadedStream: function BasePdfManager_requestLoadedStream() {
  2156. return new NotImplementedException();
  2157. },
  2158. sendProgressiveData: function BasePdfManager_sendProgressiveData(chunk) {
  2159. return new NotImplementedException();
  2160. },
  2161. updatePassword: function BasePdfManager_updatePassword(password) {
  2162. this.pdfDocument.xref.password = this.password = password;
  2163. if (this._passwordChangedCapability) {
  2164. this._passwordChangedCapability.resolve();
  2165. }
  2166. },
  2167. passwordChanged: function BasePdfManager_passwordChanged() {
  2168. this._passwordChangedCapability = createPromiseCapability();
  2169. return this._passwordChangedCapability.promise;
  2170. },
  2171. terminate: function BasePdfManager_terminate() {
  2172. return new NotImplementedException();
  2173. }
  2174. };
  2175. return BasePdfManager;
  2176. })();
  2177. var LocalPdfManager = (function LocalPdfManagerClosure() {
  2178. function LocalPdfManager(data, password) {
  2179. var stream = new Stream(data);
  2180. this.pdfDocument = new PDFDocument(this, stream, password);
  2181. this._loadedStreamCapability = createPromiseCapability();
  2182. this._loadedStreamCapability.resolve(stream);
  2183. }
  2184. LocalPdfManager.prototype = Object.create(BasePdfManager.prototype);
  2185. LocalPdfManager.prototype.constructor = LocalPdfManager;
  2186. LocalPdfManager.prototype.ensure =
  2187. function LocalPdfManager_ensure(obj, prop, args) {
  2188. return new Promise(function (resolve, reject) {
  2189. try {
  2190. var value = obj[prop];
  2191. var result;
  2192. if (typeof value === 'function') {
  2193. result = value.apply(obj, args);
  2194. } else {
  2195. result = value;
  2196. }
  2197. resolve(result);
  2198. } catch (e) {
  2199. reject(e);
  2200. }
  2201. });
  2202. };
  2203. LocalPdfManager.prototype.requestRange =
  2204. function LocalPdfManager_requestRange(begin, end) {
  2205. return Promise.resolve();
  2206. };
  2207. LocalPdfManager.prototype.requestLoadedStream =
  2208. function LocalPdfManager_requestLoadedStream() {
  2209. };
  2210. LocalPdfManager.prototype.onLoadedStream =
  2211. function LocalPdfManager_getLoadedStream() {
  2212. return this._loadedStreamCapability.promise;
  2213. };
  2214. LocalPdfManager.prototype.terminate =
  2215. function LocalPdfManager_terminate() {
  2216. return;
  2217. };
  2218. return LocalPdfManager;
  2219. })();
  2220. var NetworkPdfManager = (function NetworkPdfManagerClosure() {
  2221. function NetworkPdfManager(args, msgHandler) {
  2222. this.msgHandler = msgHandler;
  2223. var params = {
  2224. msgHandler: msgHandler,
  2225. httpHeaders: args.httpHeaders,
  2226. withCredentials: args.withCredentials,
  2227. chunkedViewerLoading: args.chunkedViewerLoading,
  2228. disableAutoFetch: args.disableAutoFetch,
  2229. initialData: args.initialData
  2230. };
  2231. this.streamManager = new ChunkedStreamManager(args.length, RANGE_CHUNK_SIZE,
  2232. args.url, params);
  2233. this.pdfDocument = new PDFDocument(this, this.streamManager.getStream(),
  2234. args.password);
  2235. }
  2236. NetworkPdfManager.prototype = Object.create(BasePdfManager.prototype);
  2237. NetworkPdfManager.prototype.constructor = NetworkPdfManager;
  2238. NetworkPdfManager.prototype.ensure =
  2239. function NetworkPdfManager_ensure(obj, prop, args) {
  2240. var pdfManager = this;
  2241. return new Promise(function (resolve, reject) {
  2242. function ensureHelper() {
  2243. try {
  2244. var result;
  2245. var value = obj[prop];
  2246. if (typeof value === 'function') {
  2247. result = value.apply(obj, args);
  2248. } else {
  2249. result = value;
  2250. }
  2251. resolve(result);
  2252. } catch(e) {
  2253. if (!(e instanceof MissingDataException)) {
  2254. reject(e);
  2255. return;
  2256. }
  2257. pdfManager.streamManager.requestRange(e.begin, e.end, ensureHelper);
  2258. }
  2259. }
  2260. ensureHelper();
  2261. });
  2262. };
  2263. NetworkPdfManager.prototype.requestRange =
  2264. function NetworkPdfManager_requestRange(begin, end) {
  2265. return new Promise(function (resolve) {
  2266. this.streamManager.requestRange(begin, end, function() {
  2267. resolve();
  2268. });
  2269. }.bind(this));
  2270. };
  2271. NetworkPdfManager.prototype.requestLoadedStream =
  2272. function NetworkPdfManager_requestLoadedStream() {
  2273. this.streamManager.requestAllChunks();
  2274. };
  2275. NetworkPdfManager.prototype.sendProgressiveData =
  2276. function NetworkPdfManager_sendProgressiveData(chunk) {
  2277. this.streamManager.onReceiveData({ chunk: chunk });
  2278. };
  2279. NetworkPdfManager.prototype.onLoadedStream =
  2280. function NetworkPdfManager_getLoadedStream() {
  2281. return this.streamManager.onLoadedStream();
  2282. };
  2283. NetworkPdfManager.prototype.terminate =
  2284. function NetworkPdfManager_terminate() {
  2285. this.streamManager.networkManager.abortAllRequests();
  2286. };
  2287. return NetworkPdfManager;
  2288. })();
  2289. var Page = (function PageClosure() {
  2290. var LETTER_SIZE_MEDIABOX = [0, 0, 612, 792];
  2291. function Page(pdfManager, xref, pageIndex, pageDict, ref, fontCache) {
  2292. this.pdfManager = pdfManager;
  2293. this.pageIndex = pageIndex;
  2294. this.pageDict = pageDict;
  2295. this.xref = xref;
  2296. this.ref = ref;
  2297. this.fontCache = fontCache;
  2298. this.idCounters = {
  2299. obj: 0
  2300. };
  2301. this.resourcesPromise = null;
  2302. }
  2303. Page.prototype = {
  2304. getPageProp: function Page_getPageProp(key) {
  2305. return this.pageDict.get(key);
  2306. },
  2307. getInheritedPageProp: function Page_inheritPageProp(key) {
  2308. var dict = this.pageDict;
  2309. var value = dict.get(key);
  2310. while (value === undefined) {
  2311. dict = dict.get('Parent');
  2312. if (!dict) {
  2313. break;
  2314. }
  2315. value = dict.get(key);
  2316. }
  2317. return value;
  2318. },
  2319. get content() {
  2320. return this.getPageProp('Contents');
  2321. },
  2322. get resources() {
  2323. var value = this.getInheritedPageProp('Resources');
  2324. // For robustness: The spec states that a \Resources entry has to be
  2325. // present, but can be empty. Some document omit it still. In this case
  2326. // return an empty dictionary:
  2327. if (value === undefined) {
  2328. value = Dict.empty;
  2329. }
  2330. return shadow(this, 'resources', value);
  2331. },
  2332. get mediaBox() {
  2333. var obj = this.getInheritedPageProp('MediaBox');
  2334. // Reset invalid media box to letter size.
  2335. if (!isArray(obj) || obj.length !== 4) {
  2336. obj = LETTER_SIZE_MEDIABOX;
  2337. }
  2338. return shadow(this, 'mediaBox', obj);
  2339. },
  2340. get view() {
  2341. var mediaBox = this.mediaBox;
  2342. var cropBox = this.getInheritedPageProp('CropBox');
  2343. if (!isArray(cropBox) || cropBox.length !== 4) {
  2344. return shadow(this, 'view', mediaBox);
  2345. }
  2346. // From the spec, 6th ed., p.963:
  2347. // "The crop, bleed, trim, and art boxes should not ordinarily
  2348. // extend beyond the boundaries of the media box. If they do, they are
  2349. // effectively reduced to their intersection with the media box."
  2350. cropBox = Util.intersect(cropBox, mediaBox);
  2351. if (!cropBox) {
  2352. return shadow(this, 'view', mediaBox);
  2353. }
  2354. return shadow(this, 'view', cropBox);
  2355. },
  2356. get annotationRefs() {
  2357. return shadow(this, 'annotationRefs',
  2358. this.getInheritedPageProp('Annots'));
  2359. },
  2360. get rotate() {
  2361. var rotate = this.getInheritedPageProp('Rotate') || 0;
  2362. // Normalize rotation so it's a multiple of 90 and between 0 and 270
  2363. if (rotate % 90 !== 0) {
  2364. rotate = 0;
  2365. } else if (rotate >= 360) {
  2366. rotate = rotate % 360;
  2367. } else if (rotate < 0) {
  2368. // The spec doesn't cover negatives, assume its counterclockwise
  2369. // rotation. The following is the other implementation of modulo.
  2370. rotate = ((rotate % 360) + 360) % 360;
  2371. }
  2372. return shadow(this, 'rotate', rotate);
  2373. },
  2374. getContentStream: function Page_getContentStream() {
  2375. var content = this.content;
  2376. var stream;
  2377. if (isArray(content)) {
  2378. // fetching items
  2379. var xref = this.xref;
  2380. var i, n = content.length;
  2381. var streams = [];
  2382. for (i = 0; i < n; ++i) {
  2383. streams.push(xref.fetchIfRef(content[i]));
  2384. }
  2385. stream = new StreamsSequenceStream(streams);
  2386. } else if (isStream(content)) {
  2387. stream = content;
  2388. } else {
  2389. // replacing non-existent page content with empty one
  2390. stream = new NullStream();
  2391. }
  2392. return stream;
  2393. },
  2394. loadResources: function Page_loadResources(keys) {
  2395. if (!this.resourcesPromise) {
  2396. // TODO: add async getInheritedPageProp and remove this.
  2397. this.resourcesPromise = this.pdfManager.ensure(this, 'resources');
  2398. }
  2399. return this.resourcesPromise.then(function resourceSuccess() {
  2400. var objectLoader = new ObjectLoader(this.resources.map,
  2401. keys,
  2402. this.xref);
  2403. return objectLoader.load();
  2404. }.bind(this));
  2405. },
  2406. getOperatorList: function Page_getOperatorList(handler, intent) {
  2407. var self = this;
  2408. var pdfManager = this.pdfManager;
  2409. var contentStreamPromise = pdfManager.ensure(this, 'getContentStream',
  2410. []);
  2411. var resourcesPromise = this.loadResources([
  2412. 'ExtGState',
  2413. 'ColorSpace',
  2414. 'Pattern',
  2415. 'Shading',
  2416. 'XObject',
  2417. 'Font'
  2418. // ProcSet
  2419. // Properties
  2420. ]);
  2421. var partialEvaluator = new PartialEvaluator(pdfManager, this.xref,
  2422. handler, this.pageIndex,
  2423. 'p' + this.pageIndex + '_',
  2424. this.idCounters,
  2425. this.fontCache);
  2426. var dataPromises = Promise.all([contentStreamPromise, resourcesPromise]);
  2427. var pageListPromise = dataPromises.then(function(data) {
  2428. var contentStream = data[0];
  2429. var opList = new OperatorList(intent, handler, self.pageIndex);
  2430. handler.send('StartRenderPage', {
  2431. transparency: partialEvaluator.hasBlendModes(self.resources),
  2432. pageIndex: self.pageIndex,
  2433. intent: intent
  2434. });
  2435. return partialEvaluator.getOperatorList(contentStream, self.resources,
  2436. opList).then(function () {
  2437. return opList;
  2438. });
  2439. });
  2440. var annotationsPromise = pdfManager.ensure(this, 'annotations');
  2441. return Promise.all([pageListPromise, annotationsPromise]).then(
  2442. function(datas) {
  2443. var pageOpList = datas[0];
  2444. var annotations = datas[1];
  2445. if (annotations.length === 0) {
  2446. pageOpList.flush(true);
  2447. return pageOpList;
  2448. }
  2449. var annotationsReadyPromise = Annotation.appendToOperatorList(
  2450. annotations, pageOpList, pdfManager, partialEvaluator, intent);
  2451. return annotationsReadyPromise.then(function () {
  2452. pageOpList.flush(true);
  2453. return pageOpList;
  2454. });
  2455. });
  2456. },
  2457. extractTextContent: function Page_extractTextContent() {
  2458. var handler = {
  2459. on: function nullHandlerOn() {},
  2460. send: function nullHandlerSend() {}
  2461. };
  2462. var self = this;
  2463. var pdfManager = this.pdfManager;
  2464. var contentStreamPromise = pdfManager.ensure(this, 'getContentStream',
  2465. []);
  2466. var resourcesPromise = this.loadResources([
  2467. 'ExtGState',
  2468. 'XObject',
  2469. 'Font'
  2470. ]);
  2471. var dataPromises = Promise.all([contentStreamPromise,
  2472. resourcesPromise]);
  2473. return dataPromises.then(function(data) {
  2474. var contentStream = data[0];
  2475. var partialEvaluator = new PartialEvaluator(pdfManager, self.xref,
  2476. handler, self.pageIndex,
  2477. 'p' + self.pageIndex + '_',
  2478. self.idCounters,
  2479. self.fontCache);
  2480. return partialEvaluator.getTextContent(contentStream,
  2481. self.resources);
  2482. });
  2483. },
  2484. getAnnotationsData: function Page_getAnnotationsData() {
  2485. var annotations = this.annotations;
  2486. var annotationsData = [];
  2487. for (var i = 0, n = annotations.length; i < n; ++i) {
  2488. annotationsData.push(annotations[i].getData());
  2489. }
  2490. return annotationsData;
  2491. },
  2492. get annotations() {
  2493. var annotations = [];
  2494. var annotationRefs = (this.annotationRefs || []);
  2495. for (var i = 0, n = annotationRefs.length; i < n; ++i) {
  2496. var annotationRef = annotationRefs[i];
  2497. var annotation = Annotation.fromRef(this.xref, annotationRef);
  2498. if (annotation) {
  2499. annotations.push(annotation);
  2500. }
  2501. }
  2502. return shadow(this, 'annotations', annotations);
  2503. }
  2504. };
  2505. return Page;
  2506. })();
  2507. /**
  2508. * The `PDFDocument` holds all the data of the PDF file. Compared to the
  2509. * `PDFDoc`, this one doesn't have any job management code.
  2510. * Right now there exists one PDFDocument on the main thread + one object
  2511. * for each worker. If there is no worker support enabled, there are two
  2512. * `PDFDocument` objects on the main thread created.
  2513. */
  2514. var PDFDocument = (function PDFDocumentClosure() {
  2515. var FINGERPRINT_FIRST_BYTES = 1024;
  2516. var EMPTY_FINGERPRINT = '\x00\x00\x00\x00\x00\x00\x00' +
  2517. '\x00\x00\x00\x00\x00\x00\x00\x00\x00';
  2518. function PDFDocument(pdfManager, arg, password) {
  2519. if (isStream(arg)) {
  2520. init.call(this, pdfManager, arg, password);
  2521. } else if (isArrayBuffer(arg)) {
  2522. init.call(this, pdfManager, new Stream(arg), password);
  2523. } else {
  2524. error('PDFDocument: Unknown argument type');
  2525. }
  2526. }
  2527. function init(pdfManager, stream, password) {
  2528. assert(stream.length > 0, 'stream must have data');
  2529. this.pdfManager = pdfManager;
  2530. this.stream = stream;
  2531. var xref = new XRef(this.stream, password, pdfManager);
  2532. this.xref = xref;
  2533. }
  2534. function find(stream, needle, limit, backwards) {
  2535. var pos = stream.pos;
  2536. var end = stream.end;
  2537. var strBuf = [];
  2538. if (pos + limit > end) {
  2539. limit = end - pos;
  2540. }
  2541. for (var n = 0; n < limit; ++n) {
  2542. strBuf.push(String.fromCharCode(stream.getByte()));
  2543. }
  2544. var str = strBuf.join('');
  2545. stream.pos = pos;
  2546. var index = backwards ? str.lastIndexOf(needle) : str.indexOf(needle);
  2547. if (index === -1) {
  2548. return false; /* not found */
  2549. }
  2550. stream.pos += index;
  2551. return true; /* found */
  2552. }
  2553. var DocumentInfoValidators = {
  2554. get entries() {
  2555. // Lazily build this since all the validation functions below are not
  2556. // defined until after this file loads.
  2557. return shadow(this, 'entries', {
  2558. Title: isString,
  2559. Author: isString,
  2560. Subject: isString,
  2561. Keywords: isString,
  2562. Creator: isString,
  2563. Producer: isString,
  2564. CreationDate: isString,
  2565. ModDate: isString,
  2566. Trapped: isName
  2567. });
  2568. }
  2569. };
  2570. PDFDocument.prototype = {
  2571. parse: function PDFDocument_parse(recoveryMode) {
  2572. this.setup(recoveryMode);
  2573. try {
  2574. // checking if AcroForm is present
  2575. this.acroForm = this.catalog.catDict.get('AcroForm');
  2576. if (this.acroForm) {
  2577. this.xfa = this.acroForm.get('XFA');
  2578. var fields = this.acroForm.get('Fields');
  2579. if ((!fields || !isArray(fields) || fields.length === 0) &&
  2580. !this.xfa) {
  2581. // no fields and no XFA -- not a form (?)
  2582. this.acroForm = null;
  2583. }
  2584. }
  2585. } catch (ex) {
  2586. info('Something wrong with AcroForm entry');
  2587. this.acroForm = null;
  2588. }
  2589. },
  2590. get linearization() {
  2591. var linearization = null;
  2592. if (this.stream.length) {
  2593. try {
  2594. linearization = Linearization.create(this.stream);
  2595. } catch (err) {
  2596. if (err instanceof MissingDataException) {
  2597. throw err;
  2598. }
  2599. info(err);
  2600. }
  2601. }
  2602. // shadow the prototype getter with a data property
  2603. return shadow(this, 'linearization', linearization);
  2604. },
  2605. get startXRef() {
  2606. var stream = this.stream;
  2607. var startXRef = 0;
  2608. var linearization = this.linearization;
  2609. if (linearization) {
  2610. // Find end of first obj.
  2611. stream.reset();
  2612. if (find(stream, 'endobj', 1024)) {
  2613. startXRef = stream.pos + 6;
  2614. }
  2615. } else {
  2616. // Find startxref by jumping backward from the end of the file.
  2617. var step = 1024;
  2618. var found = false, pos = stream.end;
  2619. while (!found && pos > 0) {
  2620. pos -= step - 'startxref'.length;
  2621. if (pos < 0) {
  2622. pos = 0;
  2623. }
  2624. stream.pos = pos;
  2625. found = find(stream, 'startxref', step, true);
  2626. }
  2627. if (found) {
  2628. stream.skip(9);
  2629. var ch;
  2630. do {
  2631. ch = stream.getByte();
  2632. } while (Lexer.isSpace(ch));
  2633. var str = '';
  2634. while (ch >= 0x20 && ch <= 0x39) { // < '9'
  2635. str += String.fromCharCode(ch);
  2636. ch = stream.getByte();
  2637. }
  2638. startXRef = parseInt(str, 10);
  2639. if (isNaN(startXRef)) {
  2640. startXRef = 0;
  2641. }
  2642. }
  2643. }
  2644. // shadow the prototype getter with a data property
  2645. return shadow(this, 'startXRef', startXRef);
  2646. },
  2647. get mainXRefEntriesOffset() {
  2648. var mainXRefEntriesOffset = 0;
  2649. var linearization = this.linearization;
  2650. if (linearization) {
  2651. mainXRefEntriesOffset = linearization.mainXRefEntriesOffset;
  2652. }
  2653. // shadow the prototype getter with a data property
  2654. return shadow(this, 'mainXRefEntriesOffset', mainXRefEntriesOffset);
  2655. },
  2656. // Find the header, remove leading garbage and setup the stream
  2657. // starting from the header.
  2658. checkHeader: function PDFDocument_checkHeader() {
  2659. var stream = this.stream;
  2660. stream.reset();
  2661. if (find(stream, '%PDF-', 1024)) {
  2662. // Found the header, trim off any garbage before it.
  2663. stream.moveStart();
  2664. // Reading file format version
  2665. var MAX_VERSION_LENGTH = 12;
  2666. var version = '', ch;
  2667. while ((ch = stream.getByte()) > 0x20) { // SPACE
  2668. if (version.length >= MAX_VERSION_LENGTH) {
  2669. break;
  2670. }
  2671. version += String.fromCharCode(ch);
  2672. }
  2673. // removing "%PDF-"-prefix
  2674. this.pdfFormatVersion = version.substring(5);
  2675. return;
  2676. }
  2677. // May not be a PDF file, continue anyway.
  2678. },
  2679. parseStartXRef: function PDFDocument_parseStartXRef() {
  2680. var startXRef = this.startXRef;
  2681. this.xref.setStartXRef(startXRef);
  2682. },
  2683. setup: function PDFDocument_setup(recoveryMode) {
  2684. this.xref.parse(recoveryMode);
  2685. this.catalog = new Catalog(this.pdfManager, this.xref);
  2686. },
  2687. get numPages() {
  2688. var linearization = this.linearization;
  2689. var num = linearization ? linearization.numPages : this.catalog.numPages;
  2690. // shadow the prototype getter
  2691. return shadow(this, 'numPages', num);
  2692. },
  2693. get documentInfo() {
  2694. var docInfo = {
  2695. PDFFormatVersion: this.pdfFormatVersion,
  2696. IsAcroFormPresent: !!this.acroForm,
  2697. IsXFAPresent: !!this.xfa
  2698. };
  2699. var infoDict;
  2700. try {
  2701. infoDict = this.xref.trailer.get('Info');
  2702. } catch (err) {
  2703. info('The document information dictionary is invalid.');
  2704. }
  2705. if (infoDict) {
  2706. var validEntries = DocumentInfoValidators.entries;
  2707. // Only fill the document info with valid entries from the spec.
  2708. for (var key in validEntries) {
  2709. if (infoDict.has(key)) {
  2710. var value = infoDict.get(key);
  2711. // Make sure the value conforms to the spec.
  2712. if (validEntries[key](value)) {
  2713. docInfo[key] = (typeof value !== 'string' ?
  2714. value : stringToPDFString(value));
  2715. } else {
  2716. info('Bad value in document info for "' + key + '"');
  2717. }
  2718. }
  2719. }
  2720. }
  2721. return shadow(this, 'documentInfo', docInfo);
  2722. },
  2723. get fingerprint() {
  2724. var xref = this.xref, idArray, hash, fileID = '';
  2725. if (xref.trailer.has('ID')) {
  2726. idArray = xref.trailer.get('ID');
  2727. }
  2728. if (idArray && isArray(idArray) && idArray[0] !== EMPTY_FINGERPRINT) {
  2729. hash = stringToBytes(idArray[0]);
  2730. } else {
  2731. if (this.stream.ensureRange) {
  2732. this.stream.ensureRange(0,
  2733. Math.min(FINGERPRINT_FIRST_BYTES, this.stream.end));
  2734. }
  2735. hash = calculateMD5(this.stream.bytes.subarray(0,
  2736. FINGERPRINT_FIRST_BYTES), 0, FINGERPRINT_FIRST_BYTES);
  2737. }
  2738. for (var i = 0, n = hash.length; i < n; i++) {
  2739. var hex = hash[i].toString(16);
  2740. fileID += hex.length === 1 ? '0' + hex : hex;
  2741. }
  2742. return shadow(this, 'fingerprint', fileID);
  2743. },
  2744. getPage: function PDFDocument_getPage(pageIndex) {
  2745. return this.catalog.getPage(pageIndex);
  2746. },
  2747. cleanup: function PDFDocument_cleanup() {
  2748. return this.catalog.cleanup();
  2749. }
  2750. };
  2751. return PDFDocument;
  2752. })();
  2753. var Name = (function NameClosure() {
  2754. function Name(name) {
  2755. this.name = name;
  2756. }
  2757. Name.prototype = {};
  2758. var nameCache = {};
  2759. Name.get = function Name_get(name) {
  2760. var nameValue = nameCache[name];
  2761. return (nameValue ? nameValue : (nameCache[name] = new Name(name)));
  2762. };
  2763. return Name;
  2764. })();
  2765. var Cmd = (function CmdClosure() {
  2766. function Cmd(cmd) {
  2767. this.cmd = cmd;
  2768. }
  2769. Cmd.prototype = {};
  2770. var cmdCache = {};
  2771. Cmd.get = function Cmd_get(cmd) {
  2772. var cmdValue = cmdCache[cmd];
  2773. return (cmdValue ? cmdValue : (cmdCache[cmd] = new Cmd(cmd)));
  2774. };
  2775. return Cmd;
  2776. })();
  2777. var Dict = (function DictClosure() {
  2778. var nonSerializable = function nonSerializableClosure() {
  2779. return nonSerializable; // creating closure on some variable
  2780. };
  2781. var GETALL_DICTIONARY_TYPES_WHITELIST = {
  2782. 'Background': true,
  2783. 'ExtGState': true,
  2784. 'Halftone': true,
  2785. 'Layout': true,
  2786. 'Mask': true,
  2787. 'Pagination': true,
  2788. 'Printing': true
  2789. };
  2790. function isRecursionAllowedFor(dict) {
  2791. if (!isName(dict.Type)) {
  2792. return true;
  2793. }
  2794. var dictType = dict.Type.name;
  2795. return GETALL_DICTIONARY_TYPES_WHITELIST[dictType] === true;
  2796. }
  2797. // xref is optional
  2798. function Dict(xref) {
  2799. // Map should only be used internally, use functions below to access.
  2800. this.map = Object.create(null);
  2801. this.xref = xref;
  2802. this.objId = null;
  2803. this.__nonSerializable__ = nonSerializable; // disable cloning of the Dict
  2804. }
  2805. Dict.prototype = {
  2806. assignXref: function Dict_assignXref(newXref) {
  2807. this.xref = newXref;
  2808. },
  2809. // automatically dereferences Ref objects
  2810. get: function Dict_get(key1, key2, key3) {
  2811. var value;
  2812. var xref = this.xref;
  2813. if (typeof (value = this.map[key1]) !== 'undefined' || key1 in this.map ||
  2814. typeof key2 === 'undefined') {
  2815. return xref ? xref.fetchIfRef(value) : value;
  2816. }
  2817. if (typeof (value = this.map[key2]) !== 'undefined' || key2 in this.map ||
  2818. typeof key3 === 'undefined') {
  2819. return xref ? xref.fetchIfRef(value) : value;
  2820. }
  2821. value = this.map[key3] || null;
  2822. return xref ? xref.fetchIfRef(value) : value;
  2823. },
  2824. // Same as get(), but returns a promise and uses fetchIfRefAsync().
  2825. getAsync: function Dict_getAsync(key1, key2, key3) {
  2826. var value;
  2827. var xref = this.xref;
  2828. if (typeof (value = this.map[key1]) !== 'undefined' || key1 in this.map ||
  2829. typeof key2 === 'undefined') {
  2830. if (xref) {
  2831. return xref.fetchIfRefAsync(value);
  2832. }
  2833. return Promise.resolve(value);
  2834. }
  2835. if (typeof (value = this.map[key2]) !== 'undefined' || key2 in this.map ||
  2836. typeof key3 === 'undefined') {
  2837. if (xref) {
  2838. return xref.fetchIfRefAsync(value);
  2839. }
  2840. return Promise.resolve(value);
  2841. }
  2842. value = this.map[key3] || null;
  2843. if (xref) {
  2844. return xref.fetchIfRefAsync(value);
  2845. }
  2846. return Promise.resolve(value);
  2847. },
  2848. // no dereferencing
  2849. getRaw: function Dict_getRaw(key) {
  2850. return this.map[key];
  2851. },
  2852. // creates new map and dereferences all Refs
  2853. getAll: function Dict_getAll() {
  2854. var all = Object.create(null);
  2855. var queue = null;
  2856. var key, obj;
  2857. for (key in this.map) {
  2858. obj = this.get(key);
  2859. if (obj instanceof Dict) {
  2860. if (isRecursionAllowedFor(obj)) {
  2861. (queue || (queue = [])).push({target: all, key: key, obj: obj});
  2862. } else {
  2863. all[key] = this.getRaw(key);
  2864. }
  2865. } else {
  2866. all[key] = obj;
  2867. }
  2868. }
  2869. if (!queue) {
  2870. return all;
  2871. }
  2872. // trying to take cyclic references into the account
  2873. var processed = Object.create(null);
  2874. while (queue.length > 0) {
  2875. var item = queue.shift();
  2876. var itemObj = item.obj;
  2877. var objId = itemObj.objId;
  2878. if (objId && objId in processed) {
  2879. item.target[item.key] = processed[objId];
  2880. continue;
  2881. }
  2882. var dereferenced = Object.create(null);
  2883. for (key in itemObj.map) {
  2884. obj = itemObj.get(key);
  2885. if (obj instanceof Dict) {
  2886. if (isRecursionAllowedFor(obj)) {
  2887. queue.push({target: dereferenced, key: key, obj: obj});
  2888. } else {
  2889. dereferenced[key] = itemObj.getRaw(key);
  2890. }
  2891. } else {
  2892. dereferenced[key] = obj;
  2893. }
  2894. }
  2895. if (objId) {
  2896. processed[objId] = dereferenced;
  2897. }
  2898. item.target[item.key] = dereferenced;
  2899. }
  2900. return all;
  2901. },
  2902. getKeys: function Dict_getKeys() {
  2903. return Object.keys(this.map);
  2904. },
  2905. set: function Dict_set(key, value) {
  2906. this.map[key] = value;
  2907. },
  2908. has: function Dict_has(key) {
  2909. return key in this.map;
  2910. },
  2911. forEach: function Dict_forEach(callback) {
  2912. for (var key in this.map) {
  2913. callback(key, this.get(key));
  2914. }
  2915. }
  2916. };
  2917. Dict.empty = new Dict(null);
  2918. return Dict;
  2919. })();
  2920. var Ref = (function RefClosure() {
  2921. function Ref(num, gen) {
  2922. this.num = num;
  2923. this.gen = gen;
  2924. }
  2925. Ref.prototype = {
  2926. toString: function Ref_toString() {
  2927. // This function is hot, so we make the string as compact as possible.
  2928. // |this.gen| is almost always zero, so we treat that case specially.
  2929. var str = this.num + 'R';
  2930. if (this.gen !== 0) {
  2931. str += this.gen;
  2932. }
  2933. return str;
  2934. }
  2935. };
  2936. return Ref;
  2937. })();
  2938. // The reference is identified by number and generation.
  2939. // This structure stores only one instance of the reference.
  2940. var RefSet = (function RefSetClosure() {
  2941. function RefSet() {
  2942. this.dict = {};
  2943. }
  2944. RefSet.prototype = {
  2945. has: function RefSet_has(ref) {
  2946. return ref.toString() in this.dict;
  2947. },
  2948. put: function RefSet_put(ref) {
  2949. this.dict[ref.toString()] = true;
  2950. },
  2951. remove: function RefSet_remove(ref) {
  2952. delete this.dict[ref.toString()];
  2953. }
  2954. };
  2955. return RefSet;
  2956. })();
  2957. var RefSetCache = (function RefSetCacheClosure() {
  2958. function RefSetCache() {
  2959. this.dict = Object.create(null);
  2960. }
  2961. RefSetCache.prototype = {
  2962. get: function RefSetCache_get(ref) {
  2963. return this.dict[ref.toString()];
  2964. },
  2965. has: function RefSetCache_has(ref) {
  2966. return ref.toString() in this.dict;
  2967. },
  2968. put: function RefSetCache_put(ref, obj) {
  2969. this.dict[ref.toString()] = obj;
  2970. },
  2971. putAlias: function RefSetCache_putAlias(ref, aliasRef) {
  2972. this.dict[ref.toString()] = this.get(aliasRef);
  2973. },
  2974. forEach: function RefSetCache_forEach(fn, thisArg) {
  2975. for (var i in this.dict) {
  2976. fn.call(thisArg, this.dict[i]);
  2977. }
  2978. },
  2979. clear: function RefSetCache_clear() {
  2980. this.dict = Object.create(null);
  2981. }
  2982. };
  2983. return RefSetCache;
  2984. })();
  2985. var Catalog = (function CatalogClosure() {
  2986. function Catalog(pdfManager, xref) {
  2987. this.pdfManager = pdfManager;
  2988. this.xref = xref;
  2989. this.catDict = xref.getCatalogObj();
  2990. this.fontCache = new RefSetCache();
  2991. assert(isDict(this.catDict),
  2992. 'catalog object is not a dictionary');
  2993. this.pagePromises = [];
  2994. }
  2995. Catalog.prototype = {
  2996. get metadata() {
  2997. var streamRef = this.catDict.getRaw('Metadata');
  2998. if (!isRef(streamRef)) {
  2999. return shadow(this, 'metadata', null);
  3000. }
  3001. var encryptMetadata = (!this.xref.encrypt ? false :
  3002. this.xref.encrypt.encryptMetadata);
  3003. var stream = this.xref.fetch(streamRef, !encryptMetadata);
  3004. var metadata;
  3005. if (stream && isDict(stream.dict)) {
  3006. var type = stream.dict.get('Type');
  3007. var subtype = stream.dict.get('Subtype');
  3008. if (isName(type) && isName(subtype) &&
  3009. type.name === 'Metadata' && subtype.name === 'XML') {
  3010. // XXX: This should examine the charset the XML document defines,
  3011. // however since there are currently no real means to decode
  3012. // arbitrary charsets, let's just hope that the author of the PDF
  3013. // was reasonable enough to stick with the XML default charset,
  3014. // which is UTF-8.
  3015. try {
  3016. metadata = stringToUTF8String(bytesToString(stream.getBytes()));
  3017. } catch (e) {
  3018. info('Skipping invalid metadata.');
  3019. }
  3020. }
  3021. }
  3022. return shadow(this, 'metadata', metadata);
  3023. },
  3024. get toplevelPagesDict() {
  3025. var pagesObj = this.catDict.get('Pages');
  3026. assert(isDict(pagesObj), 'invalid top-level pages dictionary');
  3027. // shadow the prototype getter
  3028. return shadow(this, 'toplevelPagesDict', pagesObj);
  3029. },
  3030. get documentOutline() {
  3031. var obj = null;
  3032. try {
  3033. obj = this.readDocumentOutline();
  3034. } catch (ex) {
  3035. if (ex instanceof MissingDataException) {
  3036. throw ex;
  3037. }
  3038. warn('Unable to read document outline');
  3039. }
  3040. return shadow(this, 'documentOutline', obj);
  3041. },
  3042. readDocumentOutline: function Catalog_readDocumentOutline() {
  3043. var xref = this.xref;
  3044. var obj = this.catDict.get('Outlines');
  3045. var root = { items: [] };
  3046. if (isDict(obj)) {
  3047. obj = obj.getRaw('First');
  3048. var processed = new RefSet();
  3049. if (isRef(obj)) {
  3050. var queue = [{obj: obj, parent: root}];
  3051. // to avoid recursion keeping track of the items
  3052. // in the processed dictionary
  3053. processed.put(obj);
  3054. while (queue.length > 0) {
  3055. var i = queue.shift();
  3056. var outlineDict = xref.fetchIfRef(i.obj);
  3057. if (outlineDict === null) {
  3058. continue;
  3059. }
  3060. if (!outlineDict.has('Title')) {
  3061. error('Invalid outline item');
  3062. }
  3063. var dest = outlineDict.get('A');
  3064. if (dest) {
  3065. dest = dest.get('D');
  3066. } else if (outlineDict.has('Dest')) {
  3067. dest = outlineDict.getRaw('Dest');
  3068. if (isName(dest)) {
  3069. dest = dest.name;
  3070. }
  3071. }
  3072. var title = outlineDict.get('Title');
  3073. var outlineItem = {
  3074. dest: dest,
  3075. title: stringToPDFString(title),
  3076. color: outlineDict.get('C') || [0, 0, 0],
  3077. count: outlineDict.get('Count'),
  3078. bold: !!(outlineDict.get('F') & 2),
  3079. italic: !!(outlineDict.get('F') & 1),
  3080. items: []
  3081. };
  3082. i.parent.items.push(outlineItem);
  3083. obj = outlineDict.getRaw('First');
  3084. if (isRef(obj) && !processed.has(obj)) {
  3085. queue.push({obj: obj, parent: outlineItem});
  3086. processed.put(obj);
  3087. }
  3088. obj = outlineDict.getRaw('Next');
  3089. if (isRef(obj) && !processed.has(obj)) {
  3090. queue.push({obj: obj, parent: i.parent});
  3091. processed.put(obj);
  3092. }
  3093. }
  3094. }
  3095. }
  3096. return (root.items.length > 0 ? root.items : null);
  3097. },
  3098. get numPages() {
  3099. var obj = this.toplevelPagesDict.get('Count');
  3100. assert(
  3101. isInt(obj),
  3102. 'page count in top level pages object is not an integer'
  3103. );
  3104. // shadow the prototype getter
  3105. return shadow(this, 'num', obj);
  3106. },
  3107. get destinations() {
  3108. function fetchDestination(dest) {
  3109. return isDict(dest) ? dest.get('D') : dest;
  3110. }
  3111. var xref = this.xref;
  3112. var dests = {}, nameTreeRef, nameDictionaryRef;
  3113. var obj = this.catDict.get('Names');
  3114. if (obj && obj.has('Dests')) {
  3115. nameTreeRef = obj.getRaw('Dests');
  3116. } else if (this.catDict.has('Dests')) {
  3117. nameDictionaryRef = this.catDict.get('Dests');
  3118. }
  3119. if (nameDictionaryRef) {
  3120. // reading simple destination dictionary
  3121. obj = nameDictionaryRef;
  3122. obj.forEach(function catalogForEach(key, value) {
  3123. if (!value) {
  3124. return;
  3125. }
  3126. dests[key] = fetchDestination(value);
  3127. });
  3128. }
  3129. if (nameTreeRef) {
  3130. var nameTree = new NameTree(nameTreeRef, xref);
  3131. var names = nameTree.getAll();
  3132. for (var name in names) {
  3133. if (!names.hasOwnProperty(name)) {
  3134. continue;
  3135. }
  3136. dests[name] = fetchDestination(names[name]);
  3137. }
  3138. }
  3139. return shadow(this, 'destinations', dests);
  3140. },
  3141. getDestination: function Catalog_getDestination(destinationId) {
  3142. function fetchDestination(dest) {
  3143. return isDict(dest) ? dest.get('D') : dest;
  3144. }
  3145. var xref = this.xref;
  3146. var dest, nameTreeRef, nameDictionaryRef;
  3147. var obj = this.catDict.get('Names');
  3148. if (obj && obj.has('Dests')) {
  3149. nameTreeRef = obj.getRaw('Dests');
  3150. } else if (this.catDict.has('Dests')) {
  3151. nameDictionaryRef = this.catDict.get('Dests');
  3152. }
  3153. if (nameDictionaryRef) {
  3154. // reading simple destination dictionary
  3155. obj = nameDictionaryRef;
  3156. obj.forEach(function catalogForEach(key, value) {
  3157. if (!value) {
  3158. return;
  3159. }
  3160. if (key === destinationId) {
  3161. dest = fetchDestination(value);
  3162. }
  3163. });
  3164. }
  3165. if (nameTreeRef) {
  3166. var nameTree = new NameTree(nameTreeRef, xref);
  3167. dest = fetchDestination(nameTree.get(destinationId));
  3168. }
  3169. return dest;
  3170. },
  3171. get attachments() {
  3172. var xref = this.xref;
  3173. var attachments = null, nameTreeRef;
  3174. var obj = this.catDict.get('Names');
  3175. if (obj) {
  3176. nameTreeRef = obj.getRaw('EmbeddedFiles');
  3177. }
  3178. if (nameTreeRef) {
  3179. var nameTree = new NameTree(nameTreeRef, xref);
  3180. var names = nameTree.getAll();
  3181. for (var name in names) {
  3182. if (!names.hasOwnProperty(name)) {
  3183. continue;
  3184. }
  3185. var fs = new FileSpec(names[name], xref);
  3186. if (!attachments) {
  3187. attachments = {};
  3188. }
  3189. attachments[stringToPDFString(name)] = fs.serializable;
  3190. }
  3191. }
  3192. return shadow(this, 'attachments', attachments);
  3193. },
  3194. get javaScript() {
  3195. var xref = this.xref;
  3196. var obj = this.catDict.get('Names');
  3197. var javaScript = [];
  3198. if (obj && obj.has('JavaScript')) {
  3199. var nameTree = new NameTree(obj.getRaw('JavaScript'), xref);
  3200. var names = nameTree.getAll();
  3201. for (var name in names) {
  3202. if (!names.hasOwnProperty(name)) {
  3203. continue;
  3204. }
  3205. // We don't really use the JavaScript right now. This code is
  3206. // defensive so we don't cause errors on document load.
  3207. var jsDict = names[name];
  3208. if (!isDict(jsDict)) {
  3209. continue;
  3210. }
  3211. var type = jsDict.get('S');
  3212. if (!isName(type) || type.name !== 'JavaScript') {
  3213. continue;
  3214. }
  3215. var js = jsDict.get('JS');
  3216. if (!isString(js) && !isStream(js)) {
  3217. continue;
  3218. }
  3219. if (isStream(js)) {
  3220. js = bytesToString(js.getBytes());
  3221. }
  3222. javaScript.push(stringToPDFString(js));
  3223. }
  3224. }
  3225. // Append OpenAction actions to javaScript array
  3226. var openactionDict = this.catDict.get('OpenAction');
  3227. if (isDict(openactionDict)) {
  3228. var objType = openactionDict.get('Type');
  3229. var actionType = openactionDict.get('S');
  3230. var action = openactionDict.get('N');
  3231. var isPrintAction = (isName(objType) && objType.name === 'Action' &&
  3232. isName(actionType) && actionType.name === 'Named' &&
  3233. isName(action) && action.name === 'Print');
  3234. if (isPrintAction) {
  3235. javaScript.push('print(true);');
  3236. }
  3237. }
  3238. return shadow(this, 'javaScript', javaScript);
  3239. },
  3240. cleanup: function Catalog_cleanup() {
  3241. var promises = [];
  3242. this.fontCache.forEach(function (promise) {
  3243. promises.push(promise);
  3244. });
  3245. return Promise.all(promises).then(function (translatedFonts) {
  3246. for (var i = 0, ii = translatedFonts.length; i < ii; i++) {
  3247. var font = translatedFonts[i].dict;
  3248. delete font.translated;
  3249. }
  3250. this.fontCache.clear();
  3251. }.bind(this));
  3252. },
  3253. getPage: function Catalog_getPage(pageIndex) {
  3254. if (!(pageIndex in this.pagePromises)) {
  3255. this.pagePromises[pageIndex] = this.getPageDict(pageIndex).then(
  3256. function (a) {
  3257. var dict = a[0];
  3258. var ref = a[1];
  3259. return new Page(this.pdfManager, this.xref, pageIndex, dict, ref,
  3260. this.fontCache);
  3261. }.bind(this)
  3262. );
  3263. }
  3264. return this.pagePromises[pageIndex];
  3265. },
  3266. getPageDict: function Catalog_getPageDict(pageIndex) {
  3267. var capability = createPromiseCapability();
  3268. var nodesToVisit = [this.catDict.getRaw('Pages')];
  3269. var currentPageIndex = 0;
  3270. var xref = this.xref;
  3271. var checkAllKids = false;
  3272. function next() {
  3273. while (nodesToVisit.length) {
  3274. var currentNode = nodesToVisit.pop();
  3275. if (isRef(currentNode)) {
  3276. xref.fetchAsync(currentNode).then(function (obj) {
  3277. if (isDict(obj, 'Page') || (isDict(obj) && !obj.has('Kids'))) {
  3278. if (pageIndex === currentPageIndex) {
  3279. capability.resolve([obj, currentNode]);
  3280. } else {
  3281. currentPageIndex++;
  3282. next();
  3283. }
  3284. return;
  3285. }
  3286. nodesToVisit.push(obj);
  3287. next();
  3288. }, capability.reject);
  3289. return;
  3290. }
  3291. // Must be a child page dictionary.
  3292. assert(
  3293. isDict(currentNode),
  3294. 'page dictionary kid reference points to wrong type of object'
  3295. );
  3296. var count = currentNode.get('Count');
  3297. // If the current node doesn't have any children, avoid getting stuck
  3298. // in an empty node further down in the tree (see issue5644.pdf).
  3299. if (count === 0) {
  3300. checkAllKids = true;
  3301. }
  3302. // Skip nodes where the page can't be.
  3303. if (currentPageIndex + count <= pageIndex) {
  3304. currentPageIndex += count;
  3305. continue;
  3306. }
  3307. var kids = currentNode.get('Kids');
  3308. assert(isArray(kids), 'page dictionary kids object is not an array');
  3309. if (!checkAllKids && count === kids.length) {
  3310. // Nodes that don't have the page have been skipped and this is the
  3311. // bottom of the tree which means the page requested must be a
  3312. // descendant of this pages node. Ideally we would just resolve the
  3313. // promise with the page ref here, but there is the case where more
  3314. // pages nodes could link to single a page (see issue 3666 pdf). To
  3315. // handle this push it back on the queue so if it is a pages node it
  3316. // will be descended into.
  3317. nodesToVisit = [kids[pageIndex - currentPageIndex]];
  3318. currentPageIndex = pageIndex;
  3319. continue;
  3320. } else {
  3321. for (var last = kids.length - 1; last >= 0; last--) {
  3322. nodesToVisit.push(kids[last]);
  3323. }
  3324. }
  3325. }
  3326. capability.reject('Page index ' + pageIndex + ' not found.');
  3327. }
  3328. next();
  3329. return capability.promise;
  3330. },
  3331. getPageIndex: function Catalog_getPageIndex(ref) {
  3332. // The page tree nodes have the count of all the leaves below them. To get
  3333. // how many pages are before we just have to walk up the tree and keep
  3334. // adding the count of siblings to the left of the node.
  3335. var xref = this.xref;
  3336. function pagesBeforeRef(kidRef) {
  3337. var total = 0;
  3338. var parentRef;
  3339. return xref.fetchAsync(kidRef).then(function (node) {
  3340. if (!node) {
  3341. return null;
  3342. }
  3343. parentRef = node.getRaw('Parent');
  3344. return node.getAsync('Parent');
  3345. }).then(function (parent) {
  3346. if (!parent) {
  3347. return null;
  3348. }
  3349. return parent.getAsync('Kids');
  3350. }).then(function (kids) {
  3351. if (!kids) {
  3352. return null;
  3353. }
  3354. var kidPromises = [];
  3355. var found = false;
  3356. for (var i = 0; i < kids.length; i++) {
  3357. var kid = kids[i];
  3358. assert(isRef(kid), 'kids must be a ref');
  3359. if (kid.num === kidRef.num) {
  3360. found = true;
  3361. break;
  3362. }
  3363. kidPromises.push(xref.fetchAsync(kid).then(function (kid) {
  3364. if (kid.has('Count')) {
  3365. var count = kid.get('Count');
  3366. total += count;
  3367. } else { // page leaf node
  3368. total++;
  3369. }
  3370. }));
  3371. }
  3372. if (!found) {
  3373. error('kid ref not found in parents kids');
  3374. }
  3375. return Promise.all(kidPromises).then(function () {
  3376. return [total, parentRef];
  3377. });
  3378. });
  3379. }
  3380. var total = 0;
  3381. function next(ref) {
  3382. return pagesBeforeRef(ref).then(function (args) {
  3383. if (!args) {
  3384. return total;
  3385. }
  3386. var count = args[0];
  3387. var parentRef = args[1];
  3388. total += count;
  3389. return next(parentRef);
  3390. });
  3391. }
  3392. return next(ref);
  3393. }
  3394. };
  3395. return Catalog;
  3396. })();
  3397. var XRef = (function XRefClosure() {
  3398. function XRef(stream, password) {
  3399. this.stream = stream;
  3400. this.entries = [];
  3401. this.xrefstms = {};
  3402. // prepare the XRef cache
  3403. this.cache = [];
  3404. this.password = password;
  3405. this.stats = {
  3406. streamTypes: [],
  3407. fontTypes: []
  3408. };
  3409. }
  3410. XRef.prototype = {
  3411. setStartXRef: function XRef_setStartXRef(startXRef) {
  3412. // Store the starting positions of xref tables as we process them
  3413. // so we can recover from missing data errors
  3414. this.startXRefQueue = [startXRef];
  3415. },
  3416. parse: function XRef_parse(recoveryMode) {
  3417. var trailerDict;
  3418. if (!recoveryMode) {
  3419. trailerDict = this.readXRef();
  3420. } else {
  3421. warn('Indexing all PDF objects');
  3422. trailerDict = this.indexObjects();
  3423. }
  3424. trailerDict.assignXref(this);
  3425. this.trailer = trailerDict;
  3426. var encrypt = trailerDict.get('Encrypt');
  3427. if (encrypt) {
  3428. var ids = trailerDict.get('ID');
  3429. var fileId = (ids && ids.length) ? ids[0] : '';
  3430. this.encrypt = new CipherTransformFactory(encrypt, fileId,
  3431. this.password);
  3432. }
  3433. // get the root dictionary (catalog) object
  3434. if (!(this.root = trailerDict.get('Root'))) {
  3435. error('Invalid root reference');
  3436. }
  3437. },
  3438. processXRefTable: function XRef_processXRefTable(parser) {
  3439. if (!('tableState' in this)) {
  3440. // Stores state of the table as we process it so we can resume
  3441. // from middle of table in case of missing data error
  3442. this.tableState = {
  3443. entryNum: 0,
  3444. streamPos: parser.lexer.stream.pos,
  3445. parserBuf1: parser.buf1,
  3446. parserBuf2: parser.buf2
  3447. };
  3448. }
  3449. var obj = this.readXRefTable(parser);
  3450. // Sanity check
  3451. if (!isCmd(obj, 'trailer')) {
  3452. error('Invalid XRef table: could not find trailer dictionary');
  3453. }
  3454. // Read trailer dictionary, e.g.
  3455. // trailer
  3456. // << /Size 22
  3457. // /Root 20R
  3458. // /Info 10R
  3459. // /ID [ <81b14aafa313db63dbd6f981e49f94f4> ]
  3460. // >>
  3461. // The parser goes through the entire stream << ... >> and provides
  3462. // a getter interface for the key-value table
  3463. var dict = parser.getObj();
  3464. // The pdflib PDF generator can generate a nested trailer dictionary
  3465. if (!isDict(dict) && dict.dict) {
  3466. dict = dict.dict;
  3467. }
  3468. if (!isDict(dict)) {
  3469. error('Invalid XRef table: could not parse trailer dictionary');
  3470. }
  3471. delete this.tableState;
  3472. return dict;
  3473. },
  3474. readXRefTable: function XRef_readXRefTable(parser) {
  3475. // Example of cross-reference table:
  3476. // xref
  3477. // 0 1 <-- subsection header (first obj #, obj count)
  3478. // 0000000000 65535 f <-- actual object (offset, generation #, f/n)
  3479. // 23 2 <-- subsection header ... and so on ...
  3480. // 0000025518 00002 n
  3481. // 0000025635 00000 n
  3482. // trailer
  3483. // ...
  3484. var stream = parser.lexer.stream;
  3485. var tableState = this.tableState;
  3486. stream.pos = tableState.streamPos;
  3487. parser.buf1 = tableState.parserBuf1;
  3488. parser.buf2 = tableState.parserBuf2;
  3489. // Outer loop is over subsection headers
  3490. var obj;
  3491. while (true) {
  3492. if (!('firstEntryNum' in tableState) || !('entryCount' in tableState)) {
  3493. if (isCmd(obj = parser.getObj(), 'trailer')) {
  3494. break;
  3495. }
  3496. tableState.firstEntryNum = obj;
  3497. tableState.entryCount = parser.getObj();
  3498. }
  3499. var first = tableState.firstEntryNum;
  3500. var count = tableState.entryCount;
  3501. if (!isInt(first) || !isInt(count)) {
  3502. error('Invalid XRef table: wrong types in subsection header');
  3503. }
  3504. // Inner loop is over objects themselves
  3505. for (var i = tableState.entryNum; i < count; i++) {
  3506. tableState.streamPos = stream.pos;
  3507. tableState.entryNum = i;
  3508. tableState.parserBuf1 = parser.buf1;
  3509. tableState.parserBuf2 = parser.buf2;
  3510. var entry = {};
  3511. entry.offset = parser.getObj();
  3512. entry.gen = parser.getObj();
  3513. var type = parser.getObj();
  3514. if (isCmd(type, 'f')) {
  3515. entry.free = true;
  3516. } else if (isCmd(type, 'n')) {
  3517. entry.uncompressed = true;
  3518. }
  3519. // Validate entry obj
  3520. if (!isInt(entry.offset) || !isInt(entry.gen) ||
  3521. !(entry.free || entry.uncompressed)) {
  3522. error('Invalid entry in XRef subsection: ' + first + ', ' + count);
  3523. }
  3524. if (!this.entries[i + first]) {
  3525. this.entries[i + first] = entry;
  3526. }
  3527. }
  3528. tableState.entryNum = 0;
  3529. tableState.streamPos = stream.pos;
  3530. tableState.parserBuf1 = parser.buf1;
  3531. tableState.parserBuf2 = parser.buf2;
  3532. delete tableState.firstEntryNum;
  3533. delete tableState.entryCount;
  3534. }
  3535. // Per issue 3248: hp scanners generate bad XRef
  3536. if (first === 1 && this.entries[1] && this.entries[1].free) {
  3537. // shifting the entries
  3538. this.entries.shift();
  3539. }
  3540. // Sanity check: as per spec, first object must be free
  3541. if (this.entries[0] && !this.entries[0].free) {
  3542. error('Invalid XRef table: unexpected first object');
  3543. }
  3544. return obj;
  3545. },
  3546. processXRefStream: function XRef_processXRefStream(stream) {
  3547. if (!('streamState' in this)) {
  3548. // Stores state of the stream as we process it so we can resume
  3549. // from middle of stream in case of missing data error
  3550. var streamParameters = stream.dict;
  3551. var byteWidths = streamParameters.get('W');
  3552. var range = streamParameters.get('Index');
  3553. if (!range) {
  3554. range = [0, streamParameters.get('Size')];
  3555. }
  3556. this.streamState = {
  3557. entryRanges: range,
  3558. byteWidths: byteWidths,
  3559. entryNum: 0,
  3560. streamPos: stream.pos
  3561. };
  3562. }
  3563. this.readXRefStream(stream);
  3564. delete this.streamState;
  3565. return stream.dict;
  3566. },
  3567. readXRefStream: function XRef_readXRefStream(stream) {
  3568. var i, j;
  3569. var streamState = this.streamState;
  3570. stream.pos = streamState.streamPos;
  3571. var byteWidths = streamState.byteWidths;
  3572. var typeFieldWidth = byteWidths[0];
  3573. var offsetFieldWidth = byteWidths[1];
  3574. var generationFieldWidth = byteWidths[2];
  3575. var entryRanges = streamState.entryRanges;
  3576. while (entryRanges.length > 0) {
  3577. var first = entryRanges[0];
  3578. var n = entryRanges[1];
  3579. if (!isInt(first) || !isInt(n)) {
  3580. error('Invalid XRef range fields: ' + first + ', ' + n);
  3581. }
  3582. if (!isInt(typeFieldWidth) || !isInt(offsetFieldWidth) ||
  3583. !isInt(generationFieldWidth)) {
  3584. error('Invalid XRef entry fields length: ' + first + ', ' + n);
  3585. }
  3586. for (i = streamState.entryNum; i < n; ++i) {
  3587. streamState.entryNum = i;
  3588. streamState.streamPos = stream.pos;
  3589. var type = 0, offset = 0, generation = 0;
  3590. for (j = 0; j < typeFieldWidth; ++j) {
  3591. type = (type << 8) | stream.getByte();
  3592. }
  3593. // if type field is absent, its default value is 1
  3594. if (typeFieldWidth === 0) {
  3595. type = 1;
  3596. }
  3597. for (j = 0; j < offsetFieldWidth; ++j) {
  3598. offset = (offset << 8) | stream.getByte();
  3599. }
  3600. for (j = 0; j < generationFieldWidth; ++j) {
  3601. generation = (generation << 8) | stream.getByte();
  3602. }
  3603. var entry = {};
  3604. entry.offset = offset;
  3605. entry.gen = generation;
  3606. switch (type) {
  3607. case 0:
  3608. entry.free = true;
  3609. break;
  3610. case 1:
  3611. entry.uncompressed = true;
  3612. break;
  3613. case 2:
  3614. break;
  3615. default:
  3616. error('Invalid XRef entry type: ' + type);
  3617. }
  3618. if (!this.entries[first + i]) {
  3619. this.entries[first + i] = entry;
  3620. }
  3621. }
  3622. streamState.entryNum = 0;
  3623. streamState.streamPos = stream.pos;
  3624. entryRanges.splice(0, 2);
  3625. }
  3626. },
  3627. indexObjects: function XRef_indexObjects() {
  3628. // Simple scan through the PDF content to find objects,
  3629. // trailers and XRef streams.
  3630. function readToken(data, offset) {
  3631. var token = '', ch = data[offset];
  3632. while (ch !== 13 && ch !== 10) {
  3633. if (++offset >= data.length) {
  3634. break;
  3635. }
  3636. token += String.fromCharCode(ch);
  3637. ch = data[offset];
  3638. }
  3639. return token;
  3640. }
  3641. function skipUntil(data, offset, what) {
  3642. var length = what.length, dataLength = data.length;
  3643. var skipped = 0;
  3644. // finding byte sequence
  3645. while (offset < dataLength) {
  3646. var i = 0;
  3647. while (i < length && data[offset + i] === what[i]) {
  3648. ++i;
  3649. }
  3650. if (i >= length) {
  3651. break; // sequence found
  3652. }
  3653. offset++;
  3654. skipped++;
  3655. }
  3656. return skipped;
  3657. }
  3658. var trailerBytes = new Uint8Array([116, 114, 97, 105, 108, 101, 114]);
  3659. var startxrefBytes = new Uint8Array([115, 116, 97, 114, 116, 120, 114,
  3660. 101, 102]);
  3661. var endobjBytes = new Uint8Array([101, 110, 100, 111, 98, 106]);
  3662. var xrefBytes = new Uint8Array([47, 88, 82, 101, 102]);
  3663. var stream = this.stream;
  3664. stream.pos = 0;
  3665. var buffer = stream.getBytes();
  3666. var position = stream.start, length = buffer.length;
  3667. var trailers = [], xrefStms = [];
  3668. while (position < length) {
  3669. var ch = buffer[position];
  3670. if (ch === 32 || ch === 9 || ch === 13 || ch === 10) {
  3671. ++position;
  3672. continue;
  3673. }
  3674. if (ch === 37) { // %-comment
  3675. do {
  3676. ++position;
  3677. if (position >= length) {
  3678. break;
  3679. }
  3680. ch = buffer[position];
  3681. } while (ch !== 13 && ch !== 10);
  3682. continue;
  3683. }
  3684. var token = readToken(buffer, position);
  3685. var m;
  3686. if (token === 'xref') {
  3687. position += skipUntil(buffer, position, trailerBytes);
  3688. trailers.push(position);
  3689. position += skipUntil(buffer, position, startxrefBytes);
  3690. } else if ((m = /^(\d+)\s+(\d+)\s+obj\b/.exec(token))) {
  3691. this.entries[m[1]] = {
  3692. offset: position,
  3693. gen: m[2] | 0,
  3694. uncompressed: true
  3695. };
  3696. var contentLength = skipUntil(buffer, position, endobjBytes) + 7;
  3697. var content = buffer.subarray(position, position + contentLength);
  3698. // checking XRef stream suspect
  3699. // (it shall have '/XRef' and next char is not a letter)
  3700. var xrefTagOffset = skipUntil(content, 0, xrefBytes);
  3701. if (xrefTagOffset < contentLength &&
  3702. content[xrefTagOffset + 5] < 64) {
  3703. xrefStms.push(position);
  3704. this.xrefstms[position] = 1; // don't read it recursively
  3705. }
  3706. position += contentLength;
  3707. } else {
  3708. position += token.length + 1;
  3709. }
  3710. }
  3711. // reading XRef streams
  3712. var i, ii;
  3713. for (i = 0, ii = xrefStms.length; i < ii; ++i) {
  3714. this.startXRefQueue.push(xrefStms[i]);
  3715. this.readXRef(/* recoveryMode */ true);
  3716. }
  3717. // finding main trailer
  3718. var dict;
  3719. for (i = 0, ii = trailers.length; i < ii; ++i) {
  3720. stream.pos = trailers[i];
  3721. var parser = new Parser(new Lexer(stream), true, this);
  3722. var obj = parser.getObj();
  3723. if (!isCmd(obj, 'trailer')) {
  3724. continue;
  3725. }
  3726. // read the trailer dictionary
  3727. if (!isDict(dict = parser.getObj())) {
  3728. continue;
  3729. }
  3730. // taking the first one with 'ID'
  3731. if (dict.has('ID')) {
  3732. return dict;
  3733. }
  3734. }
  3735. // no tailer with 'ID', taking last one (if exists)
  3736. if (dict) {
  3737. return dict;
  3738. }
  3739. // nothing helps
  3740. // calling error() would reject worker with an UnknownErrorException.
  3741. throw new InvalidPDFException('Invalid PDF structure');
  3742. },
  3743. readXRef: function XRef_readXRef(recoveryMode) {
  3744. var stream = this.stream;
  3745. try {
  3746. while (this.startXRefQueue.length) {
  3747. var startXRef = this.startXRefQueue[0];
  3748. stream.pos = startXRef + stream.start;
  3749. var parser = new Parser(new Lexer(stream), true, this);
  3750. var obj = parser.getObj();
  3751. var dict;
  3752. // Get dictionary
  3753. if (isCmd(obj, 'xref')) {
  3754. // Parse end-of-file XRef
  3755. dict = this.processXRefTable(parser);
  3756. if (!this.topDict) {
  3757. this.topDict = dict;
  3758. }
  3759. // Recursively get other XRefs 'XRefStm', if any
  3760. obj = dict.get('XRefStm');
  3761. if (isInt(obj)) {
  3762. var pos = obj;
  3763. // ignore previously loaded xref streams
  3764. // (possible infinite recursion)
  3765. if (!(pos in this.xrefstms)) {
  3766. this.xrefstms[pos] = 1;
  3767. this.startXRefQueue.push(pos);
  3768. }
  3769. }
  3770. } else if (isInt(obj)) {
  3771. // Parse in-stream XRef
  3772. if (!isInt(parser.getObj()) ||
  3773. !isCmd(parser.getObj(), 'obj') ||
  3774. !isStream(obj = parser.getObj())) {
  3775. error('Invalid XRef stream');
  3776. }
  3777. dict = this.processXRefStream(obj);
  3778. if (!this.topDict) {
  3779. this.topDict = dict;
  3780. }
  3781. if (!dict) {
  3782. error('Failed to read XRef stream');
  3783. }
  3784. } else {
  3785. error('Invalid XRef stream header');
  3786. }
  3787. // Recursively get previous dictionary, if any
  3788. obj = dict.get('Prev');
  3789. if (isInt(obj)) {
  3790. this.startXRefQueue.push(obj);
  3791. } else if (isRef(obj)) {
  3792. // The spec says Prev must not be a reference, i.e. "/Prev NNN"
  3793. // This is a fallback for non-compliant PDFs, i.e. "/Prev NNN 0 R"
  3794. this.startXRefQueue.push(obj.num);
  3795. }
  3796. this.startXRefQueue.shift();
  3797. }
  3798. return this.topDict;
  3799. } catch (e) {
  3800. if (e instanceof MissingDataException) {
  3801. throw e;
  3802. }
  3803. info('(while reading XRef): ' + e);
  3804. }
  3805. if (recoveryMode) {
  3806. return;
  3807. }
  3808. throw new XRefParseException();
  3809. },
  3810. getEntry: function XRef_getEntry(i) {
  3811. var xrefEntry = this.entries[i];
  3812. if (xrefEntry && !xrefEntry.free && xrefEntry.offset) {
  3813. return xrefEntry;
  3814. }
  3815. return null;
  3816. },
  3817. fetchIfRef: function XRef_fetchIfRef(obj) {
  3818. if (!isRef(obj)) {
  3819. return obj;
  3820. }
  3821. return this.fetch(obj);
  3822. },
  3823. fetch: function XRef_fetch(ref, suppressEncryption) {
  3824. assert(isRef(ref), 'ref object is not a reference');
  3825. var num = ref.num;
  3826. if (num in this.cache) {
  3827. var cacheEntry = this.cache[num];
  3828. return cacheEntry;
  3829. }
  3830. var xrefEntry = this.getEntry(num);
  3831. // the referenced entry can be free
  3832. if (xrefEntry === null) {
  3833. return (this.cache[num] = null);
  3834. }
  3835. if (xrefEntry.uncompressed) {
  3836. xrefEntry = this.fetchUncompressed(ref, xrefEntry, suppressEncryption);
  3837. } else {
  3838. xrefEntry = this.fetchCompressed(xrefEntry, suppressEncryption);
  3839. }
  3840. if (isDict(xrefEntry)){
  3841. xrefEntry.objId = ref.toString();
  3842. } else if (isStream(xrefEntry)) {
  3843. xrefEntry.dict.objId = ref.toString();
  3844. }
  3845. return xrefEntry;
  3846. },
  3847. fetchUncompressed: function XRef_fetchUncompressed(ref, xrefEntry,
  3848. suppressEncryption) {
  3849. var gen = ref.gen;
  3850. var num = ref.num;
  3851. if (xrefEntry.gen !== gen) {
  3852. error('inconsistent generation in XRef');
  3853. }
  3854. var stream = this.stream.makeSubStream(xrefEntry.offset +
  3855. this.stream.start);
  3856. var parser = new Parser(new Lexer(stream), true, this);
  3857. var obj1 = parser.getObj();
  3858. var obj2 = parser.getObj();
  3859. var obj3 = parser.getObj();
  3860. if (!isInt(obj1) || parseInt(obj1, 10) !== num ||
  3861. !isInt(obj2) || parseInt(obj2, 10) !== gen ||
  3862. !isCmd(obj3)) {
  3863. error('bad XRef entry');
  3864. }
  3865. if (!isCmd(obj3, 'obj')) {
  3866. // some bad PDFs use "obj1234" and really mean 1234
  3867. if (obj3.cmd.indexOf('obj') === 0) {
  3868. num = parseInt(obj3.cmd.substring(3), 10);
  3869. if (!isNaN(num)) {
  3870. return num;
  3871. }
  3872. }
  3873. error('bad XRef entry');
  3874. }
  3875. if (this.encrypt && !suppressEncryption) {
  3876. xrefEntry = parser.getObj(this.encrypt.createCipherTransform(num, gen));
  3877. } else {
  3878. xrefEntry = parser.getObj();
  3879. }
  3880. if (!isStream(xrefEntry)) {
  3881. this.cache[num] = xrefEntry;
  3882. }
  3883. return xrefEntry;
  3884. },
  3885. fetchCompressed: function XRef_fetchCompressed(xrefEntry,
  3886. suppressEncryption) {
  3887. var tableOffset = xrefEntry.offset;
  3888. var stream = this.fetch(new Ref(tableOffset, 0));
  3889. if (!isStream(stream)) {
  3890. error('bad ObjStm stream');
  3891. }
  3892. var first = stream.dict.get('First');
  3893. var n = stream.dict.get('N');
  3894. if (!isInt(first) || !isInt(n)) {
  3895. error('invalid first and n parameters for ObjStm stream');
  3896. }
  3897. var parser = new Parser(new Lexer(stream), false, this);
  3898. parser.allowStreams = true;
  3899. var i, entries = [], num, nums = [];
  3900. // read the object numbers to populate cache
  3901. for (i = 0; i < n; ++i) {
  3902. num = parser.getObj();
  3903. if (!isInt(num)) {
  3904. error('invalid object number in the ObjStm stream: ' + num);
  3905. }
  3906. nums.push(num);
  3907. var offset = parser.getObj();
  3908. if (!isInt(offset)) {
  3909. error('invalid object offset in the ObjStm stream: ' + offset);
  3910. }
  3911. }
  3912. // read stream objects for cache
  3913. for (i = 0; i < n; ++i) {
  3914. entries.push(parser.getObj());
  3915. num = nums[i];
  3916. var entry = this.entries[num];
  3917. if (entry && entry.offset === tableOffset && entry.gen === i) {
  3918. this.cache[num] = entries[i];
  3919. }
  3920. }
  3921. xrefEntry = entries[xrefEntry.gen];
  3922. if (xrefEntry === undefined) {
  3923. error('bad XRef entry for compressed object');
  3924. }
  3925. return xrefEntry;
  3926. },
  3927. fetchIfRefAsync: function XRef_fetchIfRefAsync(obj) {
  3928. if (!isRef(obj)) {
  3929. return Promise.resolve(obj);
  3930. }
  3931. return this.fetchAsync(obj);
  3932. },
  3933. fetchAsync: function XRef_fetchAsync(ref, suppressEncryption) {
  3934. var streamManager = this.stream.manager;
  3935. var xref = this;
  3936. return new Promise(function tryFetch(resolve, reject) {
  3937. try {
  3938. resolve(xref.fetch(ref, suppressEncryption));
  3939. } catch (e) {
  3940. if (e instanceof MissingDataException) {
  3941. streamManager.requestRange(e.begin, e.end, function () {
  3942. tryFetch(resolve, reject);
  3943. });
  3944. return;
  3945. }
  3946. reject(e);
  3947. }
  3948. });
  3949. },
  3950. getCatalogObj: function XRef_getCatalogObj() {
  3951. return this.root;
  3952. }
  3953. };
  3954. return XRef;
  3955. })();
  3956. /**
  3957. * A NameTree is like a Dict but has some advantageous properties, see the
  3958. * spec (7.9.6) for more details.
  3959. * TODO: implement all the Dict functions and make this more efficent.
  3960. */
  3961. var NameTree = (function NameTreeClosure() {
  3962. function NameTree(root, xref) {
  3963. this.root = root;
  3964. this.xref = xref;
  3965. }
  3966. NameTree.prototype = {
  3967. getAll: function NameTree_getAll() {
  3968. var dict = {};
  3969. if (!this.root) {
  3970. return dict;
  3971. }
  3972. var xref = this.xref;
  3973. // reading name tree
  3974. var processed = new RefSet();
  3975. processed.put(this.root);
  3976. var queue = [this.root];
  3977. while (queue.length > 0) {
  3978. var i, n;
  3979. var obj = xref.fetchIfRef(queue.shift());
  3980. if (!isDict(obj)) {
  3981. continue;
  3982. }
  3983. if (obj.has('Kids')) {
  3984. var kids = obj.get('Kids');
  3985. for (i = 0, n = kids.length; i < n; i++) {
  3986. var kid = kids[i];
  3987. if (processed.has(kid)) {
  3988. error('invalid destinations');
  3989. }
  3990. queue.push(kid);
  3991. processed.put(kid);
  3992. }
  3993. continue;
  3994. }
  3995. var names = obj.get('Names');
  3996. if (names) {
  3997. for (i = 0, n = names.length; i < n; i += 2) {
  3998. dict[names[i]] = xref.fetchIfRef(names[i + 1]);
  3999. }
  4000. }
  4001. }
  4002. return dict;
  4003. },
  4004. get: function NameTree_get(destinationId) {
  4005. if (!this.root) {
  4006. return null;
  4007. }
  4008. var xref = this.xref;
  4009. var kidsOrNames = xref.fetchIfRef(this.root);
  4010. var loopCount = 0;
  4011. var MAX_NAMES_LEVELS = 10;
  4012. var l, r, m;
  4013. // Perform a binary search to quickly find the entry that
  4014. // contains the named destination we are looking for.
  4015. while (kidsOrNames.has('Kids')) {
  4016. loopCount++;
  4017. if (loopCount > MAX_NAMES_LEVELS) {
  4018. warn('Search depth limit for named destionations has been reached.');
  4019. return null;
  4020. }
  4021. var kids = kidsOrNames.get('Kids');
  4022. if (!isArray(kids)) {
  4023. return null;
  4024. }
  4025. l = 0;
  4026. r = kids.length - 1;
  4027. while (l <= r) {
  4028. m = (l + r) >> 1;
  4029. var kid = xref.fetchIfRef(kids[m]);
  4030. var limits = kid.get('Limits');
  4031. if (destinationId < limits[0]) {
  4032. r = m - 1;
  4033. } else if (destinationId > limits[1]) {
  4034. l = m + 1;
  4035. } else {
  4036. kidsOrNames = xref.fetchIfRef(kids[m]);
  4037. break;
  4038. }
  4039. }
  4040. if (l > r) {
  4041. return null;
  4042. }
  4043. }
  4044. // If we get here, then we have found the right entry. Now
  4045. // go through the named destinations in the Named dictionary
  4046. // until we find the exact destination we're looking for.
  4047. var names = kidsOrNames.get('Names');
  4048. if (isArray(names)) {
  4049. // Perform a binary search to reduce the lookup time.
  4050. l = 0;
  4051. r = names.length - 2;
  4052. while (l <= r) {
  4053. // Check only even indices (0, 2, 4, ...) because the
  4054. // odd indices contain the actual D array.
  4055. m = (l + r) & ~1;
  4056. if (destinationId < names[m]) {
  4057. r = m - 2;
  4058. } else if (destinationId > names[m]) {
  4059. l = m + 2;
  4060. } else {
  4061. return xref.fetchIfRef(names[m + 1]);
  4062. }
  4063. }
  4064. }
  4065. return null;
  4066. }
  4067. };
  4068. return NameTree;
  4069. })();
  4070. /**
  4071. * "A PDF file can refer to the contents of another file by using a File
  4072. * Specification (PDF 1.1)", see the spec (7.11) for more details.
  4073. * NOTE: Only embedded files are supported (as part of the attachments support)
  4074. * TODO: support the 'URL' file system (with caching if !/V), portable
  4075. * collections attributes and related files (/RF)
  4076. */
  4077. var FileSpec = (function FileSpecClosure() {
  4078. function FileSpec(root, xref) {
  4079. if (!root || !isDict(root)) {
  4080. return;
  4081. }
  4082. this.xref = xref;
  4083. this.root = root;
  4084. if (root.has('FS')) {
  4085. this.fs = root.get('FS');
  4086. }
  4087. this.description = root.has('Desc') ?
  4088. stringToPDFString(root.get('Desc')) :
  4089. '';
  4090. if (root.has('RF')) {
  4091. warn('Related file specifications are not supported');
  4092. }
  4093. this.contentAvailable = true;
  4094. if (!root.has('EF')) {
  4095. this.contentAvailable = false;
  4096. warn('Non-embedded file specifications are not supported');
  4097. }
  4098. }
  4099. function pickPlatformItem(dict) {
  4100. // Look for the filename in this order:
  4101. // UF, F, Unix, Mac, DOS
  4102. if (dict.has('UF')) {
  4103. return dict.get('UF');
  4104. } else if (dict.has('F')) {
  4105. return dict.get('F');
  4106. } else if (dict.has('Unix')) {
  4107. return dict.get('Unix');
  4108. } else if (dict.has('Mac')) {
  4109. return dict.get('Mac');
  4110. } else if (dict.has('DOS')) {
  4111. return dict.get('DOS');
  4112. } else {
  4113. return null;
  4114. }
  4115. }
  4116. FileSpec.prototype = {
  4117. get filename() {
  4118. if (!this._filename && this.root) {
  4119. var filename = pickPlatformItem(this.root) || 'unnamed';
  4120. this._filename = stringToPDFString(filename).
  4121. replace(/\\\\/g, '\\').
  4122. replace(/\\\//g, '/').
  4123. replace(/\\/g, '/');
  4124. }
  4125. return this._filename;
  4126. },
  4127. get content() {
  4128. if (!this.contentAvailable) {
  4129. return null;
  4130. }
  4131. if (!this.contentRef && this.root) {
  4132. this.contentRef = pickPlatformItem(this.root.get('EF'));
  4133. }
  4134. var content = null;
  4135. if (this.contentRef) {
  4136. var xref = this.xref;
  4137. var fileObj = xref.fetchIfRef(this.contentRef);
  4138. if (fileObj && isStream(fileObj)) {
  4139. content = fileObj.getBytes();
  4140. } else {
  4141. warn('Embedded file specification points to non-existing/invalid ' +
  4142. 'content');
  4143. }
  4144. } else {
  4145. warn('Embedded file specification does not have a content');
  4146. }
  4147. return content;
  4148. },
  4149. get serializable() {
  4150. return {
  4151. filename: this.filename,
  4152. content: this.content
  4153. };
  4154. }
  4155. };
  4156. return FileSpec;
  4157. })();
  4158. /**
  4159. * A helper for loading missing data in object graphs. It traverses the graph
  4160. * depth first and queues up any objects that have missing data. Once it has
  4161. * has traversed as many objects that are available it attempts to bundle the
  4162. * missing data requests and then resume from the nodes that weren't ready.
  4163. *
  4164. * NOTE: It provides protection from circular references by keeping track of
  4165. * of loaded references. However, you must be careful not to load any graphs
  4166. * that have references to the catalog or other pages since that will cause the
  4167. * entire PDF document object graph to be traversed.
  4168. */
  4169. var ObjectLoader = (function() {
  4170. function mayHaveChildren(value) {
  4171. return isRef(value) || isDict(value) || isArray(value) || isStream(value);
  4172. }
  4173. function addChildren(node, nodesToVisit) {
  4174. var value;
  4175. if (isDict(node) || isStream(node)) {
  4176. var map;
  4177. if (isDict(node)) {
  4178. map = node.map;
  4179. } else {
  4180. map = node.dict.map;
  4181. }
  4182. for (var key in map) {
  4183. value = map[key];
  4184. if (mayHaveChildren(value)) {
  4185. nodesToVisit.push(value);
  4186. }
  4187. }
  4188. } else if (isArray(node)) {
  4189. for (var i = 0, ii = node.length; i < ii; i++) {
  4190. value = node[i];
  4191. if (mayHaveChildren(value)) {
  4192. nodesToVisit.push(value);
  4193. }
  4194. }
  4195. }
  4196. }
  4197. function ObjectLoader(obj, keys, xref) {
  4198. this.obj = obj;
  4199. this.keys = keys;
  4200. this.xref = xref;
  4201. this.refSet = null;
  4202. }
  4203. ObjectLoader.prototype = {
  4204. load: function ObjectLoader_load() {
  4205. var keys = this.keys;
  4206. this.capability = createPromiseCapability();
  4207. // Don't walk the graph if all the data is already loaded.
  4208. if (!(this.xref.stream instanceof ChunkedStream) ||
  4209. this.xref.stream.getMissingChunks().length === 0) {
  4210. this.capability.resolve();
  4211. return this.capability.promise;
  4212. }
  4213. this.refSet = new RefSet();
  4214. // Setup the initial nodes to visit.
  4215. var nodesToVisit = [];
  4216. for (var i = 0; i < keys.length; i++) {
  4217. nodesToVisit.push(this.obj[keys[i]]);
  4218. }
  4219. this.walk(nodesToVisit);
  4220. return this.capability.promise;
  4221. },
  4222. walk: function ObjectLoader_walk(nodesToVisit) {
  4223. var nodesToRevisit = [];
  4224. var pendingRequests = [];
  4225. // DFS walk of the object graph.
  4226. while (nodesToVisit.length) {
  4227. var currentNode = nodesToVisit.pop();
  4228. // Only references or chunked streams can cause missing data exceptions.
  4229. if (isRef(currentNode)) {
  4230. // Skip nodes that have already been visited.
  4231. if (this.refSet.has(currentNode)) {
  4232. continue;
  4233. }
  4234. try {
  4235. var ref = currentNode;
  4236. this.refSet.put(ref);
  4237. currentNode = this.xref.fetch(currentNode);
  4238. } catch (e) {
  4239. if (!(e instanceof MissingDataException)) {
  4240. throw e;
  4241. }
  4242. nodesToRevisit.push(currentNode);
  4243. pendingRequests.push({ begin: e.begin, end: e.end });
  4244. }
  4245. }
  4246. if (currentNode && currentNode.getBaseStreams) {
  4247. var baseStreams = currentNode.getBaseStreams();
  4248. var foundMissingData = false;
  4249. for (var i = 0; i < baseStreams.length; i++) {
  4250. var stream = baseStreams[i];
  4251. if (stream.getMissingChunks && stream.getMissingChunks().length) {
  4252. foundMissingData = true;
  4253. pendingRequests.push({
  4254. begin: stream.start,
  4255. end: stream.end
  4256. });
  4257. }
  4258. }
  4259. if (foundMissingData) {
  4260. nodesToRevisit.push(currentNode);
  4261. }
  4262. }
  4263. addChildren(currentNode, nodesToVisit);
  4264. }
  4265. if (pendingRequests.length) {
  4266. this.xref.stream.manager.requestRanges(pendingRequests,
  4267. function pendingRequestCallback() {
  4268. nodesToVisit = nodesToRevisit;
  4269. for (var i = 0; i < nodesToRevisit.length; i++) {
  4270. var node = nodesToRevisit[i];
  4271. // Remove any reference nodes from the currrent refset so they
  4272. // aren't skipped when we revist them.
  4273. if (isRef(node)) {
  4274. this.refSet.remove(node);
  4275. }
  4276. }
  4277. this.walk(nodesToVisit);
  4278. }.bind(this));
  4279. return;
  4280. }
  4281. // Everything is loaded.
  4282. this.refSet = null;
  4283. this.capability.resolve();
  4284. }
  4285. };
  4286. return ObjectLoader;
  4287. })();
  4288. var ISOAdobeCharset = [
  4289. '.notdef', 'space', 'exclam', 'quotedbl', 'numbersign', 'dollar',
  4290. 'percent', 'ampersand', 'quoteright', 'parenleft', 'parenright',
  4291. 'asterisk', 'plus', 'comma', 'hyphen', 'period', 'slash', 'zero',
  4292. 'one', 'two', 'three', 'four', 'five', 'six', 'seven', 'eight',
  4293. 'nine', 'colon', 'semicolon', 'less', 'equal', 'greater', 'question',
  4294. 'at', 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M',
  4295. 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z',
  4296. 'bracketleft', 'backslash', 'bracketright', 'asciicircum', 'underscore',
  4297. 'quoteleft', 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l',
  4298. 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z',
  4299. 'braceleft', 'bar', 'braceright', 'asciitilde', 'exclamdown', 'cent',
  4300. 'sterling', 'fraction', 'yen', 'florin', 'section', 'currency',
  4301. 'quotesingle', 'quotedblleft', 'guillemotleft', 'guilsinglleft',
  4302. 'guilsinglright', 'fi', 'fl', 'endash', 'dagger', 'daggerdbl',
  4303. 'periodcentered', 'paragraph', 'bullet', 'quotesinglbase',
  4304. 'quotedblbase', 'quotedblright', 'guillemotright', 'ellipsis',
  4305. 'perthousand', 'questiondown', 'grave', 'acute', 'circumflex', 'tilde',
  4306. 'macron', 'breve', 'dotaccent', 'dieresis', 'ring', 'cedilla',
  4307. 'hungarumlaut', 'ogonek', 'caron', 'emdash', 'AE', 'ordfeminine',
  4308. 'Lslash', 'Oslash', 'OE', 'ordmasculine', 'ae', 'dotlessi', 'lslash',
  4309. 'oslash', 'oe', 'germandbls', 'onesuperior', 'logicalnot', 'mu',
  4310. 'trademark', 'Eth', 'onehalf', 'plusminus', 'Thorn', 'onequarter',
  4311. 'divide', 'brokenbar', 'degree', 'thorn', 'threequarters', 'twosuperior',
  4312. 'registered', 'minus', 'eth', 'multiply', 'threesuperior', 'copyright',
  4313. 'Aacute', 'Acircumflex', 'Adieresis', 'Agrave', 'Aring', 'Atilde',
  4314. 'Ccedilla', 'Eacute', 'Ecircumflex', 'Edieresis', 'Egrave', 'Iacute',
  4315. 'Icircumflex', 'Idieresis', 'Igrave', 'Ntilde', 'Oacute', 'Ocircumflex',
  4316. 'Odieresis', 'Ograve', 'Otilde', 'Scaron', 'Uacute', 'Ucircumflex',
  4317. 'Udieresis', 'Ugrave', 'Yacute', 'Ydieresis', 'Zcaron', 'aacute',
  4318. 'acircumflex', 'adieresis', 'agrave', 'aring', 'atilde', 'ccedilla',
  4319. 'eacute', 'ecircumflex', 'edieresis', 'egrave', 'iacute', 'icircumflex',
  4320. 'idieresis', 'igrave', 'ntilde', 'oacute', 'ocircumflex', 'odieresis',
  4321. 'ograve', 'otilde', 'scaron', 'uacute', 'ucircumflex', 'udieresis',
  4322. 'ugrave', 'yacute', 'ydieresis', 'zcaron'
  4323. ];
  4324. var ExpertCharset = [
  4325. '.notdef', 'space', 'exclamsmall', 'Hungarumlautsmall', 'dollaroldstyle',
  4326. 'dollarsuperior', 'ampersandsmall', 'Acutesmall', 'parenleftsuperior',
  4327. 'parenrightsuperior', 'twodotenleader', 'onedotenleader', 'comma',
  4328. 'hyphen', 'period', 'fraction', 'zerooldstyle', 'oneoldstyle',
  4329. 'twooldstyle', 'threeoldstyle', 'fouroldstyle', 'fiveoldstyle',
  4330. 'sixoldstyle', 'sevenoldstyle', 'eightoldstyle', 'nineoldstyle',
  4331. 'colon', 'semicolon', 'commasuperior', 'threequartersemdash',
  4332. 'periodsuperior', 'questionsmall', 'asuperior', 'bsuperior',
  4333. 'centsuperior', 'dsuperior', 'esuperior', 'isuperior', 'lsuperior',
  4334. 'msuperior', 'nsuperior', 'osuperior', 'rsuperior', 'ssuperior',
  4335. 'tsuperior', 'ff', 'fi', 'fl', 'ffi', 'ffl', 'parenleftinferior',
  4336. 'parenrightinferior', 'Circumflexsmall', 'hyphensuperior', 'Gravesmall',
  4337. 'Asmall', 'Bsmall', 'Csmall', 'Dsmall', 'Esmall', 'Fsmall', 'Gsmall',
  4338. 'Hsmall', 'Ismall', 'Jsmall', 'Ksmall', 'Lsmall', 'Msmall', 'Nsmall',
  4339. 'Osmall', 'Psmall', 'Qsmall', 'Rsmall', 'Ssmall', 'Tsmall', 'Usmall',
  4340. 'Vsmall', 'Wsmall', 'Xsmall', 'Ysmall', 'Zsmall', 'colonmonetary',
  4341. 'onefitted', 'rupiah', 'Tildesmall', 'exclamdownsmall', 'centoldstyle',
  4342. 'Lslashsmall', 'Scaronsmall', 'Zcaronsmall', 'Dieresissmall',
  4343. 'Brevesmall', 'Caronsmall', 'Dotaccentsmall', 'Macronsmall',
  4344. 'figuredash', 'hypheninferior', 'Ogoneksmall', 'Ringsmall',
  4345. 'Cedillasmall', 'onequarter', 'onehalf', 'threequarters',
  4346. 'questiondownsmall', 'oneeighth', 'threeeighths', 'fiveeighths',
  4347. 'seveneighths', 'onethird', 'twothirds', 'zerosuperior', 'onesuperior',
  4348. 'twosuperior', 'threesuperior', 'foursuperior', 'fivesuperior',
  4349. 'sixsuperior', 'sevensuperior', 'eightsuperior', 'ninesuperior',
  4350. 'zeroinferior', 'oneinferior', 'twoinferior', 'threeinferior',
  4351. 'fourinferior', 'fiveinferior', 'sixinferior', 'seveninferior',
  4352. 'eightinferior', 'nineinferior', 'centinferior', 'dollarinferior',
  4353. 'periodinferior', 'commainferior', 'Agravesmall', 'Aacutesmall',
  4354. 'Acircumflexsmall', 'Atildesmall', 'Adieresissmall', 'Aringsmall',
  4355. 'AEsmall', 'Ccedillasmall', 'Egravesmall', 'Eacutesmall',
  4356. 'Ecircumflexsmall', 'Edieresissmall', 'Igravesmall', 'Iacutesmall',
  4357. 'Icircumflexsmall', 'Idieresissmall', 'Ethsmall', 'Ntildesmall',
  4358. 'Ogravesmall', 'Oacutesmall', 'Ocircumflexsmall', 'Otildesmall',
  4359. 'Odieresissmall', 'OEsmall', 'Oslashsmall', 'Ugravesmall', 'Uacutesmall',
  4360. 'Ucircumflexsmall', 'Udieresissmall', 'Yacutesmall', 'Thornsmall',
  4361. 'Ydieresissmall'
  4362. ];
  4363. var ExpertSubsetCharset = [
  4364. '.notdef', 'space', 'dollaroldstyle', 'dollarsuperior',
  4365. 'parenleftsuperior', 'parenrightsuperior', 'twodotenleader',
  4366. 'onedotenleader', 'comma', 'hyphen', 'period', 'fraction',
  4367. 'zerooldstyle', 'oneoldstyle', 'twooldstyle', 'threeoldstyle',
  4368. 'fouroldstyle', 'fiveoldstyle', 'sixoldstyle', 'sevenoldstyle',
  4369. 'eightoldstyle', 'nineoldstyle', 'colon', 'semicolon', 'commasuperior',
  4370. 'threequartersemdash', 'periodsuperior', 'asuperior', 'bsuperior',
  4371. 'centsuperior', 'dsuperior', 'esuperior', 'isuperior', 'lsuperior',
  4372. 'msuperior', 'nsuperior', 'osuperior', 'rsuperior', 'ssuperior',
  4373. 'tsuperior', 'ff', 'fi', 'fl', 'ffi', 'ffl', 'parenleftinferior',
  4374. 'parenrightinferior', 'hyphensuperior', 'colonmonetary', 'onefitted',
  4375. 'rupiah', 'centoldstyle', 'figuredash', 'hypheninferior', 'onequarter',
  4376. 'onehalf', 'threequarters', 'oneeighth', 'threeeighths', 'fiveeighths',
  4377. 'seveneighths', 'onethird', 'twothirds', 'zerosuperior', 'onesuperior',
  4378. 'twosuperior', 'threesuperior', 'foursuperior', 'fivesuperior',
  4379. 'sixsuperior', 'sevensuperior', 'eightsuperior', 'ninesuperior',
  4380. 'zeroinferior', 'oneinferior', 'twoinferior', 'threeinferior',
  4381. 'fourinferior', 'fiveinferior', 'sixinferior', 'seveninferior',
  4382. 'eightinferior', 'nineinferior', 'centinferior', 'dollarinferior',
  4383. 'periodinferior', 'commainferior'
  4384. ];
  4385. var DEFAULT_ICON_SIZE = 22; // px
  4386. var SUPPORTED_TYPES = ['Link', 'Text', 'Widget'];
  4387. var Annotation = (function AnnotationClosure() {
  4388. // 12.5.5: Algorithm: Appearance streams
  4389. function getTransformMatrix(rect, bbox, matrix) {
  4390. var bounds = Util.getAxialAlignedBoundingBox(bbox, matrix);
  4391. var minX = bounds[0];
  4392. var minY = bounds[1];
  4393. var maxX = bounds[2];
  4394. var maxY = bounds[3];
  4395. if (minX === maxX || minY === maxY) {
  4396. // From real-life file, bbox was [0, 0, 0, 0]. In this case,
  4397. // just apply the transform for rect
  4398. return [1, 0, 0, 1, rect[0], rect[1]];
  4399. }
  4400. var xRatio = (rect[2] - rect[0]) / (maxX - minX);
  4401. var yRatio = (rect[3] - rect[1]) / (maxY - minY);
  4402. return [
  4403. xRatio,
  4404. 0,
  4405. 0,
  4406. yRatio,
  4407. rect[0] - minX * xRatio,
  4408. rect[1] - minY * yRatio
  4409. ];
  4410. }
  4411. function getDefaultAppearance(dict) {
  4412. var appearanceState = dict.get('AP');
  4413. if (!isDict(appearanceState)) {
  4414. return;
  4415. }
  4416. var appearance;
  4417. var appearances = appearanceState.get('N');
  4418. if (isDict(appearances)) {
  4419. var as = dict.get('AS');
  4420. if (as && appearances.has(as.name)) {
  4421. appearance = appearances.get(as.name);
  4422. }
  4423. } else {
  4424. appearance = appearances;
  4425. }
  4426. return appearance;
  4427. }
  4428. function Annotation(params) {
  4429. var dict = params.dict;
  4430. var data = this.data = {};
  4431. data.subtype = dict.get('Subtype').name;
  4432. var rect = dict.get('Rect') || [0, 0, 0, 0];
  4433. data.rect = Util.normalizeRect(rect);
  4434. data.annotationFlags = dict.get('F');
  4435. var color = dict.get('C');
  4436. if (!color) {
  4437. // The PDF spec does not mention how a missing color array is interpreted.
  4438. // Adobe Reader seems to default to black in this case.
  4439. data.color = [0, 0, 0];
  4440. } else if (isArray(color)) {
  4441. switch (color.length) {
  4442. case 0:
  4443. // Empty array denotes transparent border.
  4444. data.color = null;
  4445. break;
  4446. case 1:
  4447. // TODO: implement DeviceGray
  4448. break;
  4449. case 3:
  4450. data.color = color;
  4451. break;
  4452. case 4:
  4453. // TODO: implement DeviceCMYK
  4454. break;
  4455. }
  4456. }
  4457. // Some types of annotations have border style dict which has more
  4458. // info than the border array
  4459. if (dict.has('BS')) {
  4460. var borderStyle = dict.get('BS');
  4461. data.borderWidth = borderStyle.has('W') ? borderStyle.get('W') : 1;
  4462. } else {
  4463. var borderArray = dict.get('Border') || [0, 0, 1];
  4464. data.borderWidth = borderArray[2] || 0;
  4465. // TODO: implement proper support for annotations with line dash patterns.
  4466. var dashArray = borderArray[3];
  4467. if (data.borderWidth > 0 && dashArray) {
  4468. if (!isArray(dashArray)) {
  4469. // Ignore the border if dashArray is not actually an array,
  4470. // this is consistent with the behaviour in Adobe Reader.
  4471. data.borderWidth = 0;
  4472. } else {
  4473. var dashArrayLength = dashArray.length;
  4474. if (dashArrayLength > 0) {
  4475. // According to the PDF specification: the elements in a dashArray
  4476. // shall be numbers that are nonnegative and not all equal to zero.
  4477. var isInvalid = false;
  4478. var numPositive = 0;
  4479. for (var i = 0; i < dashArrayLength; i++) {
  4480. var validNumber = (+dashArray[i] >= 0);
  4481. if (!validNumber) {
  4482. isInvalid = true;
  4483. break;
  4484. } else if (dashArray[i] > 0) {
  4485. numPositive++;
  4486. }
  4487. }
  4488. if (isInvalid || numPositive === 0) {
  4489. data.borderWidth = 0;
  4490. }
  4491. }
  4492. }
  4493. }
  4494. }
  4495. this.appearance = getDefaultAppearance(dict);
  4496. data.hasAppearance = !!this.appearance;
  4497. data.id = params.ref.num;
  4498. }
  4499. Annotation.prototype = {
  4500. getData: function Annotation_getData() {
  4501. return this.data;
  4502. },
  4503. isInvisible: function Annotation_isInvisible() {
  4504. var data = this.data;
  4505. if (data && SUPPORTED_TYPES.indexOf(data.subtype) !== -1) {
  4506. return false;
  4507. } else {
  4508. return !!(data &&
  4509. data.annotationFlags && // Default: not invisible
  4510. data.annotationFlags & 0x1); // Invisible
  4511. }
  4512. },
  4513. isViewable: function Annotation_isViewable() {
  4514. var data = this.data;
  4515. return !!(!this.isInvisible() &&
  4516. data &&
  4517. (!data.annotationFlags ||
  4518. !(data.annotationFlags & 0x22)) && // Hidden or NoView
  4519. data.rect); // rectangle is necessary
  4520. },
  4521. isPrintable: function Annotation_isPrintable() {
  4522. var data = this.data;
  4523. return !!(!this.isInvisible() &&
  4524. data &&
  4525. data.annotationFlags && // Default: not printable
  4526. data.annotationFlags & 0x4 && // Print
  4527. !(data.annotationFlags & 0x2) && // Hidden
  4528. data.rect); // rectangle is necessary
  4529. },
  4530. loadResources: function Annotation_loadResources(keys) {
  4531. return new Promise(function (resolve, reject) {
  4532. this.appearance.dict.getAsync('Resources').then(function (resources) {
  4533. if (!resources) {
  4534. resolve();
  4535. return;
  4536. }
  4537. var objectLoader = new ObjectLoader(resources.map,
  4538. keys,
  4539. resources.xref);
  4540. objectLoader.load().then(function() {
  4541. resolve(resources);
  4542. }, reject);
  4543. }, reject);
  4544. }.bind(this));
  4545. },
  4546. getOperatorList: function Annotation_getOperatorList(evaluator) {
  4547. if (!this.appearance) {
  4548. return Promise.resolve(new OperatorList());
  4549. }
  4550. var data = this.data;
  4551. var appearanceDict = this.appearance.dict;
  4552. var resourcesPromise = this.loadResources([
  4553. 'ExtGState',
  4554. 'ColorSpace',
  4555. 'Pattern',
  4556. 'Shading',
  4557. 'XObject',
  4558. 'Font'
  4559. // ProcSet
  4560. // Properties
  4561. ]);
  4562. var bbox = appearanceDict.get('BBox') || [0, 0, 1, 1];
  4563. var matrix = appearanceDict.get('Matrix') || [1, 0, 0, 1, 0 ,0];
  4564. var transform = getTransformMatrix(data.rect, bbox, matrix);
  4565. var self = this;
  4566. return resourcesPromise.then(function(resources) {
  4567. var opList = new OperatorList();
  4568. opList.addOp(OPS.beginAnnotation, [data.rect, transform, matrix]);
  4569. return evaluator.getOperatorList(self.appearance, resources, opList).
  4570. then(function () {
  4571. opList.addOp(OPS.endAnnotation, []);
  4572. self.appearance.reset();
  4573. return opList;
  4574. });
  4575. });
  4576. }
  4577. };
  4578. Annotation.getConstructor =
  4579. function Annotation_getConstructor(subtype, fieldType) {
  4580. if (!subtype) {
  4581. return;
  4582. }
  4583. // TODO(mack): Implement FreeText annotations
  4584. if (subtype === 'Link') {
  4585. return LinkAnnotation;
  4586. } else if (subtype === 'Text') {
  4587. return TextAnnotation;
  4588. } else if (subtype === 'Widget') {
  4589. if (!fieldType) {
  4590. return;
  4591. }
  4592. if (fieldType === 'Tx') {
  4593. return TextWidgetAnnotation;
  4594. } else {
  4595. return WidgetAnnotation;
  4596. }
  4597. } else {
  4598. return Annotation;
  4599. }
  4600. };
  4601. Annotation.fromRef = function Annotation_fromRef(xref, ref) {
  4602. var dict = xref.fetchIfRef(ref);
  4603. if (!isDict(dict)) {
  4604. return;
  4605. }
  4606. var subtype = dict.get('Subtype');
  4607. subtype = isName(subtype) ? subtype.name : '';
  4608. if (!subtype) {
  4609. return;
  4610. }
  4611. var fieldType = Util.getInheritableProperty(dict, 'FT');
  4612. fieldType = isName(fieldType) ? fieldType.name : '';
  4613. var Constructor = Annotation.getConstructor(subtype, fieldType);
  4614. if (!Constructor) {
  4615. return;
  4616. }
  4617. var params = {
  4618. dict: dict,
  4619. ref: ref,
  4620. };
  4621. var annotation = new Constructor(params);
  4622. if (annotation.isViewable() || annotation.isPrintable()) {
  4623. return annotation;
  4624. } else {
  4625. if (SUPPORTED_TYPES.indexOf(subtype) === -1) {
  4626. warn('unimplemented annotation type: ' + subtype);
  4627. }
  4628. }
  4629. };
  4630. Annotation.appendToOperatorList = function Annotation_appendToOperatorList(
  4631. annotations, opList, pdfManager, partialEvaluator, intent) {
  4632. function reject(e) {
  4633. annotationsReadyCapability.reject(e);
  4634. }
  4635. var annotationsReadyCapability = createPromiseCapability();
  4636. var annotationPromises = [];
  4637. for (var i = 0, n = annotations.length; i < n; ++i) {
  4638. if (intent === 'display' && annotations[i].isViewable() ||
  4639. intent === 'print' && annotations[i].isPrintable()) {
  4640. annotationPromises.push(
  4641. annotations[i].getOperatorList(partialEvaluator));
  4642. }
  4643. }
  4644. Promise.all(annotationPromises).then(function(datas) {
  4645. opList.addOp(OPS.beginAnnotations, []);
  4646. for (var i = 0, n = datas.length; i < n; ++i) {
  4647. var annotOpList = datas[i];
  4648. opList.addOpList(annotOpList);
  4649. }
  4650. opList.addOp(OPS.endAnnotations, []);
  4651. annotationsReadyCapability.resolve();
  4652. }, reject);
  4653. return annotationsReadyCapability.promise;
  4654. };
  4655. return Annotation;
  4656. })();
  4657. var WidgetAnnotation = (function WidgetAnnotationClosure() {
  4658. function WidgetAnnotation(params) {
  4659. Annotation.call(this, params);
  4660. var dict = params.dict;
  4661. var data = this.data;
  4662. data.fieldValue = stringToPDFString(
  4663. Util.getInheritableProperty(dict, 'V') || '');
  4664. data.alternativeText = stringToPDFString(dict.get('TU') || '');
  4665. data.defaultAppearance = Util.getInheritableProperty(dict, 'DA') || '';
  4666. var fieldType = Util.getInheritableProperty(dict, 'FT');
  4667. data.fieldType = isName(fieldType) ? fieldType.name : '';
  4668. data.fieldFlags = Util.getInheritableProperty(dict, 'Ff') || 0;
  4669. this.fieldResources = Util.getInheritableProperty(dict, 'DR') || Dict.empty;
  4670. // Building the full field name by collecting the field and
  4671. // its ancestors 'T' data and joining them using '.'.
  4672. var fieldName = [];
  4673. var namedItem = dict;
  4674. var ref = params.ref;
  4675. while (namedItem) {
  4676. var parent = namedItem.get('Parent');
  4677. var parentRef = namedItem.getRaw('Parent');
  4678. var name = namedItem.get('T');
  4679. if (name) {
  4680. fieldName.unshift(stringToPDFString(name));
  4681. } else if (parent && ref) {
  4682. // The field name is absent, that means more than one field
  4683. // with the same name may exist. Replacing the empty name
  4684. // with the '`' plus index in the parent's 'Kids' array.
  4685. // This is not in the PDF spec but necessary to id the
  4686. // the input controls.
  4687. var kids = parent.get('Kids');
  4688. var j, jj;
  4689. for (j = 0, jj = kids.length; j < jj; j++) {
  4690. var kidRef = kids[j];
  4691. if (kidRef.num === ref.num && kidRef.gen === ref.gen) {
  4692. break;
  4693. }
  4694. }
  4695. fieldName.unshift('`' + j);
  4696. }
  4697. namedItem = parent;
  4698. ref = parentRef;
  4699. }
  4700. data.fullName = fieldName.join('.');
  4701. }
  4702. var parent = Annotation.prototype;
  4703. Util.inherit(WidgetAnnotation, Annotation, {
  4704. isViewable: function WidgetAnnotation_isViewable() {
  4705. if (this.data.fieldType === 'Sig') {
  4706. warn('unimplemented annotation type: Widget signature');
  4707. return false;
  4708. }
  4709. return parent.isViewable.call(this);
  4710. }
  4711. });
  4712. return WidgetAnnotation;
  4713. })();
  4714. var TextWidgetAnnotation = (function TextWidgetAnnotationClosure() {
  4715. function TextWidgetAnnotation(params) {
  4716. WidgetAnnotation.call(this, params);
  4717. this.data.textAlignment = Util.getInheritableProperty(params.dict, 'Q');
  4718. this.data.annotationType = AnnotationType.WIDGET;
  4719. this.data.hasHtml = !this.data.hasAppearance && !!this.data.fieldValue;
  4720. }
  4721. Util.inherit(TextWidgetAnnotation, WidgetAnnotation, {
  4722. getOperatorList: function TextWidgetAnnotation_getOperatorList(evaluator) {
  4723. if (this.appearance) {
  4724. return Annotation.prototype.getOperatorList.call(this, evaluator);
  4725. }
  4726. var opList = new OperatorList();
  4727. var data = this.data;
  4728. // Even if there is an appearance stream, ignore it. This is the
  4729. // behaviour used by Adobe Reader.
  4730. if (!data.defaultAppearance) {
  4731. return Promise.resolve(opList);
  4732. }
  4733. var stream = new Stream(stringToBytes(data.defaultAppearance));
  4734. return evaluator.getOperatorList(stream, this.fieldResources, opList).
  4735. then(function () {
  4736. return opList;
  4737. });
  4738. }
  4739. });
  4740. return TextWidgetAnnotation;
  4741. })();
  4742. var InteractiveAnnotation = (function InteractiveAnnotationClosure() {
  4743. function InteractiveAnnotation(params) {
  4744. Annotation.call(this, params);
  4745. this.data.hasHtml = true;
  4746. }
  4747. Util.inherit(InteractiveAnnotation, Annotation, { });
  4748. return InteractiveAnnotation;
  4749. })();
  4750. var TextAnnotation = (function TextAnnotationClosure() {
  4751. function TextAnnotation(params) {
  4752. InteractiveAnnotation.call(this, params);
  4753. var dict = params.dict;
  4754. var data = this.data;
  4755. var content = dict.get('Contents');
  4756. var title = dict.get('T');
  4757. data.annotationType = AnnotationType.TEXT;
  4758. data.content = stringToPDFString(content || '');
  4759. data.title = stringToPDFString(title || '');
  4760. if (data.hasAppearance) {
  4761. data.name = 'NoIcon';
  4762. } else {
  4763. data.rect[1] = data.rect[3] - DEFAULT_ICON_SIZE;
  4764. data.rect[2] = data.rect[0] + DEFAULT_ICON_SIZE;
  4765. data.name = dict.has('Name') ? dict.get('Name').name : 'Note';
  4766. }
  4767. if (dict.has('C')) {
  4768. data.hasBgColor = true;
  4769. }
  4770. }
  4771. Util.inherit(TextAnnotation, InteractiveAnnotation, { });
  4772. return TextAnnotation;
  4773. })();
  4774. var LinkAnnotation = (function LinkAnnotationClosure() {
  4775. function LinkAnnotation(params) {
  4776. InteractiveAnnotation.call(this, params);
  4777. var dict = params.dict;
  4778. var data = this.data;
  4779. data.annotationType = AnnotationType.LINK;
  4780. var action = dict.get('A');
  4781. if (action && isDict(action)) {
  4782. var linkType = action.get('S').name;
  4783. if (linkType === 'URI') {
  4784. var url = action.get('URI');
  4785. if (isName(url)) {
  4786. // Some bad PDFs do not put parentheses around relative URLs.
  4787. url = '/' + url.name;
  4788. } else if (url) {
  4789. url = addDefaultProtocolToUrl(url);
  4790. }
  4791. // TODO: pdf spec mentions urls can be relative to a Base
  4792. // entry in the dictionary.
  4793. if (!isValidUrl(url, false)) {
  4794. url = '';
  4795. }
  4796. data.url = url;
  4797. } else if (linkType === 'GoTo') {
  4798. data.dest = action.get('D');
  4799. } else if (linkType === 'GoToR') {
  4800. var urlDict = action.get('F');
  4801. if (isDict(urlDict)) {
  4802. // We assume that the 'url' is a Filspec dictionary
  4803. // and fetch the url without checking any further
  4804. url = urlDict.get('F') || '';
  4805. }
  4806. // TODO: pdf reference says that GoToR
  4807. // can also have 'NewWindow' attribute
  4808. if (!isValidUrl(url, false)) {
  4809. url = '';
  4810. }
  4811. data.url = url;
  4812. data.dest = action.get('D');
  4813. } else if (linkType === 'Named') {
  4814. data.action = action.get('N').name;
  4815. } else {
  4816. warn('unrecognized link type: ' + linkType);
  4817. }
  4818. } else if (dict.has('Dest')) {
  4819. // simple destination link
  4820. var dest = dict.get('Dest');
  4821. data.dest = isName(dest) ? dest.name : dest;
  4822. }
  4823. }
  4824. // Lets URLs beginning with 'www.' default to using the 'http://' protocol.
  4825. function addDefaultProtocolToUrl(url) {
  4826. if (url && url.indexOf('www.') === 0) {
  4827. return ('http://' + url);
  4828. }
  4829. return url;
  4830. }
  4831. Util.inherit(LinkAnnotation, InteractiveAnnotation, { });
  4832. return LinkAnnotation;
  4833. })();
  4834. var PDFFunction = (function PDFFunctionClosure() {
  4835. var CONSTRUCT_SAMPLED = 0;
  4836. var CONSTRUCT_INTERPOLATED = 2;
  4837. var CONSTRUCT_STICHED = 3;
  4838. var CONSTRUCT_POSTSCRIPT = 4;
  4839. return {
  4840. getSampleArray: function PDFFunction_getSampleArray(size, outputSize, bps,
  4841. str) {
  4842. var i, ii;
  4843. var length = 1;
  4844. for (i = 0, ii = size.length; i < ii; i++) {
  4845. length *= size[i];
  4846. }
  4847. length *= outputSize;
  4848. var array = new Array(length);
  4849. var codeSize = 0;
  4850. var codeBuf = 0;
  4851. // 32 is a valid bps so shifting won't work
  4852. var sampleMul = 1.0 / (Math.pow(2.0, bps) - 1);
  4853. var strBytes = str.getBytes((length * bps + 7) / 8);
  4854. var strIdx = 0;
  4855. for (i = 0; i < length; i++) {
  4856. while (codeSize < bps) {
  4857. codeBuf <<= 8;
  4858. codeBuf |= strBytes[strIdx++];
  4859. codeSize += 8;
  4860. }
  4861. codeSize -= bps;
  4862. array[i] = (codeBuf >> codeSize) * sampleMul;
  4863. codeBuf &= (1 << codeSize) - 1;
  4864. }
  4865. return array;
  4866. },
  4867. getIR: function PDFFunction_getIR(xref, fn) {
  4868. var dict = fn.dict;
  4869. if (!dict) {
  4870. dict = fn;
  4871. }
  4872. var types = [this.constructSampled,
  4873. null,
  4874. this.constructInterpolated,
  4875. this.constructStiched,
  4876. this.constructPostScript];
  4877. var typeNum = dict.get('FunctionType');
  4878. var typeFn = types[typeNum];
  4879. if (!typeFn) {
  4880. error('Unknown type of function');
  4881. }
  4882. return typeFn.call(this, fn, dict, xref);
  4883. },
  4884. fromIR: function PDFFunction_fromIR(IR) {
  4885. var type = IR[0];
  4886. switch (type) {
  4887. case CONSTRUCT_SAMPLED:
  4888. return this.constructSampledFromIR(IR);
  4889. case CONSTRUCT_INTERPOLATED:
  4890. return this.constructInterpolatedFromIR(IR);
  4891. case CONSTRUCT_STICHED:
  4892. return this.constructStichedFromIR(IR);
  4893. //case CONSTRUCT_POSTSCRIPT:
  4894. default:
  4895. return this.constructPostScriptFromIR(IR);
  4896. }
  4897. },
  4898. parse: function PDFFunction_parse(xref, fn) {
  4899. var IR = this.getIR(xref, fn);
  4900. return this.fromIR(IR);
  4901. },
  4902. parseArray: function PDFFunction_parseArray(xref, fnObj) {
  4903. if (!isArray(fnObj)) {
  4904. // not an array -- parsing as regular function
  4905. return this.parse(xref, fnObj);
  4906. }
  4907. var fnArray = [];
  4908. for (var j = 0, jj = fnObj.length; j < jj; j++) {
  4909. var obj = xref.fetchIfRef(fnObj[j]);
  4910. fnArray.push(PDFFunction.parse(xref, obj));
  4911. }
  4912. return function (src, srcOffset, dest, destOffset) {
  4913. for (var i = 0, ii = fnArray.length; i < ii; i++) {
  4914. fnArray[i](src, srcOffset, dest, destOffset + i);
  4915. }
  4916. };
  4917. },
  4918. constructSampled: function PDFFunction_constructSampled(str, dict) {
  4919. function toMultiArray(arr) {
  4920. var inputLength = arr.length;
  4921. var out = [];
  4922. var index = 0;
  4923. for (var i = 0; i < inputLength; i += 2) {
  4924. out[index] = [arr[i], arr[i + 1]];
  4925. ++index;
  4926. }
  4927. return out;
  4928. }
  4929. var domain = dict.get('Domain');
  4930. var range = dict.get('Range');
  4931. if (!domain || !range) {
  4932. error('No domain or range');
  4933. }
  4934. var inputSize = domain.length / 2;
  4935. var outputSize = range.length / 2;
  4936. domain = toMultiArray(domain);
  4937. range = toMultiArray(range);
  4938. var size = dict.get('Size');
  4939. var bps = dict.get('BitsPerSample');
  4940. var order = dict.get('Order') || 1;
  4941. if (order !== 1) {
  4942. // No description how cubic spline interpolation works in PDF32000:2008
  4943. // As in poppler, ignoring order, linear interpolation may work as good
  4944. info('No support for cubic spline interpolation: ' + order);
  4945. }
  4946. var encode = dict.get('Encode');
  4947. if (!encode) {
  4948. encode = [];
  4949. for (var i = 0; i < inputSize; ++i) {
  4950. encode.push(0);
  4951. encode.push(size[i] - 1);
  4952. }
  4953. }
  4954. encode = toMultiArray(encode);
  4955. var decode = dict.get('Decode');
  4956. if (!decode) {
  4957. decode = range;
  4958. } else {
  4959. decode = toMultiArray(decode);
  4960. }
  4961. var samples = this.getSampleArray(size, outputSize, bps, str);
  4962. return [
  4963. CONSTRUCT_SAMPLED, inputSize, domain, encode, decode, samples, size,
  4964. outputSize, Math.pow(2, bps) - 1, range
  4965. ];
  4966. },
  4967. constructSampledFromIR: function PDFFunction_constructSampledFromIR(IR) {
  4968. // See chapter 3, page 109 of the PDF reference
  4969. function interpolate(x, xmin, xmax, ymin, ymax) {
  4970. return ymin + ((x - xmin) * ((ymax - ymin) / (xmax - xmin)));
  4971. }
  4972. return function constructSampledFromIRResult(src, srcOffset,
  4973. dest, destOffset) {
  4974. // See chapter 3, page 110 of the PDF reference.
  4975. var m = IR[1];
  4976. var domain = IR[2];
  4977. var encode = IR[3];
  4978. var decode = IR[4];
  4979. var samples = IR[5];
  4980. var size = IR[6];
  4981. var n = IR[7];
  4982. //var mask = IR[8];
  4983. var range = IR[9];
  4984. // Building the cube vertices: its part and sample index
  4985. // http://rjwagner49.com/Mathematics/Interpolation.pdf
  4986. var cubeVertices = 1 << m;
  4987. var cubeN = new Float64Array(cubeVertices);
  4988. var cubeVertex = new Uint32Array(cubeVertices);
  4989. var i, j;
  4990. for (j = 0; j < cubeVertices; j++) {
  4991. cubeN[j] = 1;
  4992. }
  4993. var k = n, pos = 1;
  4994. // Map x_i to y_j for 0 <= i < m using the sampled function.
  4995. for (i = 0; i < m; ++i) {
  4996. // x_i' = min(max(x_i, Domain_2i), Domain_2i+1)
  4997. var domain_2i = domain[i][0];
  4998. var domain_2i_1 = domain[i][1];
  4999. var xi = Math.min(Math.max(src[srcOffset +i], domain_2i),
  5000. domain_2i_1);
  5001. // e_i = Interpolate(x_i', Domain_2i, Domain_2i+1,
  5002. // Encode_2i, Encode_2i+1)
  5003. var e = interpolate(xi, domain_2i, domain_2i_1,
  5004. encode[i][0], encode[i][1]);
  5005. // e_i' = min(max(e_i, 0), Size_i - 1)
  5006. var size_i = size[i];
  5007. e = Math.min(Math.max(e, 0), size_i - 1);
  5008. // Adjusting the cube: N and vertex sample index
  5009. var e0 = e < size_i - 1 ? Math.floor(e) : e - 1; // e1 = e0 + 1;
  5010. var n0 = e0 + 1 - e; // (e1 - e) / (e1 - e0);
  5011. var n1 = e - e0; // (e - e0) / (e1 - e0);
  5012. var offset0 = e0 * k;
  5013. var offset1 = offset0 + k; // e1 * k
  5014. for (j = 0; j < cubeVertices; j++) {
  5015. if (j & pos) {
  5016. cubeN[j] *= n1;
  5017. cubeVertex[j] += offset1;
  5018. } else {
  5019. cubeN[j] *= n0;
  5020. cubeVertex[j] += offset0;
  5021. }
  5022. }
  5023. k *= size_i;
  5024. pos <<= 1;
  5025. }
  5026. for (j = 0; j < n; ++j) {
  5027. // Sum all cube vertices' samples portions
  5028. var rj = 0;
  5029. for (i = 0; i < cubeVertices; i++) {
  5030. rj += samples[cubeVertex[i] + j] * cubeN[i];
  5031. }
  5032. // r_j' = Interpolate(r_j, 0, 2^BitsPerSample - 1,
  5033. // Decode_2j, Decode_2j+1)
  5034. rj = interpolate(rj, 0, 1, decode[j][0], decode[j][1]);
  5035. // y_j = min(max(r_j, range_2j), range_2j+1)
  5036. dest[destOffset + j] = Math.min(Math.max(rj, range[j][0]),
  5037. range[j][1]);
  5038. }
  5039. };
  5040. },
  5041. constructInterpolated: function PDFFunction_constructInterpolated(str,
  5042. dict) {
  5043. var c0 = dict.get('C0') || [0];
  5044. var c1 = dict.get('C1') || [1];
  5045. var n = dict.get('N');
  5046. if (!isArray(c0) || !isArray(c1)) {
  5047. error('Illegal dictionary for interpolated function');
  5048. }
  5049. var length = c0.length;
  5050. var diff = [];
  5051. for (var i = 0; i < length; ++i) {
  5052. diff.push(c1[i] - c0[i]);
  5053. }
  5054. return [CONSTRUCT_INTERPOLATED, c0, diff, n];
  5055. },
  5056. constructInterpolatedFromIR:
  5057. function PDFFunction_constructInterpolatedFromIR(IR) {
  5058. var c0 = IR[1];
  5059. var diff = IR[2];
  5060. var n = IR[3];
  5061. var length = diff.length;
  5062. return function constructInterpolatedFromIRResult(src, srcOffset,
  5063. dest, destOffset) {
  5064. var x = n === 1 ? src[srcOffset] : Math.pow(src[srcOffset], n);
  5065. for (var j = 0; j < length; ++j) {
  5066. dest[destOffset + j] = c0[j] + (x * diff[j]);
  5067. }
  5068. };
  5069. },
  5070. constructStiched: function PDFFunction_constructStiched(fn, dict, xref) {
  5071. var domain = dict.get('Domain');
  5072. if (!domain) {
  5073. error('No domain');
  5074. }
  5075. var inputSize = domain.length / 2;
  5076. if (inputSize !== 1) {
  5077. error('Bad domain for stiched function');
  5078. }
  5079. var fnRefs = dict.get('Functions');
  5080. var fns = [];
  5081. for (var i = 0, ii = fnRefs.length; i < ii; ++i) {
  5082. fns.push(PDFFunction.getIR(xref, xref.fetchIfRef(fnRefs[i])));
  5083. }
  5084. var bounds = dict.get('Bounds');
  5085. var encode = dict.get('Encode');
  5086. return [CONSTRUCT_STICHED, domain, bounds, encode, fns];
  5087. },
  5088. constructStichedFromIR: function PDFFunction_constructStichedFromIR(IR) {
  5089. var domain = IR[1];
  5090. var bounds = IR[2];
  5091. var encode = IR[3];
  5092. var fnsIR = IR[4];
  5093. var fns = [];
  5094. var tmpBuf = new Float32Array(1);
  5095. for (var i = 0, ii = fnsIR.length; i < ii; i++) {
  5096. fns.push(PDFFunction.fromIR(fnsIR[i]));
  5097. }
  5098. return function constructStichedFromIRResult(src, srcOffset,
  5099. dest, destOffset) {
  5100. var clip = function constructStichedFromIRClip(v, min, max) {
  5101. if (v > max) {
  5102. v = max;
  5103. } else if (v < min) {
  5104. v = min;
  5105. }
  5106. return v;
  5107. };
  5108. // clip to domain
  5109. var v = clip(src[srcOffset], domain[0], domain[1]);
  5110. // calulate which bound the value is in
  5111. for (var i = 0, ii = bounds.length; i < ii; ++i) {
  5112. if (v < bounds[i]) {
  5113. break;
  5114. }
  5115. }
  5116. // encode value into domain of function
  5117. var dmin = domain[0];
  5118. if (i > 0) {
  5119. dmin = bounds[i - 1];
  5120. }
  5121. var dmax = domain[1];
  5122. if (i < bounds.length) {
  5123. dmax = bounds[i];
  5124. }
  5125. var rmin = encode[2 * i];
  5126. var rmax = encode[2 * i + 1];
  5127. tmpBuf[0] = rmin + (v - dmin) * (rmax - rmin) / (dmax - dmin);
  5128. // call the appropriate function
  5129. fns[i](tmpBuf, 0, dest, destOffset);
  5130. };
  5131. },
  5132. constructPostScript: function PDFFunction_constructPostScript(fn, dict,
  5133. xref) {
  5134. var domain = dict.get('Domain');
  5135. var range = dict.get('Range');
  5136. if (!domain) {
  5137. error('No domain.');
  5138. }
  5139. if (!range) {
  5140. error('No range.');
  5141. }
  5142. var lexer = new PostScriptLexer(fn);
  5143. var parser = new PostScriptParser(lexer);
  5144. var code = parser.parse();
  5145. return [CONSTRUCT_POSTSCRIPT, domain, range, code];
  5146. },
  5147. constructPostScriptFromIR: function PDFFunction_constructPostScriptFromIR(
  5148. IR) {
  5149. var domain = IR[1];
  5150. var range = IR[2];
  5151. var code = IR[3];
  5152. var compiled = (new PostScriptCompiler()).compile(code, domain, range);
  5153. if (compiled) {
  5154. // Compiled function consists of simple expressions such as addition,
  5155. // subtraction, Math.max, and also contains 'var' and 'return'
  5156. // statements. See the generation in the PostScriptCompiler below.
  5157. /*jshint -W054 */
  5158. return new Function('src', 'srcOffset', 'dest', 'destOffset', compiled);
  5159. }
  5160. info('Unable to compile PS function');
  5161. var numOutputs = range.length >> 1;
  5162. var numInputs = domain.length >> 1;
  5163. var evaluator = new PostScriptEvaluator(code);
  5164. // Cache the values for a big speed up, the cache size is limited though
  5165. // since the number of possible values can be huge from a PS function.
  5166. var cache = {};
  5167. // The MAX_CACHE_SIZE is set to ~4x the maximum number of distinct values
  5168. // seen in our tests.
  5169. var MAX_CACHE_SIZE = 2048 * 4;
  5170. var cache_available = MAX_CACHE_SIZE;
  5171. var tmpBuf = new Float32Array(numInputs);
  5172. return function constructPostScriptFromIRResult(src, srcOffset,
  5173. dest, destOffset) {
  5174. var i, value;
  5175. var key = '';
  5176. var input = tmpBuf;
  5177. for (i = 0; i < numInputs; i++) {
  5178. value = src[srcOffset + i];
  5179. input[i] = value;
  5180. key += value + '_';
  5181. }
  5182. var cachedValue = cache[key];
  5183. if (cachedValue !== undefined) {
  5184. dest.set(cachedValue, destOffset);
  5185. return;
  5186. }
  5187. var output = new Float32Array(numOutputs);
  5188. var stack = evaluator.execute(input);
  5189. var stackIndex = stack.length - numOutputs;
  5190. for (i = 0; i < numOutputs; i++) {
  5191. value = stack[stackIndex + i];
  5192. var bound = range[i * 2];
  5193. if (value < bound) {
  5194. value = bound;
  5195. } else {
  5196. bound = range[i * 2 +1];
  5197. if (value > bound) {
  5198. value = bound;
  5199. }
  5200. }
  5201. output[i] = value;
  5202. }
  5203. if (cache_available > 0) {
  5204. cache_available--;
  5205. cache[key] = output;
  5206. }
  5207. dest.set(output, destOffset);
  5208. };
  5209. }
  5210. };
  5211. })();
  5212. function isPDFFunction(v) {
  5213. var fnDict;
  5214. if (typeof v !== 'object') {
  5215. return false;
  5216. } else if (isDict(v)) {
  5217. fnDict = v;
  5218. } else if (isStream(v)) {
  5219. fnDict = v.dict;
  5220. } else {
  5221. return false;
  5222. }
  5223. return fnDict.has('FunctionType');
  5224. }
  5225. var PostScriptStack = (function PostScriptStackClosure() {
  5226. var MAX_STACK_SIZE = 100;
  5227. function PostScriptStack(initialStack) {
  5228. this.stack = !initialStack ? [] :
  5229. Array.prototype.slice.call(initialStack, 0);
  5230. }
  5231. PostScriptStack.prototype = {
  5232. push: function PostScriptStack_push(value) {
  5233. if (this.stack.length >= MAX_STACK_SIZE) {
  5234. error('PostScript function stack overflow.');
  5235. }
  5236. this.stack.push(value);
  5237. },
  5238. pop: function PostScriptStack_pop() {
  5239. if (this.stack.length <= 0) {
  5240. error('PostScript function stack underflow.');
  5241. }
  5242. return this.stack.pop();
  5243. },
  5244. copy: function PostScriptStack_copy(n) {
  5245. if (this.stack.length + n >= MAX_STACK_SIZE) {
  5246. error('PostScript function stack overflow.');
  5247. }
  5248. var stack = this.stack;
  5249. for (var i = stack.length - n, j = n - 1; j >= 0; j--, i++) {
  5250. stack.push(stack[i]);
  5251. }
  5252. },
  5253. index: function PostScriptStack_index(n) {
  5254. this.push(this.stack[this.stack.length - n - 1]);
  5255. },
  5256. // rotate the last n stack elements p times
  5257. roll: function PostScriptStack_roll(n, p) {
  5258. var stack = this.stack;
  5259. var l = stack.length - n;
  5260. var r = stack.length - 1, c = l + (p - Math.floor(p / n) * n), i, j, t;
  5261. for (i = l, j = r; i < j; i++, j--) {
  5262. t = stack[i]; stack[i] = stack[j]; stack[j] = t;
  5263. }
  5264. for (i = l, j = c - 1; i < j; i++, j--) {
  5265. t = stack[i]; stack[i] = stack[j]; stack[j] = t;
  5266. }
  5267. for (i = c, j = r; i < j; i++, j--) {
  5268. t = stack[i]; stack[i] = stack[j]; stack[j] = t;
  5269. }
  5270. }
  5271. };
  5272. return PostScriptStack;
  5273. })();
  5274. var PostScriptEvaluator = (function PostScriptEvaluatorClosure() {
  5275. function PostScriptEvaluator(operators) {
  5276. this.operators = operators;
  5277. }
  5278. PostScriptEvaluator.prototype = {
  5279. execute: function PostScriptEvaluator_execute(initialStack) {
  5280. var stack = new PostScriptStack(initialStack);
  5281. var counter = 0;
  5282. var operators = this.operators;
  5283. var length = operators.length;
  5284. var operator, a, b;
  5285. while (counter < length) {
  5286. operator = operators[counter++];
  5287. if (typeof operator === 'number') {
  5288. // Operator is really an operand and should be pushed to the stack.
  5289. stack.push(operator);
  5290. continue;
  5291. }
  5292. switch (operator) {
  5293. // non standard ps operators
  5294. case 'jz': // jump if false
  5295. b = stack.pop();
  5296. a = stack.pop();
  5297. if (!a) {
  5298. counter = b;
  5299. }
  5300. break;
  5301. case 'j': // jump
  5302. a = stack.pop();
  5303. counter = a;
  5304. break;
  5305. // all ps operators in alphabetical order (excluding if/ifelse)
  5306. case 'abs':
  5307. a = stack.pop();
  5308. stack.push(Math.abs(a));
  5309. break;
  5310. case 'add':
  5311. b = stack.pop();
  5312. a = stack.pop();
  5313. stack.push(a + b);
  5314. break;
  5315. case 'and':
  5316. b = stack.pop();
  5317. a = stack.pop();
  5318. if (isBool(a) && isBool(b)) {
  5319. stack.push(a && b);
  5320. } else {
  5321. stack.push(a & b);
  5322. }
  5323. break;
  5324. case 'atan':
  5325. a = stack.pop();
  5326. stack.push(Math.atan(a));
  5327. break;
  5328. case 'bitshift':
  5329. b = stack.pop();
  5330. a = stack.pop();
  5331. if (a > 0) {
  5332. stack.push(a << b);
  5333. } else {
  5334. stack.push(a >> b);
  5335. }
  5336. break;
  5337. case 'ceiling':
  5338. a = stack.pop();
  5339. stack.push(Math.ceil(a));
  5340. break;
  5341. case 'copy':
  5342. a = stack.pop();
  5343. stack.copy(a);
  5344. break;
  5345. case 'cos':
  5346. a = stack.pop();
  5347. stack.push(Math.cos(a));
  5348. break;
  5349. case 'cvi':
  5350. a = stack.pop() | 0;
  5351. stack.push(a);
  5352. break;
  5353. case 'cvr':
  5354. // noop
  5355. break;
  5356. case 'div':
  5357. b = stack.pop();
  5358. a = stack.pop();
  5359. stack.push(a / b);
  5360. break;
  5361. case 'dup':
  5362. stack.copy(1);
  5363. break;
  5364. case 'eq':
  5365. b = stack.pop();
  5366. a = stack.pop();
  5367. stack.push(a === b);
  5368. break;
  5369. case 'exch':
  5370. stack.roll(2, 1);
  5371. break;
  5372. case 'exp':
  5373. b = stack.pop();
  5374. a = stack.pop();
  5375. stack.push(Math.pow(a, b));
  5376. break;
  5377. case 'false':
  5378. stack.push(false);
  5379. break;
  5380. case 'floor':
  5381. a = stack.pop();
  5382. stack.push(Math.floor(a));
  5383. break;
  5384. case 'ge':
  5385. b = stack.pop();
  5386. a = stack.pop();
  5387. stack.push(a >= b);
  5388. break;
  5389. case 'gt':
  5390. b = stack.pop();
  5391. a = stack.pop();
  5392. stack.push(a > b);
  5393. break;
  5394. case 'idiv':
  5395. b = stack.pop();
  5396. a = stack.pop();
  5397. stack.push((a / b) | 0);
  5398. break;
  5399. case 'index':
  5400. a = stack.pop();
  5401. stack.index(a);
  5402. break;
  5403. case 'le':
  5404. b = stack.pop();
  5405. a = stack.pop();
  5406. stack.push(a <= b);
  5407. break;
  5408. case 'ln':
  5409. a = stack.pop();
  5410. stack.push(Math.log(a));
  5411. break;
  5412. case 'log':
  5413. a = stack.pop();
  5414. stack.push(Math.log(a) / Math.LN10);
  5415. break;
  5416. case 'lt':
  5417. b = stack.pop();
  5418. a = stack.pop();
  5419. stack.push(a < b);
  5420. break;
  5421. case 'mod':
  5422. b = stack.pop();
  5423. a = stack.pop();
  5424. stack.push(a % b);
  5425. break;
  5426. case 'mul':
  5427. b = stack.pop();
  5428. a = stack.pop();
  5429. stack.push(a * b);
  5430. break;
  5431. case 'ne':
  5432. b = stack.pop();
  5433. a = stack.pop();
  5434. stack.push(a !== b);
  5435. break;
  5436. case 'neg':
  5437. a = stack.pop();
  5438. stack.push(-a);
  5439. break;
  5440. case 'not':
  5441. a = stack.pop();
  5442. if (isBool(a)) {
  5443. stack.push(!a);
  5444. } else {
  5445. stack.push(~a);
  5446. }
  5447. break;
  5448. case 'or':
  5449. b = stack.pop();
  5450. a = stack.pop();
  5451. if (isBool(a) && isBool(b)) {
  5452. stack.push(a || b);
  5453. } else {
  5454. stack.push(a | b);
  5455. }
  5456. break;
  5457. case 'pop':
  5458. stack.pop();
  5459. break;
  5460. case 'roll':
  5461. b = stack.pop();
  5462. a = stack.pop();
  5463. stack.roll(a, b);
  5464. break;
  5465. case 'round':
  5466. a = stack.pop();
  5467. stack.push(Math.round(a));
  5468. break;
  5469. case 'sin':
  5470. a = stack.pop();
  5471. stack.push(Math.sin(a));
  5472. break;
  5473. case 'sqrt':
  5474. a = stack.pop();
  5475. stack.push(Math.sqrt(a));
  5476. break;
  5477. case 'sub':
  5478. b = stack.pop();
  5479. a = stack.pop();
  5480. stack.push(a - b);
  5481. break;
  5482. case 'true':
  5483. stack.push(true);
  5484. break;
  5485. case 'truncate':
  5486. a = stack.pop();
  5487. a = a < 0 ? Math.ceil(a) : Math.floor(a);
  5488. stack.push(a);
  5489. break;
  5490. case 'xor':
  5491. b = stack.pop();
  5492. a = stack.pop();
  5493. if (isBool(a) && isBool(b)) {
  5494. stack.push(a !== b);
  5495. } else {
  5496. stack.push(a ^ b);
  5497. }
  5498. break;
  5499. default:
  5500. error('Unknown operator ' + operator);
  5501. break;
  5502. }
  5503. }
  5504. return stack.stack;
  5505. }
  5506. };
  5507. return PostScriptEvaluator;
  5508. })();
  5509. // Most of the PDFs functions consist of simple operations such as:
  5510. // roll, exch, sub, cvr, pop, index, dup, mul, if, gt, add.
  5511. //
  5512. // We can compile most of such programs, and at the same moment, we can
  5513. // optimize some expressions using basic math properties. Keeping track of
  5514. // min/max values will allow us to avoid extra Math.min/Math.max calls.
  5515. var PostScriptCompiler = (function PostScriptCompilerClosure() {
  5516. function AstNode(type) {
  5517. this.type = type;
  5518. }
  5519. AstNode.prototype.visit = function (visitor) {
  5520. throw new Error('abstract method');
  5521. };
  5522. function AstArgument(index, min, max) {
  5523. AstNode.call(this, 'args');
  5524. this.index = index;
  5525. this.min = min;
  5526. this.max = max;
  5527. }
  5528. AstArgument.prototype = Object.create(AstNode.prototype);
  5529. AstArgument.prototype.visit = function (visitor) {
  5530. visitor.visitArgument(this);
  5531. };
  5532. function AstLiteral(number) {
  5533. AstNode.call(this, 'literal');
  5534. this.number = number;
  5535. this.min = number;
  5536. this.max = number;
  5537. }
  5538. AstLiteral.prototype = Object.create(AstNode.prototype);
  5539. AstLiteral.prototype.visit = function (visitor) {
  5540. visitor.visitLiteral(this);
  5541. };
  5542. function AstBinaryOperation(op, arg1, arg2, min, max) {
  5543. AstNode.call(this, 'binary');
  5544. this.op = op;
  5545. this.arg1 = arg1;
  5546. this.arg2 = arg2;
  5547. this.min = min;
  5548. this.max = max;
  5549. }
  5550. AstBinaryOperation.prototype = Object.create(AstNode.prototype);
  5551. AstBinaryOperation.prototype.visit = function (visitor) {
  5552. visitor.visitBinaryOperation(this);
  5553. };
  5554. function AstMin(arg, max) {
  5555. AstNode.call(this, 'max');
  5556. this.arg = arg;
  5557. this.min = arg.min;
  5558. this.max = max;
  5559. }
  5560. AstMin.prototype = Object.create(AstNode.prototype);
  5561. AstMin.prototype.visit = function (visitor) {
  5562. visitor.visitMin(this);
  5563. };
  5564. function AstVariable(index, min, max) {
  5565. AstNode.call(this, 'var');
  5566. this.index = index;
  5567. this.min = min;
  5568. this.max = max;
  5569. }
  5570. AstVariable.prototype = Object.create(AstNode.prototype);
  5571. AstVariable.prototype.visit = function (visitor) {
  5572. visitor.visitVariable(this);
  5573. };
  5574. function AstVariableDefinition(variable, arg) {
  5575. AstNode.call(this, 'definition');
  5576. this.variable = variable;
  5577. this.arg = arg;
  5578. }
  5579. AstVariableDefinition.prototype = Object.create(AstNode.prototype);
  5580. AstVariableDefinition.prototype.visit = function (visitor) {
  5581. visitor.visitVariableDefinition(this);
  5582. };
  5583. function ExpressionBuilderVisitor() {
  5584. this.parts = [];
  5585. }
  5586. ExpressionBuilderVisitor.prototype = {
  5587. visitArgument: function (arg) {
  5588. this.parts.push('Math.max(', arg.min, ', Math.min(',
  5589. arg.max, ', src[srcOffset + ', arg.index, ']))');
  5590. },
  5591. visitVariable: function (variable) {
  5592. this.parts.push('v', variable.index);
  5593. },
  5594. visitLiteral: function (literal) {
  5595. this.parts.push(literal.number);
  5596. },
  5597. visitBinaryOperation: function (operation) {
  5598. this.parts.push('(');
  5599. operation.arg1.visit(this);
  5600. this.parts.push(' ', operation.op, ' ');
  5601. operation.arg2.visit(this);
  5602. this.parts.push(')');
  5603. },
  5604. visitVariableDefinition: function (definition) {
  5605. this.parts.push('var ');
  5606. definition.variable.visit(this);
  5607. this.parts.push(' = ');
  5608. definition.arg.visit(this);
  5609. this.parts.push(';');
  5610. },
  5611. visitMin: function (max) {
  5612. this.parts.push('Math.min(');
  5613. max.arg.visit(this);
  5614. this.parts.push(', ', max.max, ')');
  5615. },
  5616. toString: function () {
  5617. return this.parts.join('');
  5618. }
  5619. };
  5620. function buildAddOperation(num1, num2) {
  5621. if (num2.type === 'literal' && num2.number === 0) {
  5622. // optimization: second operand is 0
  5623. return num1;
  5624. }
  5625. if (num1.type === 'literal' && num1.number === 0) {
  5626. // optimization: first operand is 0
  5627. return num2;
  5628. }
  5629. if (num2.type === 'literal' && num1.type === 'literal') {
  5630. // optimization: operands operand are literals
  5631. return new AstLiteral(num1.number + num2.number);
  5632. }
  5633. return new AstBinaryOperation('+', num1, num2,
  5634. num1.min + num2.min, num1.max + num2.max);
  5635. }
  5636. function buildMulOperation(num1, num2) {
  5637. if (num2.type === 'literal') {
  5638. // optimization: second operands is a literal...
  5639. if (num2.number === 0) {
  5640. return new AstLiteral(0); // and it's 0
  5641. } else if (num2.number === 1) {
  5642. return num1; // and it's 1
  5643. } else if (num1.type === 'literal') {
  5644. // ... and first operands is a literal too
  5645. return new AstLiteral(num1.number * num2.number);
  5646. }
  5647. }
  5648. if (num1.type === 'literal') {
  5649. // optimization: first operands is a literal...
  5650. if (num1.number === 0) {
  5651. return new AstLiteral(0); // and it's 0
  5652. } else if (num1.number === 1) {
  5653. return num2; // and it's 1
  5654. }
  5655. }
  5656. var min = Math.min(num1.min * num2.min, num1.min * num2.max,
  5657. num1.max * num2.min, num1.max * num2.max);
  5658. var max = Math.max(num1.min * num2.min, num1.min * num2.max,
  5659. num1.max * num2.min, num1.max * num2.max);
  5660. return new AstBinaryOperation('*', num1, num2, min, max);
  5661. }
  5662. function buildSubOperation(num1, num2) {
  5663. if (num2.type === 'literal') {
  5664. // optimization: second operands is a literal...
  5665. if (num2.number === 0) {
  5666. return num1; // ... and it's 0
  5667. } else if (num1.type === 'literal') {
  5668. // ... and first operands is a literal too
  5669. return new AstLiteral(num1.number - num2.number);
  5670. }
  5671. }
  5672. if (num2.type === 'binary' && num2.op === '-' &&
  5673. num1.type === 'literal' && num1.number === 1 &&
  5674. num2.arg1.type === 'literal' && num2.arg1.number === 1) {
  5675. // optimization for case: 1 - (1 - x)
  5676. return num2.arg2;
  5677. }
  5678. return new AstBinaryOperation('-', num1, num2,
  5679. num1.min - num2.max, num1.max - num2.min);
  5680. }
  5681. function buildMinOperation(num1, max) {
  5682. if (num1.min >= max) {
  5683. // optimization: num1 min value is not less than required max
  5684. return new AstLiteral(max); // just returning max
  5685. } else if (num1.max <= max) {
  5686. // optimization: num1 max value is not greater than required max
  5687. return num1; // just returning an argument
  5688. }
  5689. return new AstMin(num1, max);
  5690. }
  5691. function PostScriptCompiler() {}
  5692. PostScriptCompiler.prototype = {
  5693. compile: function PostScriptCompiler_compile(code, domain, range) {
  5694. var stack = [];
  5695. var i, ii;
  5696. var instructions = [];
  5697. var inputSize = domain.length >> 1, outputSize = range.length >> 1;
  5698. var lastRegister = 0;
  5699. var n, j, min, max;
  5700. var num1, num2, ast1, ast2, tmpVar, item;
  5701. for (i = 0; i < inputSize; i++) {
  5702. stack.push(new AstArgument(i, domain[i * 2], domain[i * 2 + 1]));
  5703. }
  5704. for (i = 0, ii = code.length; i < ii; i++) {
  5705. item = code[i];
  5706. if (typeof item === 'number') {
  5707. stack.push(new AstLiteral(item));
  5708. continue;
  5709. }
  5710. switch (item) {
  5711. case 'add':
  5712. if (stack.length < 2) {
  5713. return null;
  5714. }
  5715. num2 = stack.pop();
  5716. num1 = stack.pop();
  5717. stack.push(buildAddOperation(num1, num2));
  5718. break;
  5719. case 'cvr':
  5720. if (stack.length < 1) {
  5721. return null;
  5722. }
  5723. break;
  5724. case 'mul':
  5725. if (stack.length < 2) {
  5726. return null;
  5727. }
  5728. num2 = stack.pop();
  5729. num1 = stack.pop();
  5730. stack.push(buildMulOperation(num1, num2));
  5731. break;
  5732. case 'sub':
  5733. if (stack.length < 2) {
  5734. return null;
  5735. }
  5736. num2 = stack.pop();
  5737. num1 = stack.pop();
  5738. stack.push(buildSubOperation(num1, num2));
  5739. break;
  5740. case 'exch':
  5741. if (stack.length < 2) {
  5742. return null;
  5743. }
  5744. ast1 = stack.pop(); ast2 = stack.pop();
  5745. stack.push(ast1, ast2);
  5746. break;
  5747. case 'pop':
  5748. if (stack.length < 1) {
  5749. return null;
  5750. }
  5751. stack.pop();
  5752. break;
  5753. case 'index':
  5754. if (stack.length < 1) {
  5755. return null;
  5756. }
  5757. num1 = stack.pop();
  5758. if (num1.type !== 'literal') {
  5759. return null;
  5760. }
  5761. n = num1.number;
  5762. if (n < 0 || (n|0) !== n || stack.length < n) {
  5763. return null;
  5764. }
  5765. ast1 = stack[stack.length - n - 1];
  5766. if (ast1.type === 'literal' || ast1.type === 'var') {
  5767. stack.push(ast1);
  5768. break;
  5769. }
  5770. tmpVar = new AstVariable(lastRegister++, ast1.min, ast1.max);
  5771. stack[stack.length - n - 1] = tmpVar;
  5772. stack.push(tmpVar);
  5773. instructions.push(new AstVariableDefinition(tmpVar, ast1));
  5774. break;
  5775. case 'dup':
  5776. if (stack.length < 1) {
  5777. return null;
  5778. }
  5779. if (typeof code[i + 1] === 'number' && code[i + 2] === 'gt' &&
  5780. code[i + 3] === i + 7 && code[i + 4] === 'jz' &&
  5781. code[i + 5] === 'pop' && code[i + 6] === code[i + 1]) {
  5782. // special case of the commands sequence for the min operation
  5783. num1 = stack.pop();
  5784. stack.push(buildMinOperation(num1, code[i + 1]));
  5785. i += 6;
  5786. break;
  5787. }
  5788. ast1 = stack[stack.length - 1];
  5789. if (ast1.type === 'literal' || ast1.type === 'var') {
  5790. // we don't have to save into intermediate variable a literal or
  5791. // variable.
  5792. stack.push(ast1);
  5793. break;
  5794. }
  5795. tmpVar = new AstVariable(lastRegister++, ast1.min, ast1.max);
  5796. stack[stack.length - 1] = tmpVar;
  5797. stack.push(tmpVar);
  5798. instructions.push(new AstVariableDefinition(tmpVar, ast1));
  5799. break;
  5800. case 'roll':
  5801. if (stack.length < 2) {
  5802. return null;
  5803. }
  5804. num2 = stack.pop();
  5805. num1 = stack.pop();
  5806. if (num2.type !== 'literal' || num1.type !== 'literal') {
  5807. // both roll operands must be numbers
  5808. return null;
  5809. }
  5810. j = num2.number;
  5811. n = num1.number;
  5812. if (n <= 0 || (n|0) !== n || (j|0) !== j || stack.length < n) {
  5813. // ... and integers
  5814. return null;
  5815. }
  5816. j = ((j % n) + n) % n;
  5817. if (j === 0) {
  5818. break; // just skipping -- there are nothing to rotate
  5819. }
  5820. Array.prototype.push.apply(stack,
  5821. stack.splice(stack.length - n, n - j));
  5822. break;
  5823. default:
  5824. return null; // unsupported operator
  5825. }
  5826. }
  5827. if (stack.length !== outputSize) {
  5828. return null;
  5829. }
  5830. var result = [];
  5831. instructions.forEach(function (instruction) {
  5832. var statementBuilder = new ExpressionBuilderVisitor();
  5833. instruction.visit(statementBuilder);
  5834. result.push(statementBuilder.toString());
  5835. });
  5836. stack.forEach(function (expr, i) {
  5837. var statementBuilder = new ExpressionBuilderVisitor();
  5838. expr.visit(statementBuilder);
  5839. var min = range[i * 2], max = range[i * 2 + 1];
  5840. var out = [statementBuilder.toString()];
  5841. if (min > expr.min) {
  5842. out.unshift('Math.max(', min, ', ');
  5843. out.push(')');
  5844. }
  5845. if (max < expr.max) {
  5846. out.unshift('Math.min(', max, ', ');
  5847. out.push(')');
  5848. }
  5849. out.unshift('dest[destOffset + ', i, '] = ');
  5850. out.push(';');
  5851. result.push(out.join(''));
  5852. });
  5853. return result.join('\n');
  5854. }
  5855. };
  5856. return PostScriptCompiler;
  5857. })();
  5858. var ColorSpace = (function ColorSpaceClosure() {
  5859. // Constructor should define this.numComps, this.defaultColor, this.name
  5860. function ColorSpace() {
  5861. error('should not call ColorSpace constructor');
  5862. }
  5863. ColorSpace.prototype = {
  5864. /**
  5865. * Converts the color value to the RGB color. The color components are
  5866. * located in the src array starting from the srcOffset. Returns the array
  5867. * of the rgb components, each value ranging from [0,255].
  5868. */
  5869. getRgb: function ColorSpace_getRgb(src, srcOffset) {
  5870. var rgb = new Uint8Array(3);
  5871. this.getRgbItem(src, srcOffset, rgb, 0);
  5872. return rgb;
  5873. },
  5874. /**
  5875. * Converts the color value to the RGB color, similar to the getRgb method.
  5876. * The result placed into the dest array starting from the destOffset.
  5877. */
  5878. getRgbItem: function ColorSpace_getRgbItem(src, srcOffset,
  5879. dest, destOffset) {
  5880. error('Should not call ColorSpace.getRgbItem');
  5881. },
  5882. /**
  5883. * Converts the specified number of the color values to the RGB colors.
  5884. * The colors are located in the src array starting from the srcOffset.
  5885. * The result is placed into the dest array starting from the destOffset.
  5886. * The src array items shall be in [0,2^bits) range, the dest array items
  5887. * will be in [0,255] range. alpha01 indicates how many alpha components
  5888. * there are in the dest array; it will be either 0 (RGB array) or 1 (RGBA
  5889. * array).
  5890. */
  5891. getRgbBuffer: function ColorSpace_getRgbBuffer(src, srcOffset, count,
  5892. dest, destOffset, bits,
  5893. alpha01) {
  5894. error('Should not call ColorSpace.getRgbBuffer');
  5895. },
  5896. /**
  5897. * Determines the number of bytes required to store the result of the
  5898. * conversion done by the getRgbBuffer method. As in getRgbBuffer,
  5899. * |alpha01| is either 0 (RGB output) or 1 (RGBA output).
  5900. */
  5901. getOutputLength: function ColorSpace_getOutputLength(inputLength,
  5902. alpha01) {
  5903. error('Should not call ColorSpace.getOutputLength');
  5904. },
  5905. /**
  5906. * Returns true if source data will be equal the result/output data.
  5907. */
  5908. isPassthrough: function ColorSpace_isPassthrough(bits) {
  5909. return false;
  5910. },
  5911. /**
  5912. * Fills in the RGB colors in the destination buffer. alpha01 indicates
  5913. * how many alpha components there are in the dest array; it will be either
  5914. * 0 (RGB array) or 1 (RGBA array).
  5915. */
  5916. fillRgb: function ColorSpace_fillRgb(dest, originalWidth,
  5917. originalHeight, width, height,
  5918. actualHeight, bpc, comps, alpha01) {
  5919. var count = originalWidth * originalHeight;
  5920. var rgbBuf = null;
  5921. var numComponentColors = 1 << bpc;
  5922. var needsResizing = originalHeight !== height || originalWidth !== width;
  5923. var i, ii;
  5924. if (this.isPassthrough(bpc)) {
  5925. rgbBuf = comps;
  5926. } else if (this.numComps === 1 && count > numComponentColors &&
  5927. this.name !== 'DeviceGray' && this.name !== 'DeviceRGB') {
  5928. // Optimization: create a color map when there is just one component and
  5929. // we are converting more colors than the size of the color map. We
  5930. // don't build the map if the colorspace is gray or rgb since those
  5931. // methods are faster than building a map. This mainly offers big speed
  5932. // ups for indexed and alternate colorspaces.
  5933. //
  5934. // TODO it may be worth while to cache the color map. While running
  5935. // testing I never hit a cache so I will leave that out for now (perhaps
  5936. // we are reparsing colorspaces too much?).
  5937. var allColors = bpc <= 8 ? new Uint8Array(numComponentColors) :
  5938. new Uint16Array(numComponentColors);
  5939. var key;
  5940. for (i = 0; i < numComponentColors; i++) {
  5941. allColors[i] = i;
  5942. }
  5943. var colorMap = new Uint8Array(numComponentColors * 3);
  5944. this.getRgbBuffer(allColors, 0, numComponentColors, colorMap, 0, bpc,
  5945. /* alpha01 = */ 0);
  5946. var destPos, rgbPos;
  5947. if (!needsResizing) {
  5948. // Fill in the RGB values directly into |dest|.
  5949. destPos = 0;
  5950. for (i = 0; i < count; ++i) {
  5951. key = comps[i] * 3;
  5952. dest[destPos++] = colorMap[key];
  5953. dest[destPos++] = colorMap[key + 1];
  5954. dest[destPos++] = colorMap[key + 2];
  5955. destPos += alpha01;
  5956. }
  5957. } else {
  5958. rgbBuf = new Uint8Array(count * 3);
  5959. rgbPos = 0;
  5960. for (i = 0; i < count; ++i) {
  5961. key = comps[i] * 3;
  5962. rgbBuf[rgbPos++] = colorMap[key];
  5963. rgbBuf[rgbPos++] = colorMap[key + 1];
  5964. rgbBuf[rgbPos++] = colorMap[key + 2];
  5965. }
  5966. }
  5967. } else {
  5968. if (!needsResizing) {
  5969. // Fill in the RGB values directly into |dest|.
  5970. this.getRgbBuffer(comps, 0, width * actualHeight, dest, 0, bpc,
  5971. alpha01);
  5972. } else {
  5973. rgbBuf = new Uint8Array(count * 3);
  5974. this.getRgbBuffer(comps, 0, count, rgbBuf, 0, bpc,
  5975. /* alpha01 = */ 0);
  5976. }
  5977. }
  5978. if (rgbBuf) {
  5979. if (needsResizing) {
  5980. PDFImage.resize(rgbBuf, bpc, 3, originalWidth, originalHeight, width,
  5981. height, dest, alpha01);
  5982. } else {
  5983. rgbPos = 0;
  5984. destPos = 0;
  5985. for (i = 0, ii = width * actualHeight; i < ii; i++) {
  5986. dest[destPos++] = rgbBuf[rgbPos++];
  5987. dest[destPos++] = rgbBuf[rgbPos++];
  5988. dest[destPos++] = rgbBuf[rgbPos++];
  5989. destPos += alpha01;
  5990. }
  5991. }
  5992. }
  5993. },
  5994. /**
  5995. * True if the colorspace has components in the default range of [0, 1].
  5996. * This should be true for all colorspaces except for lab color spaces
  5997. * which are [0,100], [-128, 127], [-128, 127].
  5998. */
  5999. usesZeroToOneRange: true
  6000. };
  6001. ColorSpace.parse = function ColorSpace_parse(cs, xref, res) {
  6002. var IR = ColorSpace.parseToIR(cs, xref, res);
  6003. if (IR instanceof AlternateCS) {
  6004. return IR;
  6005. }
  6006. return ColorSpace.fromIR(IR);
  6007. };
  6008. ColorSpace.fromIR = function ColorSpace_fromIR(IR) {
  6009. var name = isArray(IR) ? IR[0] : IR;
  6010. var whitePoint, blackPoint, gamma;
  6011. switch (name) {
  6012. case 'DeviceGrayCS':
  6013. return this.singletons.gray;
  6014. case 'DeviceRgbCS':
  6015. return this.singletons.rgb;
  6016. case 'DeviceCmykCS':
  6017. return this.singletons.cmyk;
  6018. case 'CalGrayCS':
  6019. whitePoint = IR[1].WhitePoint;
  6020. blackPoint = IR[1].BlackPoint;
  6021. gamma = IR[1].Gamma;
  6022. return new CalGrayCS(whitePoint, blackPoint, gamma);
  6023. case 'CalRGBCS':
  6024. whitePoint = IR[1].WhitePoint;
  6025. blackPoint = IR[1].BlackPoint;
  6026. gamma = IR[1].Gamma;
  6027. var matrix = IR[1].Matrix;
  6028. return new CalRGBCS(whitePoint, blackPoint, gamma, matrix);
  6029. case 'PatternCS':
  6030. var basePatternCS = IR[1];
  6031. if (basePatternCS) {
  6032. basePatternCS = ColorSpace.fromIR(basePatternCS);
  6033. }
  6034. return new PatternCS(basePatternCS);
  6035. case 'IndexedCS':
  6036. var baseIndexedCS = IR[1];
  6037. var hiVal = IR[2];
  6038. var lookup = IR[3];
  6039. return new IndexedCS(ColorSpace.fromIR(baseIndexedCS), hiVal, lookup);
  6040. case 'AlternateCS':
  6041. var numComps = IR[1];
  6042. var alt = IR[2];
  6043. var tintFnIR = IR[3];
  6044. return new AlternateCS(numComps, ColorSpace.fromIR(alt),
  6045. PDFFunction.fromIR(tintFnIR));
  6046. case 'LabCS':
  6047. whitePoint = IR[1].WhitePoint;
  6048. blackPoint = IR[1].BlackPoint;
  6049. var range = IR[1].Range;
  6050. return new LabCS(whitePoint, blackPoint, range);
  6051. default:
  6052. error('Unknown name ' + name);
  6053. }
  6054. return null;
  6055. };
  6056. ColorSpace.parseToIR = function ColorSpace_parseToIR(cs, xref, res) {
  6057. if (isName(cs)) {
  6058. var colorSpaces = res.get('ColorSpace');
  6059. if (isDict(colorSpaces)) {
  6060. var refcs = colorSpaces.get(cs.name);
  6061. if (refcs) {
  6062. cs = refcs;
  6063. }
  6064. }
  6065. }
  6066. cs = xref.fetchIfRef(cs);
  6067. var mode;
  6068. if (isName(cs)) {
  6069. mode = cs.name;
  6070. this.mode = mode;
  6071. switch (mode) {
  6072. case 'DeviceGray':
  6073. case 'G':
  6074. return 'DeviceGrayCS';
  6075. case 'DeviceRGB':
  6076. case 'RGB':
  6077. return 'DeviceRgbCS';
  6078. case 'DeviceCMYK':
  6079. case 'CMYK':
  6080. return 'DeviceCmykCS';
  6081. case 'Pattern':
  6082. return ['PatternCS', null];
  6083. default:
  6084. error('unrecognized colorspace ' + mode);
  6085. }
  6086. } else if (isArray(cs)) {
  6087. mode = cs[0].name;
  6088. this.mode = mode;
  6089. var numComps, params;
  6090. switch (mode) {
  6091. case 'DeviceGray':
  6092. case 'G':
  6093. return 'DeviceGrayCS';
  6094. case 'DeviceRGB':
  6095. case 'RGB':
  6096. return 'DeviceRgbCS';
  6097. case 'DeviceCMYK':
  6098. case 'CMYK':
  6099. return 'DeviceCmykCS';
  6100. case 'CalGray':
  6101. params = xref.fetchIfRef(cs[1]).getAll();
  6102. return ['CalGrayCS', params];
  6103. case 'CalRGB':
  6104. params = xref.fetchIfRef(cs[1]).getAll();
  6105. return ['CalRGBCS', params];
  6106. case 'ICCBased':
  6107. var stream = xref.fetchIfRef(cs[1]);
  6108. var dict = stream.dict;
  6109. numComps = dict.get('N');
  6110. if (numComps === 1) {
  6111. return 'DeviceGrayCS';
  6112. } else if (numComps === 3) {
  6113. return 'DeviceRgbCS';
  6114. } else if (numComps === 4) {
  6115. return 'DeviceCmykCS';
  6116. }
  6117. break;
  6118. case 'Pattern':
  6119. var basePatternCS = cs[1];
  6120. if (basePatternCS) {
  6121. basePatternCS = ColorSpace.parseToIR(basePatternCS, xref, res);
  6122. }
  6123. return ['PatternCS', basePatternCS];
  6124. case 'Indexed':
  6125. case 'I':
  6126. var baseIndexedCS = ColorSpace.parseToIR(cs[1], xref, res);
  6127. var hiVal = cs[2] + 1;
  6128. var lookup = xref.fetchIfRef(cs[3]);
  6129. if (isStream(lookup)) {
  6130. lookup = lookup.getBytes();
  6131. }
  6132. return ['IndexedCS', baseIndexedCS, hiVal, lookup];
  6133. case 'Separation':
  6134. case 'DeviceN':
  6135. var name = cs[1];
  6136. numComps = 1;
  6137. if (isName(name)) {
  6138. numComps = 1;
  6139. } else if (isArray(name)) {
  6140. numComps = name.length;
  6141. }
  6142. var alt = ColorSpace.parseToIR(cs[2], xref, res);
  6143. var tintFnIR = PDFFunction.getIR(xref, xref.fetchIfRef(cs[3]));
  6144. return ['AlternateCS', numComps, alt, tintFnIR];
  6145. case 'Lab':
  6146. params = cs[1].getAll();
  6147. return ['LabCS', params];
  6148. default:
  6149. error('unimplemented color space object "' + mode + '"');
  6150. }
  6151. } else {
  6152. error('unrecognized color space object: "' + cs + '"');
  6153. }
  6154. return null;
  6155. };
  6156. /**
  6157. * Checks if a decode map matches the default decode map for a color space.
  6158. * This handles the general decode maps where there are two values per
  6159. * component. e.g. [0, 1, 0, 1, 0, 1] for a RGB color.
  6160. * This does not handle Lab, Indexed, or Pattern decode maps since they are
  6161. * slightly different.
  6162. * @param {Array} decode Decode map (usually from an image).
  6163. * @param {Number} n Number of components the color space has.
  6164. */
  6165. ColorSpace.isDefaultDecode = function ColorSpace_isDefaultDecode(decode, n) {
  6166. if (!decode) {
  6167. return true;
  6168. }
  6169. if (n * 2 !== decode.length) {
  6170. warn('The decode map is not the correct length');
  6171. return true;
  6172. }
  6173. for (var i = 0, ii = decode.length; i < ii; i += 2) {
  6174. if (decode[i] !== 0 || decode[i + 1] !== 1) {
  6175. return false;
  6176. }
  6177. }
  6178. return true;
  6179. };
  6180. ColorSpace.singletons = {
  6181. get gray() {
  6182. return shadow(this, 'gray', new DeviceGrayCS());
  6183. },
  6184. get rgb() {
  6185. return shadow(this, 'rgb', new DeviceRgbCS());
  6186. },
  6187. get cmyk() {
  6188. return shadow(this, 'cmyk', new DeviceCmykCS());
  6189. }
  6190. };
  6191. return ColorSpace;
  6192. })();
  6193. /**
  6194. * Alternate color space handles both Separation and DeviceN color spaces. A
  6195. * Separation color space is actually just a DeviceN with one color component.
  6196. * Both color spaces use a tinting function to convert colors to a base color
  6197. * space.
  6198. */
  6199. var AlternateCS = (function AlternateCSClosure() {
  6200. function AlternateCS(numComps, base, tintFn) {
  6201. this.name = 'Alternate';
  6202. this.numComps = numComps;
  6203. this.defaultColor = new Float32Array(numComps);
  6204. for (var i = 0; i < numComps; ++i) {
  6205. this.defaultColor[i] = 1;
  6206. }
  6207. this.base = base;
  6208. this.tintFn = tintFn;
  6209. this.tmpBuf = new Float32Array(base.numComps);
  6210. }
  6211. AlternateCS.prototype = {
  6212. getRgb: ColorSpace.prototype.getRgb,
  6213. getRgbItem: function AlternateCS_getRgbItem(src, srcOffset,
  6214. dest, destOffset) {
  6215. var tmpBuf = this.tmpBuf;
  6216. this.tintFn(src, srcOffset, tmpBuf, 0);
  6217. this.base.getRgbItem(tmpBuf, 0, dest, destOffset);
  6218. },
  6219. getRgbBuffer: function AlternateCS_getRgbBuffer(src, srcOffset, count,
  6220. dest, destOffset, bits,
  6221. alpha01) {
  6222. var tintFn = this.tintFn;
  6223. var base = this.base;
  6224. var scale = 1 / ((1 << bits) - 1);
  6225. var baseNumComps = base.numComps;
  6226. var usesZeroToOneRange = base.usesZeroToOneRange;
  6227. var isPassthrough = (base.isPassthrough(8) || !usesZeroToOneRange) &&
  6228. alpha01 === 0;
  6229. var pos = isPassthrough ? destOffset : 0;
  6230. var baseBuf = isPassthrough ? dest : new Uint8Array(baseNumComps * count);
  6231. var numComps = this.numComps;
  6232. var scaled = new Float32Array(numComps);
  6233. var tinted = new Float32Array(baseNumComps);
  6234. var i, j;
  6235. if (usesZeroToOneRange) {
  6236. for (i = 0; i < count; i++) {
  6237. for (j = 0; j < numComps; j++) {
  6238. scaled[j] = src[srcOffset++] * scale;
  6239. }
  6240. tintFn(scaled, 0, tinted, 0);
  6241. for (j = 0; j < baseNumComps; j++) {
  6242. baseBuf[pos++] = tinted[j] * 255;
  6243. }
  6244. }
  6245. } else {
  6246. for (i = 0; i < count; i++) {
  6247. for (j = 0; j < numComps; j++) {
  6248. scaled[j] = src[srcOffset++] * scale;
  6249. }
  6250. tintFn(scaled, 0, tinted, 0);
  6251. base.getRgbItem(tinted, 0, baseBuf, pos);
  6252. pos += baseNumComps;
  6253. }
  6254. }
  6255. if (!isPassthrough) {
  6256. base.getRgbBuffer(baseBuf, 0, count, dest, destOffset, 8, alpha01);
  6257. }
  6258. },
  6259. getOutputLength: function AlternateCS_getOutputLength(inputLength,
  6260. alpha01) {
  6261. return this.base.getOutputLength(inputLength *
  6262. this.base.numComps / this.numComps,
  6263. alpha01);
  6264. },
  6265. isPassthrough: ColorSpace.prototype.isPassthrough,
  6266. fillRgb: ColorSpace.prototype.fillRgb,
  6267. isDefaultDecode: function AlternateCS_isDefaultDecode(decodeMap) {
  6268. return ColorSpace.isDefaultDecode(decodeMap, this.numComps);
  6269. },
  6270. usesZeroToOneRange: true
  6271. };
  6272. return AlternateCS;
  6273. })();
  6274. var PatternCS = (function PatternCSClosure() {
  6275. function PatternCS(baseCS) {
  6276. this.name = 'Pattern';
  6277. this.base = baseCS;
  6278. }
  6279. PatternCS.prototype = {};
  6280. return PatternCS;
  6281. })();
  6282. var IndexedCS = (function IndexedCSClosure() {
  6283. function IndexedCS(base, highVal, lookup) {
  6284. this.name = 'Indexed';
  6285. this.numComps = 1;
  6286. this.defaultColor = new Uint8Array([0]);
  6287. this.base = base;
  6288. this.highVal = highVal;
  6289. var baseNumComps = base.numComps;
  6290. var length = baseNumComps * highVal;
  6291. var lookupArray;
  6292. if (isStream(lookup)) {
  6293. lookupArray = new Uint8Array(length);
  6294. var bytes = lookup.getBytes(length);
  6295. lookupArray.set(bytes);
  6296. } else if (isString(lookup)) {
  6297. lookupArray = new Uint8Array(length);
  6298. for (var i = 0; i < length; ++i) {
  6299. lookupArray[i] = lookup.charCodeAt(i);
  6300. }
  6301. } else if (lookup instanceof Uint8Array || lookup instanceof Array) {
  6302. lookupArray = lookup;
  6303. } else {
  6304. error('Unrecognized lookup table: ' + lookup);
  6305. }
  6306. this.lookup = lookupArray;
  6307. }
  6308. IndexedCS.prototype = {
  6309. getRgb: ColorSpace.prototype.getRgb,
  6310. getRgbItem: function IndexedCS_getRgbItem(src, srcOffset,
  6311. dest, destOffset) {
  6312. var numComps = this.base.numComps;
  6313. var start = src[srcOffset] * numComps;
  6314. this.base.getRgbItem(this.lookup, start, dest, destOffset);
  6315. },
  6316. getRgbBuffer: function IndexedCS_getRgbBuffer(src, srcOffset, count,
  6317. dest, destOffset, bits,
  6318. alpha01) {
  6319. var base = this.base;
  6320. var numComps = base.numComps;
  6321. var outputDelta = base.getOutputLength(numComps, alpha01);
  6322. var lookup = this.lookup;
  6323. for (var i = 0; i < count; ++i) {
  6324. var lookupPos = src[srcOffset++] * numComps;
  6325. base.getRgbBuffer(lookup, lookupPos, 1, dest, destOffset, 8, alpha01);
  6326. destOffset += outputDelta;
  6327. }
  6328. },
  6329. getOutputLength: function IndexedCS_getOutputLength(inputLength, alpha01) {
  6330. return this.base.getOutputLength(inputLength * this.base.numComps,
  6331. alpha01);
  6332. },
  6333. isPassthrough: ColorSpace.prototype.isPassthrough,
  6334. fillRgb: ColorSpace.prototype.fillRgb,
  6335. isDefaultDecode: function IndexedCS_isDefaultDecode(decodeMap) {
  6336. // indexed color maps shouldn't be changed
  6337. return true;
  6338. },
  6339. usesZeroToOneRange: true
  6340. };
  6341. return IndexedCS;
  6342. })();
  6343. var DeviceGrayCS = (function DeviceGrayCSClosure() {
  6344. function DeviceGrayCS() {
  6345. this.name = 'DeviceGray';
  6346. this.numComps = 1;
  6347. this.defaultColor = new Float32Array([0]);
  6348. }
  6349. DeviceGrayCS.prototype = {
  6350. getRgb: ColorSpace.prototype.getRgb,
  6351. getRgbItem: function DeviceGrayCS_getRgbItem(src, srcOffset,
  6352. dest, destOffset) {
  6353. var c = (src[srcOffset] * 255) | 0;
  6354. c = c < 0 ? 0 : c > 255 ? 255 : c;
  6355. dest[destOffset] = dest[destOffset + 1] = dest[destOffset + 2] = c;
  6356. },
  6357. getRgbBuffer: function DeviceGrayCS_getRgbBuffer(src, srcOffset, count,
  6358. dest, destOffset, bits,
  6359. alpha01) {
  6360. var scale = 255 / ((1 << bits) - 1);
  6361. var j = srcOffset, q = destOffset;
  6362. for (var i = 0; i < count; ++i) {
  6363. var c = (scale * src[j++]) | 0;
  6364. dest[q++] = c;
  6365. dest[q++] = c;
  6366. dest[q++] = c;
  6367. q += alpha01;
  6368. }
  6369. },
  6370. getOutputLength: function DeviceGrayCS_getOutputLength(inputLength,
  6371. alpha01) {
  6372. return inputLength * (3 + alpha01);
  6373. },
  6374. isPassthrough: ColorSpace.prototype.isPassthrough,
  6375. fillRgb: ColorSpace.prototype.fillRgb,
  6376. isDefaultDecode: function DeviceGrayCS_isDefaultDecode(decodeMap) {
  6377. return ColorSpace.isDefaultDecode(decodeMap, this.numComps);
  6378. },
  6379. usesZeroToOneRange: true
  6380. };
  6381. return DeviceGrayCS;
  6382. })();
  6383. var DeviceRgbCS = (function DeviceRgbCSClosure() {
  6384. function DeviceRgbCS() {
  6385. this.name = 'DeviceRGB';
  6386. this.numComps = 3;
  6387. this.defaultColor = new Float32Array([0, 0, 0]);
  6388. }
  6389. DeviceRgbCS.prototype = {
  6390. getRgb: ColorSpace.prototype.getRgb,
  6391. getRgbItem: function DeviceRgbCS_getRgbItem(src, srcOffset,
  6392. dest, destOffset) {
  6393. var r = (src[srcOffset] * 255) | 0;
  6394. var g = (src[srcOffset + 1] * 255) | 0;
  6395. var b = (src[srcOffset + 2] * 255) | 0;
  6396. dest[destOffset] = r < 0 ? 0 : r > 255 ? 255 : r;
  6397. dest[destOffset + 1] = g < 0 ? 0 : g > 255 ? 255 : g;
  6398. dest[destOffset + 2] = b < 0 ? 0 : b > 255 ? 255 : b;
  6399. },
  6400. getRgbBuffer: function DeviceRgbCS_getRgbBuffer(src, srcOffset, count,
  6401. dest, destOffset, bits,
  6402. alpha01) {
  6403. if (bits === 8 && alpha01 === 0) {
  6404. dest.set(src.subarray(srcOffset, srcOffset + count * 3), destOffset);
  6405. return;
  6406. }
  6407. var scale = 255 / ((1 << bits) - 1);
  6408. var j = srcOffset, q = destOffset;
  6409. for (var i = 0; i < count; ++i) {
  6410. dest[q++] = (scale * src[j++]) | 0;
  6411. dest[q++] = (scale * src[j++]) | 0;
  6412. dest[q++] = (scale * src[j++]) | 0;
  6413. q += alpha01;
  6414. }
  6415. },
  6416. getOutputLength: function DeviceRgbCS_getOutputLength(inputLength,
  6417. alpha01) {
  6418. return (inputLength * (3 + alpha01) / 3) | 0;
  6419. },
  6420. isPassthrough: function DeviceRgbCS_isPassthrough(bits) {
  6421. return bits === 8;
  6422. },
  6423. fillRgb: ColorSpace.prototype.fillRgb,
  6424. isDefaultDecode: function DeviceRgbCS_isDefaultDecode(decodeMap) {
  6425. return ColorSpace.isDefaultDecode(decodeMap, this.numComps);
  6426. },
  6427. usesZeroToOneRange: true
  6428. };
  6429. return DeviceRgbCS;
  6430. })();
  6431. var DeviceCmykCS = (function DeviceCmykCSClosure() {
  6432. // The coefficients below was found using numerical analysis: the method of
  6433. // steepest descent for the sum((f_i - color_value_i)^2) for r/g/b colors,
  6434. // where color_value is the tabular value from the table of sampled RGB colors
  6435. // from CMYK US Web Coated (SWOP) colorspace, and f_i is the corresponding
  6436. // CMYK color conversion using the estimation below:
  6437. // f(A, B,.. N) = Acc+Bcm+Ccy+Dck+c+Fmm+Gmy+Hmk+Im+Jyy+Kyk+Ly+Mkk+Nk+255
  6438. function convertToRgb(src, srcOffset, srcScale, dest, destOffset) {
  6439. var c = src[srcOffset + 0] * srcScale;
  6440. var m = src[srcOffset + 1] * srcScale;
  6441. var y = src[srcOffset + 2] * srcScale;
  6442. var k = src[srcOffset + 3] * srcScale;
  6443. var r =
  6444. (c * (-4.387332384609988 * c + 54.48615194189176 * m +
  6445. 18.82290502165302 * y + 212.25662451639585 * k +
  6446. -285.2331026137004) +
  6447. m * (1.7149763477362134 * m - 5.6096736904047315 * y +
  6448. -17.873870861415444 * k - 5.497006427196366) +
  6449. y * (-2.5217340131683033 * y - 21.248923337353073 * k +
  6450. 17.5119270841813) +
  6451. k * (-21.86122147463605 * k - 189.48180835922747) + 255) | 0;
  6452. var g =
  6453. (c * (8.841041422036149 * c + 60.118027045597366 * m +
  6454. 6.871425592049007 * y + 31.159100130055922 * k +
  6455. -79.2970844816548) +
  6456. m * (-15.310361306967817 * m + 17.575251261109482 * y +
  6457. 131.35250912493976 * k - 190.9453302588951) +
  6458. y * (4.444339102852739 * y + 9.8632861493405 * k - 24.86741582555878) +
  6459. k * (-20.737325471181034 * k - 187.80453709719578) + 255) | 0;
  6460. var b =
  6461. (c * (0.8842522430003296 * c + 8.078677503112928 * m +
  6462. 30.89978309703729 * y - 0.23883238689178934 * k +
  6463. -14.183576799673286) +
  6464. m * (10.49593273432072 * m + 63.02378494754052 * y +
  6465. 50.606957656360734 * k - 112.23884253719248) +
  6466. y * (0.03296041114873217 * y + 115.60384449646641 * k +
  6467. -193.58209356861505) +
  6468. k * (-22.33816807309886 * k - 180.12613974708367) + 255) | 0;
  6469. dest[destOffset] = r > 255 ? 255 : r < 0 ? 0 : r;
  6470. dest[destOffset + 1] = g > 255 ? 255 : g < 0 ? 0 : g;
  6471. dest[destOffset + 2] = b > 255 ? 255 : b < 0 ? 0 : b;
  6472. }
  6473. function DeviceCmykCS() {
  6474. this.name = 'DeviceCMYK';
  6475. this.numComps = 4;
  6476. this.defaultColor = new Float32Array([0, 0, 0, 1]);
  6477. }
  6478. DeviceCmykCS.prototype = {
  6479. getRgb: ColorSpace.prototype.getRgb,
  6480. getRgbItem: function DeviceCmykCS_getRgbItem(src, srcOffset,
  6481. dest, destOffset) {
  6482. convertToRgb(src, srcOffset, 1, dest, destOffset);
  6483. },
  6484. getRgbBuffer: function DeviceCmykCS_getRgbBuffer(src, srcOffset, count,
  6485. dest, destOffset, bits,
  6486. alpha01) {
  6487. var scale = 1 / ((1 << bits) - 1);
  6488. for (var i = 0; i < count; i++) {
  6489. convertToRgb(src, srcOffset, scale, dest, destOffset);
  6490. srcOffset += 4;
  6491. destOffset += 3 + alpha01;
  6492. }
  6493. },
  6494. getOutputLength: function DeviceCmykCS_getOutputLength(inputLength,
  6495. alpha01) {
  6496. return (inputLength / 4 * (3 + alpha01)) | 0;
  6497. },
  6498. isPassthrough: ColorSpace.prototype.isPassthrough,
  6499. fillRgb: ColorSpace.prototype.fillRgb,
  6500. isDefaultDecode: function DeviceCmykCS_isDefaultDecode(decodeMap) {
  6501. return ColorSpace.isDefaultDecode(decodeMap, this.numComps);
  6502. },
  6503. usesZeroToOneRange: true
  6504. };
  6505. return DeviceCmykCS;
  6506. })();
  6507. //
  6508. // CalGrayCS: Based on "PDF Reference, Sixth Ed", p.245
  6509. //
  6510. var CalGrayCS = (function CalGrayCSClosure() {
  6511. function CalGrayCS(whitePoint, blackPoint, gamma) {
  6512. this.name = 'CalGray';
  6513. this.numComps = 1;
  6514. this.defaultColor = new Float32Array([0]);
  6515. if (!whitePoint) {
  6516. error('WhitePoint missing - required for color space CalGray');
  6517. }
  6518. blackPoint = blackPoint || [0, 0, 0];
  6519. gamma = gamma || 1;
  6520. // Translate arguments to spec variables.
  6521. this.XW = whitePoint[0];
  6522. this.YW = whitePoint[1];
  6523. this.ZW = whitePoint[2];
  6524. this.XB = blackPoint[0];
  6525. this.YB = blackPoint[1];
  6526. this.ZB = blackPoint[2];
  6527. this.G = gamma;
  6528. // Validate variables as per spec.
  6529. if (this.XW < 0 || this.ZW < 0 || this.YW !== 1) {
  6530. error('Invalid WhitePoint components for ' + this.name +
  6531. ', no fallback available');
  6532. }
  6533. if (this.XB < 0 || this.YB < 0 || this.ZB < 0) {
  6534. info('Invalid BlackPoint for ' + this.name + ', falling back to default');
  6535. this.XB = this.YB = this.ZB = 0;
  6536. }
  6537. if (this.XB !== 0 || this.YB !== 0 || this.ZB !== 0) {
  6538. warn(this.name + ', BlackPoint: XB: ' + this.XB + ', YB: ' + this.YB +
  6539. ', ZB: ' + this.ZB + ', only default values are supported.');
  6540. }
  6541. if (this.G < 1) {
  6542. info('Invalid Gamma: ' + this.G + ' for ' + this.name +
  6543. ', falling back to default');
  6544. this.G = 1;
  6545. }
  6546. }
  6547. function convertToRgb(cs, src, srcOffset, dest, destOffset, scale) {
  6548. // A represents a gray component of a calibrated gray space.
  6549. // A <---> AG in the spec
  6550. var A = src[srcOffset] * scale;
  6551. var AG = Math.pow(A, cs.G);
  6552. // Computes L as per spec. ( = cs.YW * AG )
  6553. // Except if other than default BlackPoint values are used.
  6554. var L = cs.YW * AG;
  6555. // http://www.poynton.com/notes/colour_and_gamma/ColorFAQ.html, Ch 4.
  6556. // Convert values to rgb range [0, 255].
  6557. var val = Math.max(295.8 * Math.pow(L, 0.333333333333333333) - 40.8, 0) | 0;
  6558. dest[destOffset] = val;
  6559. dest[destOffset + 1] = val;
  6560. dest[destOffset + 2] = val;
  6561. }
  6562. CalGrayCS.prototype = {
  6563. getRgb: ColorSpace.prototype.getRgb,
  6564. getRgbItem: function CalGrayCS_getRgbItem(src, srcOffset,
  6565. dest, destOffset) {
  6566. convertToRgb(this, src, srcOffset, dest, destOffset, 1);
  6567. },
  6568. getRgbBuffer: function CalGrayCS_getRgbBuffer(src, srcOffset, count,
  6569. dest, destOffset, bits,
  6570. alpha01) {
  6571. var scale = 1 / ((1 << bits) - 1);
  6572. for (var i = 0; i < count; ++i) {
  6573. convertToRgb(this, src, srcOffset, dest, destOffset, scale);
  6574. srcOffset += 1;
  6575. destOffset += 3 + alpha01;
  6576. }
  6577. },
  6578. getOutputLength: function CalGrayCS_getOutputLength(inputLength, alpha01) {
  6579. return inputLength * (3 + alpha01);
  6580. },
  6581. isPassthrough: ColorSpace.prototype.isPassthrough,
  6582. fillRgb: ColorSpace.prototype.fillRgb,
  6583. isDefaultDecode: function CalGrayCS_isDefaultDecode(decodeMap) {
  6584. return ColorSpace.isDefaultDecode(decodeMap, this.numComps);
  6585. },
  6586. usesZeroToOneRange: true
  6587. };
  6588. return CalGrayCS;
  6589. })();
  6590. //
  6591. // CalRGBCS: Based on "PDF Reference, Sixth Ed", p.247
  6592. //
  6593. var CalRGBCS = (function CalRGBCSClosure() {
  6594. // See http://www.brucelindbloom.com/index.html?Eqn_ChromAdapt.html for these
  6595. // matrices.
  6596. var BRADFORD_SCALE_MATRIX = new Float32Array([
  6597. 0.8951, 0.2664, -0.1614,
  6598. -0.7502, 1.7135, 0.0367,
  6599. 0.0389, -0.0685, 1.0296]);
  6600. var BRADFORD_SCALE_INVERSE_MATRIX = new Float32Array([
  6601. 0.9869929, -0.1470543, 0.1599627,
  6602. 0.4323053, 0.5183603, 0.0492912,
  6603. -0.0085287, 0.0400428, 0.9684867]);
  6604. // See http://www.brucelindbloom.com/index.html?Eqn_RGB_XYZ_Matrix.html.
  6605. var SRGB_D65_XYZ_TO_RGB_MATRIX = new Float32Array([
  6606. 3.2404542, -1.5371385, -0.4985314,
  6607. -0.9692660, 1.8760108, 0.0415560,
  6608. 0.0556434, -0.2040259, 1.0572252]);
  6609. var FLAT_WHITEPOINT_MATRIX = new Float32Array([1, 1, 1]);
  6610. var tempNormalizeMatrix = new Float32Array(3);
  6611. var tempConvertMatrix1 = new Float32Array(3);
  6612. var tempConvertMatrix2 = new Float32Array(3);
  6613. var DECODE_L_CONSTANT = Math.pow(((8 + 16) / 116), 3) / 8.0;
  6614. function CalRGBCS(whitePoint, blackPoint, gamma, matrix) {
  6615. this.name = 'CalRGB';
  6616. this.numComps = 3;
  6617. this.defaultColor = new Float32Array(3);
  6618. if (!whitePoint) {
  6619. error('WhitePoint missing - required for color space CalRGB');
  6620. }
  6621. blackPoint = blackPoint || new Float32Array(3);
  6622. gamma = gamma || new Float32Array([1, 1, 1]);
  6623. matrix = matrix || new Float32Array([1, 0, 0, 0, 1, 0, 0, 0, 1]);
  6624. // Translate arguments to spec variables.
  6625. var XW = whitePoint[0];
  6626. var YW = whitePoint[1];
  6627. var ZW = whitePoint[2];
  6628. this.whitePoint = whitePoint;
  6629. var XB = blackPoint[0];
  6630. var YB = blackPoint[1];
  6631. var ZB = blackPoint[2];
  6632. this.blackPoint = blackPoint;
  6633. this.GR = gamma[0];
  6634. this.GG = gamma[1];
  6635. this.GB = gamma[2];
  6636. this.MXA = matrix[0];
  6637. this.MYA = matrix[1];
  6638. this.MZA = matrix[2];
  6639. this.MXB = matrix[3];
  6640. this.MYB = matrix[4];
  6641. this.MZB = matrix[5];
  6642. this.MXC = matrix[6];
  6643. this.MYC = matrix[7];
  6644. this.MZC = matrix[8];
  6645. // Validate variables as per spec.
  6646. if (XW < 0 || ZW < 0 || YW !== 1) {
  6647. error('Invalid WhitePoint components for ' + this.name +
  6648. ', no fallback available');
  6649. }
  6650. if (XB < 0 || YB < 0 || ZB < 0) {
  6651. info('Invalid BlackPoint for ' + this.name + ' [' + XB + ', ' + YB +
  6652. ', ' + ZB + '], falling back to default');
  6653. this.blackPoint = new Float32Array(3);
  6654. }
  6655. if (this.GR < 0 || this.GG < 0 || this.GB < 0) {
  6656. info('Invalid Gamma [' + this.GR + ', ' + this.GG + ', ' + this.GB +
  6657. '] for ' + this.name + ', falling back to default');
  6658. this.GR = this.GG = this.GB = 1;
  6659. }
  6660. if (this.MXA < 0 || this.MYA < 0 || this.MZA < 0 ||
  6661. this.MXB < 0 || this.MYB < 0 || this.MZB < 0 ||
  6662. this.MXC < 0 || this.MYC < 0 || this.MZC < 0) {
  6663. info('Invalid Matrix for ' + this.name + ' [' +
  6664. this.MXA + ', ' + this.MYA + ', ' + this.MZA +
  6665. this.MXB + ', ' + this.MYB + ', ' + this.MZB +
  6666. this.MXC + ', ' + this.MYC + ', ' + this.MZC +
  6667. '], falling back to default');
  6668. this.MXA = this.MYB = this.MZC = 1;
  6669. this.MXB = this.MYA = this.MZA = this.MXC = this.MYC = this.MZB = 0;
  6670. }
  6671. }
  6672. function matrixProduct(a, b, result) {
  6673. result[0] = a[0] * b[0] + a[1] * b[1] + a[2] * b[2];
  6674. result[1] = a[3] * b[0] + a[4] * b[1] + a[5] * b[2];
  6675. result[2] = a[6] * b[0] + a[7] * b[1] + a[8] * b[2];
  6676. }
  6677. function convertToFlat(sourceWhitePoint, LMS, result) {
  6678. result[0] = LMS[0] * 1 / sourceWhitePoint[0];
  6679. result[1] = LMS[1] * 1 / sourceWhitePoint[1];
  6680. result[2] = LMS[2] * 1 / sourceWhitePoint[2];
  6681. }
  6682. function convertToD65(sourceWhitePoint, LMS, result) {
  6683. var D65X = 0.95047;
  6684. var D65Y = 1;
  6685. var D65Z = 1.08883;
  6686. result[0] = LMS[0] * D65X / sourceWhitePoint[0];
  6687. result[1] = LMS[1] * D65Y / sourceWhitePoint[1];
  6688. result[2] = LMS[2] * D65Z / sourceWhitePoint[2];
  6689. }
  6690. function sRGBTransferFunction(color) {
  6691. // See http://en.wikipedia.org/wiki/SRGB.
  6692. if (color <= 0.0031308){
  6693. return adjustToRange(0, 1, 12.92 * color);
  6694. }
  6695. return adjustToRange(0, 1, (1 + 0.055) * Math.pow(color, 1 / 2.4) - 0.055);
  6696. }
  6697. function adjustToRange(min, max, value) {
  6698. return Math.max(min, Math.min(max, value));
  6699. }
  6700. function decodeL(L) {
  6701. if (L < 0) {
  6702. return -decodeL(-L);
  6703. }
  6704. if (L > 8.0) {
  6705. return Math.pow(((L + 16) / 116), 3);
  6706. }
  6707. return L * DECODE_L_CONSTANT;
  6708. }
  6709. function compensateBlackPoint(sourceBlackPoint, XYZ_Flat, result) {
  6710. // In case the blackPoint is already the default blackPoint then there is
  6711. // no need to do compensation.
  6712. if (sourceBlackPoint[0] === 0 &&
  6713. sourceBlackPoint[1] === 0 &&
  6714. sourceBlackPoint[2] === 0) {
  6715. result[0] = XYZ_Flat[0];
  6716. result[1] = XYZ_Flat[1];
  6717. result[2] = XYZ_Flat[2];
  6718. return;
  6719. }
  6720. // For the blackPoint calculation details, please see
  6721. // http://www.adobe.com/content/dam/Adobe/en/devnet/photoshop/sdk/
  6722. // AdobeBPC.pdf.
  6723. // The destination blackPoint is the default blackPoint [0, 0, 0].
  6724. var zeroDecodeL = decodeL(0);
  6725. var X_DST = zeroDecodeL;
  6726. var X_SRC = decodeL(sourceBlackPoint[0]);
  6727. var Y_DST = zeroDecodeL;
  6728. var Y_SRC = decodeL(sourceBlackPoint[1]);
  6729. var Z_DST = zeroDecodeL;
  6730. var Z_SRC = decodeL(sourceBlackPoint[2]);
  6731. var X_Scale = (1 - X_DST) / (1 - X_SRC);
  6732. var X_Offset = 1 - X_Scale;
  6733. var Y_Scale = (1 - Y_DST) / (1 - Y_SRC);
  6734. var Y_Offset = 1 - Y_Scale;
  6735. var Z_Scale = (1 - Z_DST) / (1 - Z_SRC);
  6736. var Z_Offset = 1 - Z_Scale;
  6737. result[0] = XYZ_Flat[0] * X_Scale + X_Offset;
  6738. result[1] = XYZ_Flat[1] * Y_Scale + Y_Offset;
  6739. result[2] = XYZ_Flat[2] * Z_Scale + Z_Offset;
  6740. }
  6741. function normalizeWhitePointToFlat(sourceWhitePoint, XYZ_In, result) {
  6742. // In case the whitePoint is already flat then there is no need to do
  6743. // normalization.
  6744. if (sourceWhitePoint[0] === 1 && sourceWhitePoint[2] === 1) {
  6745. result[0] = XYZ_In[0];
  6746. result[1] = XYZ_In[1];
  6747. result[2] = XYZ_In[2];
  6748. return;
  6749. }
  6750. var LMS = result;
  6751. matrixProduct(BRADFORD_SCALE_MATRIX, XYZ_In, LMS);
  6752. var LMS_Flat = tempNormalizeMatrix;
  6753. convertToFlat(sourceWhitePoint, LMS, LMS_Flat);
  6754. matrixProduct(BRADFORD_SCALE_INVERSE_MATRIX, LMS_Flat, result);
  6755. }
  6756. function normalizeWhitePointToD65(sourceWhitePoint, XYZ_In, result) {
  6757. var LMS = result;
  6758. matrixProduct(BRADFORD_SCALE_MATRIX, XYZ_In, LMS);
  6759. var LMS_D65 = tempNormalizeMatrix;
  6760. convertToD65(sourceWhitePoint, LMS, LMS_D65);
  6761. matrixProduct(BRADFORD_SCALE_INVERSE_MATRIX, LMS_D65, result);
  6762. }
  6763. function convertToRgb(cs, src, srcOffset, dest, destOffset, scale) {
  6764. // A, B and C represent a red, green and blue components of a calibrated
  6765. // rgb space.
  6766. var A = adjustToRange(0, 1, src[srcOffset] * scale);
  6767. var B = adjustToRange(0, 1, src[srcOffset + 1] * scale);
  6768. var C = adjustToRange(0, 1, src[srcOffset + 2] * scale);
  6769. // A <---> AGR in the spec
  6770. // B <---> BGG in the spec
  6771. // C <---> CGB in the spec
  6772. var AGR = Math.pow(A, cs.GR);
  6773. var BGG = Math.pow(B, cs.GG);
  6774. var CGB = Math.pow(C, cs.GB);
  6775. // Computes intermediate variables L, M, N as per spec.
  6776. // To decode X, Y, Z values map L, M, N directly to them.
  6777. var X = cs.MXA * AGR + cs.MXB * BGG + cs.MXC * CGB;
  6778. var Y = cs.MYA * AGR + cs.MYB * BGG + cs.MYC * CGB;
  6779. var Z = cs.MZA * AGR + cs.MZB * BGG + cs.MZC * CGB;
  6780. // The following calculations are based on this document:
  6781. // http://www.adobe.com/content/dam/Adobe/en/devnet/photoshop/sdk/
  6782. // AdobeBPC.pdf.
  6783. var XYZ = tempConvertMatrix1;
  6784. XYZ[0] = X;
  6785. XYZ[1] = Y;
  6786. XYZ[2] = Z;
  6787. var XYZ_Flat = tempConvertMatrix2;
  6788. normalizeWhitePointToFlat(cs.whitePoint, XYZ, XYZ_Flat);
  6789. var XYZ_Black = tempConvertMatrix1;
  6790. compensateBlackPoint(cs.blackPoint, XYZ_Flat, XYZ_Black);
  6791. var XYZ_D65 = tempConvertMatrix2;
  6792. normalizeWhitePointToD65(FLAT_WHITEPOINT_MATRIX, XYZ_Black, XYZ_D65);
  6793. var SRGB = tempConvertMatrix1;
  6794. matrixProduct(SRGB_D65_XYZ_TO_RGB_MATRIX, XYZ_D65, SRGB);
  6795. var sR = sRGBTransferFunction(SRGB[0]);
  6796. var sG = sRGBTransferFunction(SRGB[1]);
  6797. var sB = sRGBTransferFunction(SRGB[2]);
  6798. // Convert the values to rgb range [0, 255].
  6799. dest[destOffset] = Math.round(sR * 255);
  6800. dest[destOffset + 1] = Math.round(sG * 255);
  6801. dest[destOffset + 2] = Math.round(sB * 255);
  6802. }
  6803. CalRGBCS.prototype = {
  6804. getRgb: function CalRGBCS_getRgb(src, srcOffset) {
  6805. var rgb = new Uint8Array(3);
  6806. this.getRgbItem(src, srcOffset, rgb, 0);
  6807. return rgb;
  6808. },
  6809. getRgbItem: function CalRGBCS_getRgbItem(src, srcOffset,
  6810. dest, destOffset) {
  6811. convertToRgb(this, src, srcOffset, dest, destOffset, 1);
  6812. },
  6813. getRgbBuffer: function CalRGBCS_getRgbBuffer(src, srcOffset, count,
  6814. dest, destOffset, bits,
  6815. alpha01) {
  6816. var scale = 1 / ((1 << bits) - 1);
  6817. for (var i = 0; i < count; ++i) {
  6818. convertToRgb(this, src, srcOffset, dest, destOffset, scale);
  6819. srcOffset += 3;
  6820. destOffset += 3 + alpha01;
  6821. }
  6822. },
  6823. getOutputLength: function CalRGBCS_getOutputLength(inputLength, alpha01) {
  6824. return (inputLength * (3 + alpha01) / 3) | 0;
  6825. },
  6826. isPassthrough: ColorSpace.prototype.isPassthrough,
  6827. fillRgb: ColorSpace.prototype.fillRgb,
  6828. isDefaultDecode: function CalRGBCS_isDefaultDecode(decodeMap) {
  6829. return ColorSpace.isDefaultDecode(decodeMap, this.numComps);
  6830. },
  6831. usesZeroToOneRange: true
  6832. };
  6833. return CalRGBCS;
  6834. })();
  6835. //
  6836. // LabCS: Based on "PDF Reference, Sixth Ed", p.250
  6837. //
  6838. var LabCS = (function LabCSClosure() {
  6839. function LabCS(whitePoint, blackPoint, range) {
  6840. this.name = 'Lab';
  6841. this.numComps = 3;
  6842. this.defaultColor = new Float32Array([0, 0, 0]);
  6843. if (!whitePoint) {
  6844. error('WhitePoint missing - required for color space Lab');
  6845. }
  6846. blackPoint = blackPoint || [0, 0, 0];
  6847. range = range || [-100, 100, -100, 100];
  6848. // Translate args to spec variables
  6849. this.XW = whitePoint[0];
  6850. this.YW = whitePoint[1];
  6851. this.ZW = whitePoint[2];
  6852. this.amin = range[0];
  6853. this.amax = range[1];
  6854. this.bmin = range[2];
  6855. this.bmax = range[3];
  6856. // These are here just for completeness - the spec doesn't offer any
  6857. // formulas that use BlackPoint in Lab
  6858. this.XB = blackPoint[0];
  6859. this.YB = blackPoint[1];
  6860. this.ZB = blackPoint[2];
  6861. // Validate vars as per spec
  6862. if (this.XW < 0 || this.ZW < 0 || this.YW !== 1) {
  6863. error('Invalid WhitePoint components, no fallback available');
  6864. }
  6865. if (this.XB < 0 || this.YB < 0 || this.ZB < 0) {
  6866. info('Invalid BlackPoint, falling back to default');
  6867. this.XB = this.YB = this.ZB = 0;
  6868. }
  6869. if (this.amin > this.amax || this.bmin > this.bmax) {
  6870. info('Invalid Range, falling back to defaults');
  6871. this.amin = -100;
  6872. this.amax = 100;
  6873. this.bmin = -100;
  6874. this.bmax = 100;
  6875. }
  6876. }
  6877. // Function g(x) from spec
  6878. function fn_g(x) {
  6879. if (x >= 6 / 29) {
  6880. return x * x * x;
  6881. } else {
  6882. return (108 / 841) * (x - 4 / 29);
  6883. }
  6884. }
  6885. function decode(value, high1, low2, high2) {
  6886. return low2 + (value) * (high2 - low2) / (high1);
  6887. }
  6888. // If decoding is needed maxVal should be 2^bits per component - 1.
  6889. function convertToRgb(cs, src, srcOffset, maxVal, dest, destOffset) {
  6890. // XXX: Lab input is in the range of [0, 100], [amin, amax], [bmin, bmax]
  6891. // not the usual [0, 1]. If a command like setFillColor is used the src
  6892. // values will already be within the correct range. However, if we are
  6893. // converting an image we have to map the values to the correct range given
  6894. // above.
  6895. // Ls,as,bs <---> L*,a*,b* in the spec
  6896. var Ls = src[srcOffset];
  6897. var as = src[srcOffset + 1];
  6898. var bs = src[srcOffset + 2];
  6899. if (maxVal !== false) {
  6900. Ls = decode(Ls, maxVal, 0, 100);
  6901. as = decode(as, maxVal, cs.amin, cs.amax);
  6902. bs = decode(bs, maxVal, cs.bmin, cs.bmax);
  6903. }
  6904. // Adjust limits of 'as' and 'bs'
  6905. as = as > cs.amax ? cs.amax : as < cs.amin ? cs.amin : as;
  6906. bs = bs > cs.bmax ? cs.bmax : bs < cs.bmin ? cs.bmin : bs;
  6907. // Computes intermediate variables X,Y,Z as per spec
  6908. var M = (Ls + 16) / 116;
  6909. var L = M + (as / 500);
  6910. var N = M - (bs / 200);
  6911. var X = cs.XW * fn_g(L);
  6912. var Y = cs.YW * fn_g(M);
  6913. var Z = cs.ZW * fn_g(N);
  6914. var r, g, b;
  6915. // Using different conversions for D50 and D65 white points,
  6916. // per http://www.color.org/srgb.pdf
  6917. if (cs.ZW < 1) {
  6918. // Assuming D50 (X=0.9642, Y=1.00, Z=0.8249)
  6919. r = X * 3.1339 + Y * -1.6170 + Z * -0.4906;
  6920. g = X * -0.9785 + Y * 1.9160 + Z * 0.0333;
  6921. b = X * 0.0720 + Y * -0.2290 + Z * 1.4057;
  6922. } else {
  6923. // Assuming D65 (X=0.9505, Y=1.00, Z=1.0888)
  6924. r = X * 3.2406 + Y * -1.5372 + Z * -0.4986;
  6925. g = X * -0.9689 + Y * 1.8758 + Z * 0.0415;
  6926. b = X * 0.0557 + Y * -0.2040 + Z * 1.0570;
  6927. }
  6928. // clamp color values to [0,1] range then convert to [0,255] range.
  6929. dest[destOffset] = r <= 0 ? 0 : r >= 1 ? 255 : Math.sqrt(r) * 255 | 0;
  6930. dest[destOffset + 1] = g <= 0 ? 0 : g >= 1 ? 255 : Math.sqrt(g) * 255 | 0;
  6931. dest[destOffset + 2] = b <= 0 ? 0 : b >= 1 ? 255 : Math.sqrt(b) * 255 | 0;
  6932. }
  6933. LabCS.prototype = {
  6934. getRgb: ColorSpace.prototype.getRgb,
  6935. getRgbItem: function LabCS_getRgbItem(src, srcOffset, dest, destOffset) {
  6936. convertToRgb(this, src, srcOffset, false, dest, destOffset);
  6937. },
  6938. getRgbBuffer: function LabCS_getRgbBuffer(src, srcOffset, count,
  6939. dest, destOffset, bits,
  6940. alpha01) {
  6941. var maxVal = (1 << bits) - 1;
  6942. for (var i = 0; i < count; i++) {
  6943. convertToRgb(this, src, srcOffset, maxVal, dest, destOffset);
  6944. srcOffset += 3;
  6945. destOffset += 3 + alpha01;
  6946. }
  6947. },
  6948. getOutputLength: function LabCS_getOutputLength(inputLength, alpha01) {
  6949. return (inputLength * (3 + alpha01) / 3) | 0;
  6950. },
  6951. isPassthrough: ColorSpace.prototype.isPassthrough,
  6952. fillRgb: ColorSpace.prototype.fillRgb,
  6953. isDefaultDecode: function LabCS_isDefaultDecode(decodeMap) {
  6954. // XXX: Decoding is handled with the lab conversion because of the strange
  6955. // ranges that are used.
  6956. return true;
  6957. },
  6958. usesZeroToOneRange: false
  6959. };
  6960. return LabCS;
  6961. })();
  6962. var ARCFourCipher = (function ARCFourCipherClosure() {
  6963. function ARCFourCipher(key) {
  6964. this.a = 0;
  6965. this.b = 0;
  6966. var s = new Uint8Array(256);
  6967. var i, j = 0, tmp, keyLength = key.length;
  6968. for (i = 0; i < 256; ++i) {
  6969. s[i] = i;
  6970. }
  6971. for (i = 0; i < 256; ++i) {
  6972. tmp = s[i];
  6973. j = (j + tmp + key[i % keyLength]) & 0xFF;
  6974. s[i] = s[j];
  6975. s[j] = tmp;
  6976. }
  6977. this.s = s;
  6978. }
  6979. ARCFourCipher.prototype = {
  6980. encryptBlock: function ARCFourCipher_encryptBlock(data) {
  6981. var i, n = data.length, tmp, tmp2;
  6982. var a = this.a, b = this.b, s = this.s;
  6983. var output = new Uint8Array(n);
  6984. for (i = 0; i < n; ++i) {
  6985. a = (a + 1) & 0xFF;
  6986. tmp = s[a];
  6987. b = (b + tmp) & 0xFF;
  6988. tmp2 = s[b];
  6989. s[a] = tmp2;
  6990. s[b] = tmp;
  6991. output[i] = data[i] ^ s[(tmp + tmp2) & 0xFF];
  6992. }
  6993. this.a = a;
  6994. this.b = b;
  6995. return output;
  6996. }
  6997. };
  6998. ARCFourCipher.prototype.decryptBlock = ARCFourCipher.prototype.encryptBlock;
  6999. return ARCFourCipher;
  7000. })();
  7001. var calculateMD5 = (function calculateMD5Closure() {
  7002. var r = new Uint8Array([
  7003. 7, 12, 17, 22, 7, 12, 17, 22, 7, 12, 17, 22, 7, 12, 17, 22,
  7004. 5, 9, 14, 20, 5, 9, 14, 20, 5, 9, 14, 20, 5, 9, 14, 20,
  7005. 4, 11, 16, 23, 4, 11, 16, 23, 4, 11, 16, 23, 4, 11, 16, 23,
  7006. 6, 10, 15, 21, 6, 10, 15, 21, 6, 10, 15, 21, 6, 10, 15, 21]);
  7007. var k = new Int32Array([
  7008. -680876936, -389564586, 606105819, -1044525330, -176418897, 1200080426,
  7009. -1473231341, -45705983, 1770035416, -1958414417, -42063, -1990404162,
  7010. 1804603682, -40341101, -1502002290, 1236535329, -165796510, -1069501632,
  7011. 643717713, -373897302, -701558691, 38016083, -660478335, -405537848,
  7012. 568446438, -1019803690, -187363961, 1163531501, -1444681467, -51403784,
  7013. 1735328473, -1926607734, -378558, -2022574463, 1839030562, -35309556,
  7014. -1530992060, 1272893353, -155497632, -1094730640, 681279174, -358537222,
  7015. -722521979, 76029189, -640364487, -421815835, 530742520, -995338651,
  7016. -198630844, 1126891415, -1416354905, -57434055, 1700485571, -1894986606,
  7017. -1051523, -2054922799, 1873313359, -30611744, -1560198380, 1309151649,
  7018. -145523070, -1120210379, 718787259, -343485551]);
  7019. function hash(data, offset, length) {
  7020. var h0 = 1732584193, h1 = -271733879, h2 = -1732584194, h3 = 271733878;
  7021. // pre-processing
  7022. var paddedLength = (length + 72) & ~63; // data + 9 extra bytes
  7023. var padded = new Uint8Array(paddedLength);
  7024. var i, j, n;
  7025. for (i = 0; i < length; ++i) {
  7026. padded[i] = data[offset++];
  7027. }
  7028. padded[i++] = 0x80;
  7029. n = paddedLength - 8;
  7030. while (i < n) {
  7031. padded[i++] = 0;
  7032. }
  7033. padded[i++] = (length << 3) & 0xFF;
  7034. padded[i++] = (length >> 5) & 0xFF;
  7035. padded[i++] = (length >> 13) & 0xFF;
  7036. padded[i++] = (length >> 21) & 0xFF;
  7037. padded[i++] = (length >>> 29) & 0xFF;
  7038. padded[i++] = 0;
  7039. padded[i++] = 0;
  7040. padded[i++] = 0;
  7041. var w = new Int32Array(16);
  7042. for (i = 0; i < paddedLength;) {
  7043. for (j = 0; j < 16; ++j, i += 4) {
  7044. w[j] = (padded[i] | (padded[i + 1] << 8) |
  7045. (padded[i + 2] << 16) | (padded[i + 3] << 24));
  7046. }
  7047. var a = h0, b = h1, c = h2, d = h3, f, g;
  7048. for (j = 0; j < 64; ++j) {
  7049. if (j < 16) {
  7050. f = (b & c) | ((~b) & d);
  7051. g = j;
  7052. } else if (j < 32) {
  7053. f = (d & b) | ((~d) & c);
  7054. g = (5 * j + 1) & 15;
  7055. } else if (j < 48) {
  7056. f = b ^ c ^ d;
  7057. g = (3 * j + 5) & 15;
  7058. } else {
  7059. f = c ^ (b | (~d));
  7060. g = (7 * j) & 15;
  7061. }
  7062. var tmp = d, rotateArg = (a + f + k[j] + w[g]) | 0, rotate = r[j];
  7063. d = c;
  7064. c = b;
  7065. b = (b + ((rotateArg << rotate) | (rotateArg >>> (32 - rotate)))) | 0;
  7066. a = tmp;
  7067. }
  7068. h0 = (h0 + a) | 0;
  7069. h1 = (h1 + b) | 0;
  7070. h2 = (h2 + c) | 0;
  7071. h3 = (h3 + d) | 0;
  7072. }
  7073. return new Uint8Array([
  7074. h0 & 0xFF, (h0 >> 8) & 0xFF, (h0 >> 16) & 0xFF, (h0 >>> 24) & 0xFF,
  7075. h1 & 0xFF, (h1 >> 8) & 0xFF, (h1 >> 16) & 0xFF, (h1 >>> 24) & 0xFF,
  7076. h2 & 0xFF, (h2 >> 8) & 0xFF, (h2 >> 16) & 0xFF, (h2 >>> 24) & 0xFF,
  7077. h3 & 0xFF, (h3 >> 8) & 0xFF, (h3 >> 16) & 0xFF, (h3 >>> 24) & 0xFF
  7078. ]);
  7079. }
  7080. return hash;
  7081. })();
  7082. var Word64 = (function Word64Closure() {
  7083. function Word64(highInteger, lowInteger) {
  7084. this.high = highInteger | 0;
  7085. this.low = lowInteger | 0;
  7086. }
  7087. Word64.prototype = {
  7088. and: function Word64_and(word) {
  7089. this.high &= word.high;
  7090. this.low &= word.low;
  7091. },
  7092. xor: function Word64_xor(word) {
  7093. this.high ^= word.high;
  7094. this.low ^= word.low;
  7095. },
  7096. or: function Word64_or(word) {
  7097. this.high |= word.high;
  7098. this.low |= word.low;
  7099. },
  7100. shiftRight: function Word64_shiftRight(places) {
  7101. if (places >= 32) {
  7102. this.low = (this.high >>> (places - 32)) | 0;
  7103. this.high = 0;
  7104. } else {
  7105. this.low = (this.low >>> places) | (this.high << (32 - places));
  7106. this.high = (this.high >>> places) | 0;
  7107. }
  7108. },
  7109. shiftLeft: function Word64_shiftLeft(places) {
  7110. if (places >= 32) {
  7111. this.high = this.low << (places - 32);
  7112. this.low = 0;
  7113. } else {
  7114. this.high = (this.high << places) | (this.low >>> (32 - places));
  7115. this.low = this.low << places;
  7116. }
  7117. },
  7118. rotateRight: function Word64_rotateRight(places) {
  7119. var low, high;
  7120. if (places & 32) {
  7121. high = this.low;
  7122. low = this.high;
  7123. } else {
  7124. low = this.low;
  7125. high = this.high;
  7126. }
  7127. places &= 31;
  7128. this.low = (low >>> places) | (high << (32 - places));
  7129. this.high = (high >>> places) | (low << (32 - places));
  7130. },
  7131. not: function Word64_not() {
  7132. this.high = ~this.high;
  7133. this.low = ~this.low;
  7134. },
  7135. add: function Word64_add(word) {
  7136. var lowAdd = (this.low >>> 0) + (word.low >>> 0);
  7137. var highAdd = (this.high >>> 0) + (word.high >>> 0);
  7138. if (lowAdd > 0xFFFFFFFF) {
  7139. highAdd += 1;
  7140. }
  7141. this.low = lowAdd | 0;
  7142. this.high = highAdd | 0;
  7143. },
  7144. copyTo: function Word64_copyTo(bytes, offset) {
  7145. bytes[offset] = (this.high >>> 24) & 0xFF;
  7146. bytes[offset + 1] = (this.high >> 16) & 0xFF;
  7147. bytes[offset + 2] = (this.high >> 8) & 0xFF;
  7148. bytes[offset + 3] = this.high & 0xFF;
  7149. bytes[offset + 4] = (this.low >>> 24) & 0xFF;
  7150. bytes[offset + 5] = (this.low >> 16) & 0xFF;
  7151. bytes[offset + 6] = (this.low >> 8) & 0xFF;
  7152. bytes[offset + 7] = this.low & 0xFF;
  7153. },
  7154. assign: function Word64_assign(word) {
  7155. this.high = word.high;
  7156. this.low = word.low;
  7157. }
  7158. };
  7159. return Word64;
  7160. })();
  7161. var calculateSHA256 = (function calculateSHA256Closure() {
  7162. function rotr(x, n) {
  7163. return (x >>> n) | (x << 32 - n);
  7164. }
  7165. function ch(x, y, z) {
  7166. return (x & y) ^ (~x & z);
  7167. }
  7168. function maj(x, y, z) {
  7169. return (x & y) ^ (x & z) ^ (y & z);
  7170. }
  7171. function sigma(x) {
  7172. return rotr(x, 2) ^ rotr(x, 13) ^ rotr(x, 22);
  7173. }
  7174. function sigmaPrime(x) {
  7175. return rotr(x, 6) ^ rotr(x, 11) ^ rotr(x, 25);
  7176. }
  7177. function littleSigma(x) {
  7178. return rotr(x, 7) ^ rotr(x, 18) ^ x >>> 3;
  7179. }
  7180. function littleSigmaPrime(x) {
  7181. return rotr(x, 17) ^ rotr(x, 19) ^ x >>> 10;
  7182. }
  7183. var k = [0x428a2f98, 0x71374491, 0xb5c0fbcf, 0xe9b5dba5,
  7184. 0x3956c25b, 0x59f111f1, 0x923f82a4, 0xab1c5ed5,
  7185. 0xd807aa98, 0x12835b01, 0x243185be, 0x550c7dc3,
  7186. 0x72be5d74, 0x80deb1fe, 0x9bdc06a7, 0xc19bf174,
  7187. 0xe49b69c1, 0xefbe4786, 0x0fc19dc6, 0x240ca1cc,
  7188. 0x2de92c6f, 0x4a7484aa, 0x5cb0a9dc, 0x76f988da,
  7189. 0x983e5152, 0xa831c66d, 0xb00327c8, 0xbf597fc7,
  7190. 0xc6e00bf3, 0xd5a79147, 0x06ca6351, 0x14292967,
  7191. 0x27b70a85, 0x2e1b2138, 0x4d2c6dfc, 0x53380d13,
  7192. 0x650a7354, 0x766a0abb, 0x81c2c92e, 0x92722c85,
  7193. 0xa2bfe8a1, 0xa81a664b, 0xc24b8b70, 0xc76c51a3,
  7194. 0xd192e819, 0xd6990624, 0xf40e3585, 0x106aa070,
  7195. 0x19a4c116, 0x1e376c08, 0x2748774c, 0x34b0bcb5,
  7196. 0x391c0cb3, 0x4ed8aa4a, 0x5b9cca4f, 0x682e6ff3,
  7197. 0x748f82ee, 0x78a5636f, 0x84c87814, 0x8cc70208,
  7198. 0x90befffa, 0xa4506ceb, 0xbef9a3f7, 0xc67178f2];
  7199. function hash(data, offset, length) {
  7200. // initial hash values
  7201. var h0 = 0x6a09e667, h1 = 0xbb67ae85, h2 = 0x3c6ef372,
  7202. h3 = 0xa54ff53a, h4 = 0x510e527f, h5 = 0x9b05688c,
  7203. h6 = 0x1f83d9ab, h7 = 0x5be0cd19;
  7204. // pre-processing
  7205. var paddedLength = Math.ceil((length + 9) / 64) * 64;
  7206. var padded = new Uint8Array(paddedLength);
  7207. var i, j, n;
  7208. for (i = 0; i < length; ++i) {
  7209. padded[i] = data[offset++];
  7210. }
  7211. padded[i++] = 0x80;
  7212. n = paddedLength - 8;
  7213. while (i < n) {
  7214. padded[i++] = 0;
  7215. }
  7216. padded[i++] = 0;
  7217. padded[i++] = 0;
  7218. padded[i++] = 0;
  7219. padded[i++] = (length >>> 29) & 0xFF;
  7220. padded[i++] = (length >> 21) & 0xFF;
  7221. padded[i++] = (length >> 13) & 0xFF;
  7222. padded[i++] = (length >> 5) & 0xFF;
  7223. padded[i++] = (length << 3) & 0xFF;
  7224. var w = new Uint32Array(64);
  7225. // for each 512 bit block
  7226. for (i = 0; i < paddedLength;) {
  7227. for (j = 0; j < 16; ++j) {
  7228. w[j] = (padded[i] << 24 | (padded[i + 1] << 16) |
  7229. (padded[i + 2] << 8) | (padded[i + 3]));
  7230. i += 4;
  7231. }
  7232. for (j = 16; j < 64; ++j) {
  7233. w[j] = littleSigmaPrime(w[j - 2]) + w[j - 7] +
  7234. littleSigma(w[j - 15]) + w[j - 16] | 0;
  7235. }
  7236. var a = h0, b = h1, c = h2, d = h3, e = h4,
  7237. f = h5, g = h6, h = h7, t1, t2;
  7238. for (j = 0; j < 64; ++j) {
  7239. t1 = h + sigmaPrime(e) + ch(e, f, g) + k[j] + w[j];
  7240. t2 = sigma(a) + maj(a, b, c);
  7241. h = g;
  7242. g = f;
  7243. f = e;
  7244. e = (d + t1) | 0;
  7245. d = c;
  7246. c = b;
  7247. b = a;
  7248. a = (t1 + t2) | 0;
  7249. }
  7250. h0 = (h0 + a) | 0;
  7251. h1 = (h1 + b) | 0;
  7252. h2 = (h2 + c) | 0;
  7253. h3 = (h3 + d) | 0;
  7254. h4 = (h4 + e) | 0;
  7255. h5 = (h5 + f) | 0;
  7256. h6 = (h6 + g) | 0;
  7257. h7 = (h7 + h) | 0;
  7258. }
  7259. return new Uint8Array([
  7260. (h0 >> 24) & 0xFF, (h0 >> 16) & 0xFF, (h0 >> 8) & 0xFF, (h0) & 0xFF,
  7261. (h1 >> 24) & 0xFF, (h1 >> 16) & 0xFF, (h1 >> 8) & 0xFF, (h1) & 0xFF,
  7262. (h2 >> 24) & 0xFF, (h2 >> 16) & 0xFF, (h2 >> 8) & 0xFF, (h2) & 0xFF,
  7263. (h3 >> 24) & 0xFF, (h3 >> 16) & 0xFF, (h3 >> 8) & 0xFF, (h3) & 0xFF,
  7264. (h4 >> 24) & 0xFF, (h4 >> 16) & 0xFF, (h4 >> 8) & 0xFF, (h4) & 0xFF,
  7265. (h5 >> 24) & 0xFF, (h5 >> 16) & 0xFF, (h5 >> 8) & 0xFF, (h5) & 0xFF,
  7266. (h6 >> 24) & 0xFF, (h6 >> 16) & 0xFF, (h6 >> 8) & 0xFF, (h6) & 0xFF,
  7267. (h7 >> 24) & 0xFF, (h7 >> 16) & 0xFF, (h7 >> 8) & 0xFF, (h7) & 0xFF
  7268. ]);
  7269. }
  7270. return hash;
  7271. })();
  7272. var calculateSHA512 = (function calculateSHA512Closure() {
  7273. function ch(result, x, y, z, tmp) {
  7274. result.assign(x);
  7275. result.and(y);
  7276. tmp.assign(x);
  7277. tmp.not();
  7278. tmp.and(z);
  7279. result.xor(tmp);
  7280. }
  7281. function maj(result, x, y, z, tmp) {
  7282. result.assign(x);
  7283. result.and(y);
  7284. tmp.assign(x);
  7285. tmp.and(z);
  7286. result.xor(tmp);
  7287. tmp.assign(y);
  7288. tmp.and(z);
  7289. result.xor(tmp);
  7290. }
  7291. function sigma(result, x, tmp) {
  7292. result.assign(x);
  7293. result.rotateRight(28);
  7294. tmp.assign(x);
  7295. tmp.rotateRight(34);
  7296. result.xor(tmp);
  7297. tmp.assign(x);
  7298. tmp.rotateRight(39);
  7299. result.xor(tmp);
  7300. }
  7301. function sigmaPrime(result, x, tmp) {
  7302. result.assign(x);
  7303. result.rotateRight(14);
  7304. tmp.assign(x);
  7305. tmp.rotateRight(18);
  7306. result.xor(tmp);
  7307. tmp.assign(x);
  7308. tmp.rotateRight(41);
  7309. result.xor(tmp);
  7310. }
  7311. function littleSigma(result, x, tmp) {
  7312. result.assign(x);
  7313. result.rotateRight(1);
  7314. tmp.assign(x);
  7315. tmp.rotateRight(8);
  7316. result.xor(tmp);
  7317. tmp.assign(x);
  7318. tmp.shiftRight(7);
  7319. result.xor(tmp);
  7320. }
  7321. function littleSigmaPrime(result, x, tmp) {
  7322. result.assign(x);
  7323. result.rotateRight(19);
  7324. tmp.assign(x);
  7325. tmp.rotateRight(61);
  7326. result.xor(tmp);
  7327. tmp.assign(x);
  7328. tmp.shiftRight(6);
  7329. result.xor(tmp);
  7330. }
  7331. var k = [
  7332. new Word64(0x428a2f98, 0xd728ae22), new Word64(0x71374491, 0x23ef65cd),
  7333. new Word64(0xb5c0fbcf, 0xec4d3b2f), new Word64(0xe9b5dba5, 0x8189dbbc),
  7334. new Word64(0x3956c25b, 0xf348b538), new Word64(0x59f111f1, 0xb605d019),
  7335. new Word64(0x923f82a4, 0xaf194f9b), new Word64(0xab1c5ed5, 0xda6d8118),
  7336. new Word64(0xd807aa98, 0xa3030242), new Word64(0x12835b01, 0x45706fbe),
  7337. new Word64(0x243185be, 0x4ee4b28c), new Word64(0x550c7dc3, 0xd5ffb4e2),
  7338. new Word64(0x72be5d74, 0xf27b896f), new Word64(0x80deb1fe, 0x3b1696b1),
  7339. new Word64(0x9bdc06a7, 0x25c71235), new Word64(0xc19bf174, 0xcf692694),
  7340. new Word64(0xe49b69c1, 0x9ef14ad2), new Word64(0xefbe4786, 0x384f25e3),
  7341. new Word64(0x0fc19dc6, 0x8b8cd5b5), new Word64(0x240ca1cc, 0x77ac9c65),
  7342. new Word64(0x2de92c6f, 0x592b0275), new Word64(0x4a7484aa, 0x6ea6e483),
  7343. new Word64(0x5cb0a9dc, 0xbd41fbd4), new Word64(0x76f988da, 0x831153b5),
  7344. new Word64(0x983e5152, 0xee66dfab), new Word64(0xa831c66d, 0x2db43210),
  7345. new Word64(0xb00327c8, 0x98fb213f), new Word64(0xbf597fc7, 0xbeef0ee4),
  7346. new Word64(0xc6e00bf3, 0x3da88fc2), new Word64(0xd5a79147, 0x930aa725),
  7347. new Word64(0x06ca6351, 0xe003826f), new Word64(0x14292967, 0x0a0e6e70),
  7348. new Word64(0x27b70a85, 0x46d22ffc), new Word64(0x2e1b2138, 0x5c26c926),
  7349. new Word64(0x4d2c6dfc, 0x5ac42aed), new Word64(0x53380d13, 0x9d95b3df),
  7350. new Word64(0x650a7354, 0x8baf63de), new Word64(0x766a0abb, 0x3c77b2a8),
  7351. new Word64(0x81c2c92e, 0x47edaee6), new Word64(0x92722c85, 0x1482353b),
  7352. new Word64(0xa2bfe8a1, 0x4cf10364), new Word64(0xa81a664b, 0xbc423001),
  7353. new Word64(0xc24b8b70, 0xd0f89791), new Word64(0xc76c51a3, 0x0654be30),
  7354. new Word64(0xd192e819, 0xd6ef5218), new Word64(0xd6990624, 0x5565a910),
  7355. new Word64(0xf40e3585, 0x5771202a), new Word64(0x106aa070, 0x32bbd1b8),
  7356. new Word64(0x19a4c116, 0xb8d2d0c8), new Word64(0x1e376c08, 0x5141ab53),
  7357. new Word64(0x2748774c, 0xdf8eeb99), new Word64(0x34b0bcb5, 0xe19b48a8),
  7358. new Word64(0x391c0cb3, 0xc5c95a63), new Word64(0x4ed8aa4a, 0xe3418acb),
  7359. new Word64(0x5b9cca4f, 0x7763e373), new Word64(0x682e6ff3, 0xd6b2b8a3),
  7360. new Word64(0x748f82ee, 0x5defb2fc), new Word64(0x78a5636f, 0x43172f60),
  7361. new Word64(0x84c87814, 0xa1f0ab72), new Word64(0x8cc70208, 0x1a6439ec),
  7362. new Word64(0x90befffa, 0x23631e28), new Word64(0xa4506ceb, 0xde82bde9),
  7363. new Word64(0xbef9a3f7, 0xb2c67915), new Word64(0xc67178f2, 0xe372532b),
  7364. new Word64(0xca273ece, 0xea26619c), new Word64(0xd186b8c7, 0x21c0c207),
  7365. new Word64(0xeada7dd6, 0xcde0eb1e), new Word64(0xf57d4f7f, 0xee6ed178),
  7366. new Word64(0x06f067aa, 0x72176fba), new Word64(0x0a637dc5, 0xa2c898a6),
  7367. new Word64(0x113f9804, 0xbef90dae), new Word64(0x1b710b35, 0x131c471b),
  7368. new Word64(0x28db77f5, 0x23047d84), new Word64(0x32caab7b, 0x40c72493),
  7369. new Word64(0x3c9ebe0a, 0x15c9bebc), new Word64(0x431d67c4, 0x9c100d4c),
  7370. new Word64(0x4cc5d4be, 0xcb3e42b6), new Word64(0x597f299c, 0xfc657e2a),
  7371. new Word64(0x5fcb6fab, 0x3ad6faec), new Word64(0x6c44198c, 0x4a475817)];
  7372. function hash(data, offset, length, mode384) {
  7373. mode384 = !!mode384;
  7374. // initial hash values
  7375. var h0, h1, h2, h3, h4, h5, h6, h7;
  7376. if (!mode384) {
  7377. h0 = new Word64(0x6a09e667, 0xf3bcc908);
  7378. h1 = new Word64(0xbb67ae85, 0x84caa73b);
  7379. h2 = new Word64(0x3c6ef372, 0xfe94f82b);
  7380. h3 = new Word64(0xa54ff53a, 0x5f1d36f1);
  7381. h4 = new Word64(0x510e527f, 0xade682d1);
  7382. h5 = new Word64(0x9b05688c, 0x2b3e6c1f);
  7383. h6 = new Word64(0x1f83d9ab, 0xfb41bd6b);
  7384. h7 = new Word64(0x5be0cd19, 0x137e2179);
  7385. }
  7386. else {
  7387. // SHA384 is exactly the same
  7388. // except with different starting values and a trimmed result
  7389. h0 = new Word64(0xcbbb9d5d, 0xc1059ed8);
  7390. h1 = new Word64(0x629a292a, 0x367cd507);
  7391. h2 = new Word64(0x9159015a, 0x3070dd17);
  7392. h3 = new Word64(0x152fecd8, 0xf70e5939);
  7393. h4 = new Word64(0x67332667, 0xffc00b31);
  7394. h5 = new Word64(0x8eb44a87, 0x68581511);
  7395. h6 = new Word64(0xdb0c2e0d, 0x64f98fa7);
  7396. h7 = new Word64(0x47b5481d, 0xbefa4fa4);
  7397. }
  7398. // pre-processing
  7399. var paddedLength = Math.ceil((length + 17) / 128) * 128;
  7400. var padded = new Uint8Array(paddedLength);
  7401. var i, j, n;
  7402. for (i = 0; i < length; ++i) {
  7403. padded[i] = data[offset++];
  7404. }
  7405. padded[i++] = 0x80;
  7406. n = paddedLength - 16;
  7407. while (i < n) {
  7408. padded[i++] = 0;
  7409. }
  7410. padded[i++] = 0;
  7411. padded[i++] = 0;
  7412. padded[i++] = 0;
  7413. padded[i++] = 0;
  7414. padded[i++] = 0;
  7415. padded[i++] = 0;
  7416. padded[i++] = 0;
  7417. padded[i++] = 0;
  7418. padded[i++] = 0;
  7419. padded[i++] = 0;
  7420. padded[i++] = 0;
  7421. padded[i++] = (length >>> 29) & 0xFF;
  7422. padded[i++] = (length >> 21) & 0xFF;
  7423. padded[i++] = (length >> 13) & 0xFF;
  7424. padded[i++] = (length >> 5) & 0xFF;
  7425. padded[i++] = (length << 3) & 0xFF;
  7426. var w = new Array(80);
  7427. for (i = 0; i < 80; i++) {
  7428. w[i] = new Word64(0, 0);
  7429. }
  7430. var a = new Word64(0, 0), b = new Word64(0, 0), c = new Word64(0, 0);
  7431. var d = new Word64(0, 0), e = new Word64(0, 0), f = new Word64(0, 0);
  7432. var g = new Word64(0, 0), h = new Word64(0, 0);
  7433. var t1 = new Word64(0, 0), t2 = new Word64(0, 0);
  7434. var tmp1 = new Word64(0, 0), tmp2 = new Word64(0, 0), tmp3;
  7435. // for each 1024 bit block
  7436. for (i = 0; i < paddedLength;) {
  7437. for (j = 0; j < 16; ++j) {
  7438. w[j].high = (padded[i] << 24) | (padded[i + 1] << 16) |
  7439. (padded[i + 2] << 8) | (padded[i + 3]);
  7440. w[j].low = (padded[i + 4]) << 24 | (padded[i + 5]) << 16 |
  7441. (padded[i + 6]) << 8 | (padded[i + 7]);
  7442. i += 8;
  7443. }
  7444. for (j = 16; j < 80; ++j) {
  7445. tmp3 = w[j];
  7446. littleSigmaPrime(tmp3, w[j - 2], tmp2);
  7447. tmp3.add(w[j - 7]);
  7448. littleSigma(tmp1, w[j - 15], tmp2);
  7449. tmp3.add(tmp1);
  7450. tmp3.add(w[j - 16]);
  7451. }
  7452. a.assign(h0); b.assign(h1); c.assign(h2); d.assign(h3);
  7453. e.assign(h4); f.assign(h5); g.assign(h6); h.assign(h7);
  7454. for (j = 0; j < 80; ++j) {
  7455. t1.assign(h);
  7456. sigmaPrime(tmp1, e, tmp2);
  7457. t1.add(tmp1);
  7458. ch(tmp1, e, f, g, tmp2);
  7459. t1.add(tmp1);
  7460. t1.add(k[j]);
  7461. t1.add(w[j]);
  7462. sigma(t2, a, tmp2);
  7463. maj(tmp1, a, b, c, tmp2);
  7464. t2.add(tmp1);
  7465. tmp3 = h;
  7466. h = g;
  7467. g = f;
  7468. f = e;
  7469. d.add(t1);
  7470. e = d;
  7471. d = c;
  7472. c = b;
  7473. b = a;
  7474. tmp3.assign(t1);
  7475. tmp3.add(t2);
  7476. a = tmp3;
  7477. }
  7478. h0.add(a);
  7479. h1.add(b);
  7480. h2.add(c);
  7481. h3.add(d);
  7482. h4.add(e);
  7483. h5.add(f);
  7484. h6.add(g);
  7485. h7.add(h);
  7486. }
  7487. var result;
  7488. if (!mode384) {
  7489. result = new Uint8Array(64);
  7490. h0.copyTo(result,0);
  7491. h1.copyTo(result,8);
  7492. h2.copyTo(result,16);
  7493. h3.copyTo(result,24);
  7494. h4.copyTo(result,32);
  7495. h5.copyTo(result,40);
  7496. h6.copyTo(result,48);
  7497. h7.copyTo(result,56);
  7498. }
  7499. else {
  7500. result = new Uint8Array(48);
  7501. h0.copyTo(result,0);
  7502. h1.copyTo(result,8);
  7503. h2.copyTo(result,16);
  7504. h3.copyTo(result,24);
  7505. h4.copyTo(result,32);
  7506. h5.copyTo(result,40);
  7507. }
  7508. return result;
  7509. }
  7510. return hash;
  7511. })();
  7512. var calculateSHA384 = (function calculateSHA384Closure() {
  7513. function hash(data, offset, length) {
  7514. return calculateSHA512(data, offset, length, true);
  7515. }
  7516. return hash;
  7517. })();
  7518. var NullCipher = (function NullCipherClosure() {
  7519. function NullCipher() {
  7520. }
  7521. NullCipher.prototype = {
  7522. decryptBlock: function NullCipher_decryptBlock(data) {
  7523. return data;
  7524. }
  7525. };
  7526. return NullCipher;
  7527. })();
  7528. var AES128Cipher = (function AES128CipherClosure() {
  7529. var rcon = new Uint8Array([
  7530. 0x8d, 0x01, 0x02, 0x04, 0x08, 0x10, 0x20, 0x40, 0x80, 0x1b, 0x36, 0x6c,
  7531. 0xd8, 0xab, 0x4d, 0x9a, 0x2f, 0x5e, 0xbc, 0x63, 0xc6, 0x97, 0x35, 0x6a,
  7532. 0xd4, 0xb3, 0x7d, 0xfa, 0xef, 0xc5, 0x91, 0x39, 0x72, 0xe4, 0xd3, 0xbd,
  7533. 0x61, 0xc2, 0x9f, 0x25, 0x4a, 0x94, 0x33, 0x66, 0xcc, 0x83, 0x1d, 0x3a,
  7534. 0x74, 0xe8, 0xcb, 0x8d, 0x01, 0x02, 0x04, 0x08, 0x10, 0x20, 0x40, 0x80,
  7535. 0x1b, 0x36, 0x6c, 0xd8, 0xab, 0x4d, 0x9a, 0x2f, 0x5e, 0xbc, 0x63, 0xc6,
  7536. 0x97, 0x35, 0x6a, 0xd4, 0xb3, 0x7d, 0xfa, 0xef, 0xc5, 0x91, 0x39, 0x72,
  7537. 0xe4, 0xd3, 0xbd, 0x61, 0xc2, 0x9f, 0x25, 0x4a, 0x94, 0x33, 0x66, 0xcc,
  7538. 0x83, 0x1d, 0x3a, 0x74, 0xe8, 0xcb, 0x8d, 0x01, 0x02, 0x04, 0x08, 0x10,
  7539. 0x20, 0x40, 0x80, 0x1b, 0x36, 0x6c, 0xd8, 0xab, 0x4d, 0x9a, 0x2f, 0x5e,
  7540. 0xbc, 0x63, 0xc6, 0x97, 0x35, 0x6a, 0xd4, 0xb3, 0x7d, 0xfa, 0xef, 0xc5,
  7541. 0x91, 0x39, 0x72, 0xe4, 0xd3, 0xbd, 0x61, 0xc2, 0x9f, 0x25, 0x4a, 0x94,
  7542. 0x33, 0x66, 0xcc, 0x83, 0x1d, 0x3a, 0x74, 0xe8, 0xcb, 0x8d, 0x01, 0x02,
  7543. 0x04, 0x08, 0x10, 0x20, 0x40, 0x80, 0x1b, 0x36, 0x6c, 0xd8, 0xab, 0x4d,
  7544. 0x9a, 0x2f, 0x5e, 0xbc, 0x63, 0xc6, 0x97, 0x35, 0x6a, 0xd4, 0xb3, 0x7d,
  7545. 0xfa, 0xef, 0xc5, 0x91, 0x39, 0x72, 0xe4, 0xd3, 0xbd, 0x61, 0xc2, 0x9f,
  7546. 0x25, 0x4a, 0x94, 0x33, 0x66, 0xcc, 0x83, 0x1d, 0x3a, 0x74, 0xe8, 0xcb,
  7547. 0x8d, 0x01, 0x02, 0x04, 0x08, 0x10, 0x20, 0x40, 0x80, 0x1b, 0x36, 0x6c,
  7548. 0xd8, 0xab, 0x4d, 0x9a, 0x2f, 0x5e, 0xbc, 0x63, 0xc6, 0x97, 0x35, 0x6a,
  7549. 0xd4, 0xb3, 0x7d, 0xfa, 0xef, 0xc5, 0x91, 0x39, 0x72, 0xe4, 0xd3, 0xbd,
  7550. 0x61, 0xc2, 0x9f, 0x25, 0x4a, 0x94, 0x33, 0x66, 0xcc, 0x83, 0x1d, 0x3a,
  7551. 0x74, 0xe8, 0xcb, 0x8d]);
  7552. var s = new Uint8Array([
  7553. 0x63, 0x7c, 0x77, 0x7b, 0xf2, 0x6b, 0x6f, 0xc5, 0x30, 0x01, 0x67, 0x2b,
  7554. 0xfe, 0xd7, 0xab, 0x76, 0xca, 0x82, 0xc9, 0x7d, 0xfa, 0x59, 0x47, 0xf0,
  7555. 0xad, 0xd4, 0xa2, 0xaf, 0x9c, 0xa4, 0x72, 0xc0, 0xb7, 0xfd, 0x93, 0x26,
  7556. 0x36, 0x3f, 0xf7, 0xcc, 0x34, 0xa5, 0xe5, 0xf1, 0x71, 0xd8, 0x31, 0x15,
  7557. 0x04, 0xc7, 0x23, 0xc3, 0x18, 0x96, 0x05, 0x9a, 0x07, 0x12, 0x80, 0xe2,
  7558. 0xeb, 0x27, 0xb2, 0x75, 0x09, 0x83, 0x2c, 0x1a, 0x1b, 0x6e, 0x5a, 0xa0,
  7559. 0x52, 0x3b, 0xd6, 0xb3, 0x29, 0xe3, 0x2f, 0x84, 0x53, 0xd1, 0x00, 0xed,
  7560. 0x20, 0xfc, 0xb1, 0x5b, 0x6a, 0xcb, 0xbe, 0x39, 0x4a, 0x4c, 0x58, 0xcf,
  7561. 0xd0, 0xef, 0xaa, 0xfb, 0x43, 0x4d, 0x33, 0x85, 0x45, 0xf9, 0x02, 0x7f,
  7562. 0x50, 0x3c, 0x9f, 0xa8, 0x51, 0xa3, 0x40, 0x8f, 0x92, 0x9d, 0x38, 0xf5,
  7563. 0xbc, 0xb6, 0xda, 0x21, 0x10, 0xff, 0xf3, 0xd2, 0xcd, 0x0c, 0x13, 0xec,
  7564. 0x5f, 0x97, 0x44, 0x17, 0xc4, 0xa7, 0x7e, 0x3d, 0x64, 0x5d, 0x19, 0x73,
  7565. 0x60, 0x81, 0x4f, 0xdc, 0x22, 0x2a, 0x90, 0x88, 0x46, 0xee, 0xb8, 0x14,
  7566. 0xde, 0x5e, 0x0b, 0xdb, 0xe0, 0x32, 0x3a, 0x0a, 0x49, 0x06, 0x24, 0x5c,
  7567. 0xc2, 0xd3, 0xac, 0x62, 0x91, 0x95, 0xe4, 0x79, 0xe7, 0xc8, 0x37, 0x6d,
  7568. 0x8d, 0xd5, 0x4e, 0xa9, 0x6c, 0x56, 0xf4, 0xea, 0x65, 0x7a, 0xae, 0x08,
  7569. 0xba, 0x78, 0x25, 0x2e, 0x1c, 0xa6, 0xb4, 0xc6, 0xe8, 0xdd, 0x74, 0x1f,
  7570. 0x4b, 0xbd, 0x8b, 0x8a, 0x70, 0x3e, 0xb5, 0x66, 0x48, 0x03, 0xf6, 0x0e,
  7571. 0x61, 0x35, 0x57, 0xb9, 0x86, 0xc1, 0x1d, 0x9e, 0xe1, 0xf8, 0x98, 0x11,
  7572. 0x69, 0xd9, 0x8e, 0x94, 0x9b, 0x1e, 0x87, 0xe9, 0xce, 0x55, 0x28, 0xdf,
  7573. 0x8c, 0xa1, 0x89, 0x0d, 0xbf, 0xe6, 0x42, 0x68, 0x41, 0x99, 0x2d, 0x0f,
  7574. 0xb0, 0x54, 0xbb, 0x16]);
  7575. var inv_s = new Uint8Array([
  7576. 0x52, 0x09, 0x6a, 0xd5, 0x30, 0x36, 0xa5, 0x38, 0xbf, 0x40, 0xa3, 0x9e,
  7577. 0x81, 0xf3, 0xd7, 0xfb, 0x7c, 0xe3, 0x39, 0x82, 0x9b, 0x2f, 0xff, 0x87,
  7578. 0x34, 0x8e, 0x43, 0x44, 0xc4, 0xde, 0xe9, 0xcb, 0x54, 0x7b, 0x94, 0x32,
  7579. 0xa6, 0xc2, 0x23, 0x3d, 0xee, 0x4c, 0x95, 0x0b, 0x42, 0xfa, 0xc3, 0x4e,
  7580. 0x08, 0x2e, 0xa1, 0x66, 0x28, 0xd9, 0x24, 0xb2, 0x76, 0x5b, 0xa2, 0x49,
  7581. 0x6d, 0x8b, 0xd1, 0x25, 0x72, 0xf8, 0xf6, 0x64, 0x86, 0x68, 0x98, 0x16,
  7582. 0xd4, 0xa4, 0x5c, 0xcc, 0x5d, 0x65, 0xb6, 0x92, 0x6c, 0x70, 0x48, 0x50,
  7583. 0xfd, 0xed, 0xb9, 0xda, 0x5e, 0x15, 0x46, 0x57, 0xa7, 0x8d, 0x9d, 0x84,
  7584. 0x90, 0xd8, 0xab, 0x00, 0x8c, 0xbc, 0xd3, 0x0a, 0xf7, 0xe4, 0x58, 0x05,
  7585. 0xb8, 0xb3, 0x45, 0x06, 0xd0, 0x2c, 0x1e, 0x8f, 0xca, 0x3f, 0x0f, 0x02,
  7586. 0xc1, 0xaf, 0xbd, 0x03, 0x01, 0x13, 0x8a, 0x6b, 0x3a, 0x91, 0x11, 0x41,
  7587. 0x4f, 0x67, 0xdc, 0xea, 0x97, 0xf2, 0xcf, 0xce, 0xf0, 0xb4, 0xe6, 0x73,
  7588. 0x96, 0xac, 0x74, 0x22, 0xe7, 0xad, 0x35, 0x85, 0xe2, 0xf9, 0x37, 0xe8,
  7589. 0x1c, 0x75, 0xdf, 0x6e, 0x47, 0xf1, 0x1a, 0x71, 0x1d, 0x29, 0xc5, 0x89,
  7590. 0x6f, 0xb7, 0x62, 0x0e, 0xaa, 0x18, 0xbe, 0x1b, 0xfc, 0x56, 0x3e, 0x4b,
  7591. 0xc6, 0xd2, 0x79, 0x20, 0x9a, 0xdb, 0xc0, 0xfe, 0x78, 0xcd, 0x5a, 0xf4,
  7592. 0x1f, 0xdd, 0xa8, 0x33, 0x88, 0x07, 0xc7, 0x31, 0xb1, 0x12, 0x10, 0x59,
  7593. 0x27, 0x80, 0xec, 0x5f, 0x60, 0x51, 0x7f, 0xa9, 0x19, 0xb5, 0x4a, 0x0d,
  7594. 0x2d, 0xe5, 0x7a, 0x9f, 0x93, 0xc9, 0x9c, 0xef, 0xa0, 0xe0, 0x3b, 0x4d,
  7595. 0xae, 0x2a, 0xf5, 0xb0, 0xc8, 0xeb, 0xbb, 0x3c, 0x83, 0x53, 0x99, 0x61,
  7596. 0x17, 0x2b, 0x04, 0x7e, 0xba, 0x77, 0xd6, 0x26, 0xe1, 0x69, 0x14, 0x63,
  7597. 0x55, 0x21, 0x0c, 0x7d]);
  7598. var mixCol = new Uint8Array(256);
  7599. for (var i = 0; i < 256; i++) {
  7600. if (i < 128) {
  7601. mixCol[i] = i << 1;
  7602. } else {
  7603. mixCol[i] = (i << 1) ^ 0x1b;
  7604. }
  7605. }
  7606. var mix = new Uint32Array([
  7607. 0x00000000, 0x0e090d0b, 0x1c121a16, 0x121b171d, 0x3824342c, 0x362d3927,
  7608. 0x24362e3a, 0x2a3f2331, 0x70486858, 0x7e416553, 0x6c5a724e, 0x62537f45,
  7609. 0x486c5c74, 0x4665517f, 0x547e4662, 0x5a774b69, 0xe090d0b0, 0xee99ddbb,
  7610. 0xfc82caa6, 0xf28bc7ad, 0xd8b4e49c, 0xd6bde997, 0xc4a6fe8a, 0xcaaff381,
  7611. 0x90d8b8e8, 0x9ed1b5e3, 0x8ccaa2fe, 0x82c3aff5, 0xa8fc8cc4, 0xa6f581cf,
  7612. 0xb4ee96d2, 0xbae79bd9, 0xdb3bbb7b, 0xd532b670, 0xc729a16d, 0xc920ac66,
  7613. 0xe31f8f57, 0xed16825c, 0xff0d9541, 0xf104984a, 0xab73d323, 0xa57ade28,
  7614. 0xb761c935, 0xb968c43e, 0x9357e70f, 0x9d5eea04, 0x8f45fd19, 0x814cf012,
  7615. 0x3bab6bcb, 0x35a266c0, 0x27b971dd, 0x29b07cd6, 0x038f5fe7, 0x0d8652ec,
  7616. 0x1f9d45f1, 0x119448fa, 0x4be30393, 0x45ea0e98, 0x57f11985, 0x59f8148e,
  7617. 0x73c737bf, 0x7dce3ab4, 0x6fd52da9, 0x61dc20a2, 0xad766df6, 0xa37f60fd,
  7618. 0xb16477e0, 0xbf6d7aeb, 0x955259da, 0x9b5b54d1, 0x894043cc, 0x87494ec7,
  7619. 0xdd3e05ae, 0xd33708a5, 0xc12c1fb8, 0xcf2512b3, 0xe51a3182, 0xeb133c89,
  7620. 0xf9082b94, 0xf701269f, 0x4de6bd46, 0x43efb04d, 0x51f4a750, 0x5ffdaa5b,
  7621. 0x75c2896a, 0x7bcb8461, 0x69d0937c, 0x67d99e77, 0x3daed51e, 0x33a7d815,
  7622. 0x21bccf08, 0x2fb5c203, 0x058ae132, 0x0b83ec39, 0x1998fb24, 0x1791f62f,
  7623. 0x764dd68d, 0x7844db86, 0x6a5fcc9b, 0x6456c190, 0x4e69e2a1, 0x4060efaa,
  7624. 0x527bf8b7, 0x5c72f5bc, 0x0605bed5, 0x080cb3de, 0x1a17a4c3, 0x141ea9c8,
  7625. 0x3e218af9, 0x302887f2, 0x223390ef, 0x2c3a9de4, 0x96dd063d, 0x98d40b36,
  7626. 0x8acf1c2b, 0x84c61120, 0xaef93211, 0xa0f03f1a, 0xb2eb2807, 0xbce2250c,
  7627. 0xe6956e65, 0xe89c636e, 0xfa877473, 0xf48e7978, 0xdeb15a49, 0xd0b85742,
  7628. 0xc2a3405f, 0xccaa4d54, 0x41ecdaf7, 0x4fe5d7fc, 0x5dfec0e1, 0x53f7cdea,
  7629. 0x79c8eedb, 0x77c1e3d0, 0x65daf4cd, 0x6bd3f9c6, 0x31a4b2af, 0x3fadbfa4,
  7630. 0x2db6a8b9, 0x23bfa5b2, 0x09808683, 0x07898b88, 0x15929c95, 0x1b9b919e,
  7631. 0xa17c0a47, 0xaf75074c, 0xbd6e1051, 0xb3671d5a, 0x99583e6b, 0x97513360,
  7632. 0x854a247d, 0x8b432976, 0xd134621f, 0xdf3d6f14, 0xcd267809, 0xc32f7502,
  7633. 0xe9105633, 0xe7195b38, 0xf5024c25, 0xfb0b412e, 0x9ad7618c, 0x94de6c87,
  7634. 0x86c57b9a, 0x88cc7691, 0xa2f355a0, 0xacfa58ab, 0xbee14fb6, 0xb0e842bd,
  7635. 0xea9f09d4, 0xe49604df, 0xf68d13c2, 0xf8841ec9, 0xd2bb3df8, 0xdcb230f3,
  7636. 0xcea927ee, 0xc0a02ae5, 0x7a47b13c, 0x744ebc37, 0x6655ab2a, 0x685ca621,
  7637. 0x42638510, 0x4c6a881b, 0x5e719f06, 0x5078920d, 0x0a0fd964, 0x0406d46f,
  7638. 0x161dc372, 0x1814ce79, 0x322bed48, 0x3c22e043, 0x2e39f75e, 0x2030fa55,
  7639. 0xec9ab701, 0xe293ba0a, 0xf088ad17, 0xfe81a01c, 0xd4be832d, 0xdab78e26,
  7640. 0xc8ac993b, 0xc6a59430, 0x9cd2df59, 0x92dbd252, 0x80c0c54f, 0x8ec9c844,
  7641. 0xa4f6eb75, 0xaaffe67e, 0xb8e4f163, 0xb6edfc68, 0x0c0a67b1, 0x02036aba,
  7642. 0x10187da7, 0x1e1170ac, 0x342e539d, 0x3a275e96, 0x283c498b, 0x26354480,
  7643. 0x7c420fe9, 0x724b02e2, 0x605015ff, 0x6e5918f4, 0x44663bc5, 0x4a6f36ce,
  7644. 0x587421d3, 0x567d2cd8, 0x37a10c7a, 0x39a80171, 0x2bb3166c, 0x25ba1b67,
  7645. 0x0f853856, 0x018c355d, 0x13972240, 0x1d9e2f4b, 0x47e96422, 0x49e06929,
  7646. 0x5bfb7e34, 0x55f2733f, 0x7fcd500e, 0x71c45d05, 0x63df4a18, 0x6dd64713,
  7647. 0xd731dcca, 0xd938d1c1, 0xcb23c6dc, 0xc52acbd7, 0xef15e8e6, 0xe11ce5ed,
  7648. 0xf307f2f0, 0xfd0efffb, 0xa779b492, 0xa970b999, 0xbb6bae84, 0xb562a38f,
  7649. 0x9f5d80be, 0x91548db5, 0x834f9aa8, 0x8d4697a3]);
  7650. function expandKey128(cipherKey) {
  7651. var b = 176, result = new Uint8Array(b);
  7652. result.set(cipherKey);
  7653. for (var j = 16, i = 1; j < b; ++i) {
  7654. // RotWord
  7655. var t1 = result[j - 3], t2 = result[j - 2],
  7656. t3 = result[j - 1], t4 = result[j - 4];
  7657. // SubWord
  7658. t1 = s[t1];
  7659. t2 = s[t2];
  7660. t3 = s[t3];
  7661. t4 = s[t4];
  7662. // Rcon
  7663. t1 = t1 ^ rcon[i];
  7664. for (var n = 0; n < 4; ++n) {
  7665. result[j] = (t1 ^= result[j - 16]);
  7666. j++;
  7667. result[j] = (t2 ^= result[j - 16]);
  7668. j++;
  7669. result[j] = (t3 ^= result[j - 16]);
  7670. j++;
  7671. result[j] = (t4 ^= result[j - 16]);
  7672. j++;
  7673. }
  7674. }
  7675. return result;
  7676. }
  7677. function decrypt128(input, key) {
  7678. var state = new Uint8Array(16);
  7679. state.set(input);
  7680. var i, j, k;
  7681. var t, u, v;
  7682. // AddRoundKey
  7683. for (j = 0, k = 160; j < 16; ++j, ++k) {
  7684. state[j] ^= key[k];
  7685. }
  7686. for (i = 9; i >= 1; --i) {
  7687. // InvShiftRows
  7688. t = state[13];
  7689. state[13] = state[9];
  7690. state[9] = state[5];
  7691. state[5] = state[1];
  7692. state[1] = t;
  7693. t = state[14];
  7694. u = state[10];
  7695. state[14] = state[6];
  7696. state[10] = state[2];
  7697. state[6] = t;
  7698. state[2] = u;
  7699. t = state[15];
  7700. u = state[11];
  7701. v = state[7];
  7702. state[15] = state[3];
  7703. state[11] = t;
  7704. state[7] = u;
  7705. state[3] = v;
  7706. // InvSubBytes
  7707. for (j = 0; j < 16; ++j) {
  7708. state[j] = inv_s[state[j]];
  7709. }
  7710. // AddRoundKey
  7711. for (j = 0, k = i * 16; j < 16; ++j, ++k) {
  7712. state[j] ^= key[k];
  7713. }
  7714. // InvMixColumns
  7715. for (j = 0; j < 16; j += 4) {
  7716. var s0 = mix[state[j]], s1 = mix[state[j + 1]],
  7717. s2 = mix[state[j + 2]], s3 = mix[state[j + 3]];
  7718. t = (s0 ^ (s1 >>> 8) ^ (s1 << 24) ^ (s2 >>> 16) ^ (s2 << 16) ^
  7719. (s3 >>> 24) ^ (s3 << 8));
  7720. state[j] = (t >>> 24) & 0xFF;
  7721. state[j + 1] = (t >> 16) & 0xFF;
  7722. state[j + 2] = (t >> 8) & 0xFF;
  7723. state[j + 3] = t & 0xFF;
  7724. }
  7725. }
  7726. // InvShiftRows
  7727. t = state[13];
  7728. state[13] = state[9];
  7729. state[9] = state[5];
  7730. state[5] = state[1];
  7731. state[1] = t;
  7732. t = state[14];
  7733. u = state[10];
  7734. state[14] = state[6];
  7735. state[10] = state[2];
  7736. state[6] = t;
  7737. state[2] = u;
  7738. t = state[15];
  7739. u = state[11];
  7740. v = state[7];
  7741. state[15] = state[3];
  7742. state[11] = t;
  7743. state[7] = u;
  7744. state[3] = v;
  7745. for (j = 0; j < 16; ++j) {
  7746. // InvSubBytes
  7747. state[j] = inv_s[state[j]];
  7748. // AddRoundKey
  7749. state[j] ^= key[j];
  7750. }
  7751. return state;
  7752. }
  7753. function encrypt128(input, key) {
  7754. var t, u, v, k;
  7755. var state = new Uint8Array(16);
  7756. state.set(input);
  7757. for (j = 0; j < 16; ++j) {
  7758. // AddRoundKey
  7759. state[j] ^= key[j];
  7760. }
  7761. for (i = 1; i < 10; i++) {
  7762. //SubBytes
  7763. for (j = 0; j < 16; ++j) {
  7764. state[j] = s[state[j]];
  7765. }
  7766. //ShiftRows
  7767. v = state[1];
  7768. state[1] = state[5];
  7769. state[5] = state[9];
  7770. state[9] = state[13];
  7771. state[13] = v;
  7772. v = state[2];
  7773. u = state[6];
  7774. state[2] = state[10];
  7775. state[6] = state[14];
  7776. state[10] = v;
  7777. state[14] = u;
  7778. v = state[3];
  7779. u = state[7];
  7780. t = state[11];
  7781. state[3] = state[15];
  7782. state[7] = v;
  7783. state[11] = u;
  7784. state[15] = t;
  7785. //MixColumns
  7786. for (var j = 0; j < 16; j += 4) {
  7787. var s0 = state[j + 0], s1 = state[j + 1];
  7788. var s2 = state[j + 2], s3 = state[j + 3];
  7789. t = s0 ^ s1 ^ s2 ^ s3;
  7790. state[j + 0] ^= t ^ mixCol[s0 ^ s1];
  7791. state[j + 1] ^= t ^ mixCol[s1 ^ s2];
  7792. state[j + 2] ^= t ^ mixCol[s2 ^ s3];
  7793. state[j + 3] ^= t ^ mixCol[s3 ^ s0];
  7794. }
  7795. //AddRoundKey
  7796. for (j = 0, k = i * 16; j < 16; ++j, ++k) {
  7797. state[j] ^= key[k];
  7798. }
  7799. }
  7800. //SubBytes
  7801. for (j = 0; j < 16; ++j) {
  7802. state[j] = s[state[j]];
  7803. }
  7804. //ShiftRows
  7805. v = state[1];
  7806. state[1] = state[5];
  7807. state[5] = state[9];
  7808. state[9] = state[13];
  7809. state[13] = v;
  7810. v = state[2];
  7811. u = state[6];
  7812. state[2] = state[10];
  7813. state[6] = state[14];
  7814. state[10] = v;
  7815. state[14] = u;
  7816. v = state[3];
  7817. u = state[7];
  7818. t = state[11];
  7819. state[3] = state[15];
  7820. state[7] = v;
  7821. state[11] = u;
  7822. state[15] = t;
  7823. //AddRoundKey
  7824. for (j = 0, k = 160; j < 16; ++j, ++k) {
  7825. state[j] ^= key[k];
  7826. }
  7827. return state;
  7828. }
  7829. function AES128Cipher(key) {
  7830. this.key = expandKey128(key);
  7831. this.buffer = new Uint8Array(16);
  7832. this.bufferPosition = 0;
  7833. }
  7834. function decryptBlock2(data, finalize) {
  7835. var i, j, ii, sourceLength = data.length,
  7836. buffer = this.buffer, bufferLength = this.bufferPosition,
  7837. result = [], iv = this.iv;
  7838. for (i = 0; i < sourceLength; ++i) {
  7839. buffer[bufferLength] = data[i];
  7840. ++bufferLength;
  7841. if (bufferLength < 16) {
  7842. continue;
  7843. }
  7844. // buffer is full, decrypting
  7845. var plain = decrypt128(buffer, this.key);
  7846. // xor-ing the IV vector to get plain text
  7847. for (j = 0; j < 16; ++j) {
  7848. plain[j] ^= iv[j];
  7849. }
  7850. iv = buffer;
  7851. result.push(plain);
  7852. buffer = new Uint8Array(16);
  7853. bufferLength = 0;
  7854. }
  7855. // saving incomplete buffer
  7856. this.buffer = buffer;
  7857. this.bufferLength = bufferLength;
  7858. this.iv = iv;
  7859. if (result.length === 0) {
  7860. return new Uint8Array([]);
  7861. }
  7862. // combining plain text blocks into one
  7863. var outputLength = 16 * result.length;
  7864. if (finalize) {
  7865. // undo a padding that is described in RFC 2898
  7866. var lastBlock = result[result.length - 1];
  7867. var psLen = lastBlock[15];
  7868. if (psLen <= 16) {
  7869. for (i = 15, ii = 16 - psLen; i >= ii; --i) {
  7870. if (lastBlock[i] !== psLen) {
  7871. // Invalid padding, assume that the block has no padding.
  7872. psLen = 0;
  7873. break;
  7874. }
  7875. }
  7876. outputLength -= psLen;
  7877. result[result.length - 1] = lastBlock.subarray(0, 16 - psLen);
  7878. }
  7879. }
  7880. var output = new Uint8Array(outputLength);
  7881. for (i = 0, j = 0, ii = result.length; i < ii; ++i, j += 16) {
  7882. output.set(result[i], j);
  7883. }
  7884. return output;
  7885. }
  7886. AES128Cipher.prototype = {
  7887. decryptBlock: function AES128Cipher_decryptBlock(data, finalize) {
  7888. var i, sourceLength = data.length;
  7889. var buffer = this.buffer, bufferLength = this.bufferPosition;
  7890. // waiting for IV values -- they are at the start of the stream
  7891. for (i = 0; bufferLength < 16 && i < sourceLength; ++i, ++bufferLength) {
  7892. buffer[bufferLength] = data[i];
  7893. }
  7894. if (bufferLength < 16) {
  7895. // need more data
  7896. this.bufferLength = bufferLength;
  7897. return new Uint8Array([]);
  7898. }
  7899. this.iv = buffer;
  7900. this.buffer = new Uint8Array(16);
  7901. this.bufferLength = 0;
  7902. // starting decryption
  7903. this.decryptBlock = decryptBlock2;
  7904. return this.decryptBlock(data.subarray(16), finalize);
  7905. },
  7906. encrypt: function AES128Cipher_encrypt(data, iv) {
  7907. var i, j, ii, sourceLength = data.length,
  7908. buffer = this.buffer, bufferLength = this.bufferPosition,
  7909. result = [];
  7910. if (!iv) {
  7911. iv = new Uint8Array(16);
  7912. }
  7913. for (i = 0; i < sourceLength; ++i) {
  7914. buffer[bufferLength] = data[i];
  7915. ++bufferLength;
  7916. if (bufferLength < 16) {
  7917. continue;
  7918. }
  7919. for (j = 0; j < 16; ++j) {
  7920. buffer[j] ^= iv[j];
  7921. }
  7922. // buffer is full, encrypting
  7923. var cipher = encrypt128(buffer, this.key);
  7924. iv = cipher;
  7925. result.push(cipher);
  7926. buffer = new Uint8Array(16);
  7927. bufferLength = 0;
  7928. }
  7929. // saving incomplete buffer
  7930. this.buffer = buffer;
  7931. this.bufferLength = bufferLength;
  7932. this.iv = iv;
  7933. if (result.length === 0) {
  7934. return new Uint8Array([]);
  7935. }
  7936. // combining plain text blocks into one
  7937. var outputLength = 16 * result.length;
  7938. var output = new Uint8Array(outputLength);
  7939. for (i = 0, j = 0, ii = result.length; i < ii; ++i, j += 16) {
  7940. output.set(result[i], j);
  7941. }
  7942. return output;
  7943. }
  7944. };
  7945. return AES128Cipher;
  7946. })();
  7947. var AES256Cipher = (function AES256CipherClosure() {
  7948. var rcon = new Uint8Array([
  7949. 0x8d, 0x01, 0x02, 0x04, 0x08, 0x10, 0x20, 0x40, 0x80, 0x1b, 0x36, 0x6c,
  7950. 0xd8, 0xab, 0x4d, 0x9a, 0x2f, 0x5e, 0xbc, 0x63, 0xc6, 0x97, 0x35, 0x6a,
  7951. 0xd4, 0xb3, 0x7d, 0xfa, 0xef, 0xc5, 0x91, 0x39, 0x72, 0xe4, 0xd3, 0xbd,
  7952. 0x61, 0xc2, 0x9f, 0x25, 0x4a, 0x94, 0x33, 0x66, 0xcc, 0x83, 0x1d, 0x3a,
  7953. 0x74, 0xe8, 0xcb, 0x8d, 0x01, 0x02, 0x04, 0x08, 0x10, 0x20, 0x40, 0x80,
  7954. 0x1b, 0x36, 0x6c, 0xd8, 0xab, 0x4d, 0x9a, 0x2f, 0x5e, 0xbc, 0x63, 0xc6,
  7955. 0x97, 0x35, 0x6a, 0xd4, 0xb3, 0x7d, 0xfa, 0xef, 0xc5, 0x91, 0x39, 0x72,
  7956. 0xe4, 0xd3, 0xbd, 0x61, 0xc2, 0x9f, 0x25, 0x4a, 0x94, 0x33, 0x66, 0xcc,
  7957. 0x83, 0x1d, 0x3a, 0x74, 0xe8, 0xcb, 0x8d, 0x01, 0x02, 0x04, 0x08, 0x10,
  7958. 0x20, 0x40, 0x80, 0x1b, 0x36, 0x6c, 0xd8, 0xab, 0x4d, 0x9a, 0x2f, 0x5e,
  7959. 0xbc, 0x63, 0xc6, 0x97, 0x35, 0x6a, 0xd4, 0xb3, 0x7d, 0xfa, 0xef, 0xc5,
  7960. 0x91, 0x39, 0x72, 0xe4, 0xd3, 0xbd, 0x61, 0xc2, 0x9f, 0x25, 0x4a, 0x94,
  7961. 0x33, 0x66, 0xcc, 0x83, 0x1d, 0x3a, 0x74, 0xe8, 0xcb, 0x8d, 0x01, 0x02,
  7962. 0x04, 0x08, 0x10, 0x20, 0x40, 0x80, 0x1b, 0x36, 0x6c, 0xd8, 0xab, 0x4d,
  7963. 0x9a, 0x2f, 0x5e, 0xbc, 0x63, 0xc6, 0x97, 0x35, 0x6a, 0xd4, 0xb3, 0x7d,
  7964. 0xfa, 0xef, 0xc5, 0x91, 0x39, 0x72, 0xe4, 0xd3, 0xbd, 0x61, 0xc2, 0x9f,
  7965. 0x25, 0x4a, 0x94, 0x33, 0x66, 0xcc, 0x83, 0x1d, 0x3a, 0x74, 0xe8, 0xcb,
  7966. 0x8d, 0x01, 0x02, 0x04, 0x08, 0x10, 0x20, 0x40, 0x80, 0x1b, 0x36, 0x6c,
  7967. 0xd8, 0xab, 0x4d, 0x9a, 0x2f, 0x5e, 0xbc, 0x63, 0xc6, 0x97, 0x35, 0x6a,
  7968. 0xd4, 0xb3, 0x7d, 0xfa, 0xef, 0xc5, 0x91, 0x39, 0x72, 0xe4, 0xd3, 0xbd,
  7969. 0x61, 0xc2, 0x9f, 0x25, 0x4a, 0x94, 0x33, 0x66, 0xcc, 0x83, 0x1d, 0x3a,
  7970. 0x74, 0xe8, 0xcb, 0x8d]);
  7971. var s = new Uint8Array([
  7972. 0x63, 0x7c, 0x77, 0x7b, 0xf2, 0x6b, 0x6f, 0xc5, 0x30, 0x01, 0x67, 0x2b,
  7973. 0xfe, 0xd7, 0xab, 0x76, 0xca, 0x82, 0xc9, 0x7d, 0xfa, 0x59, 0x47, 0xf0,
  7974. 0xad, 0xd4, 0xa2, 0xaf, 0x9c, 0xa4, 0x72, 0xc0, 0xb7, 0xfd, 0x93, 0x26,
  7975. 0x36, 0x3f, 0xf7, 0xcc, 0x34, 0xa5, 0xe5, 0xf1, 0x71, 0xd8, 0x31, 0x15,
  7976. 0x04, 0xc7, 0x23, 0xc3, 0x18, 0x96, 0x05, 0x9a, 0x07, 0x12, 0x80, 0xe2,
  7977. 0xeb, 0x27, 0xb2, 0x75, 0x09, 0x83, 0x2c, 0x1a, 0x1b, 0x6e, 0x5a, 0xa0,
  7978. 0x52, 0x3b, 0xd6, 0xb3, 0x29, 0xe3, 0x2f, 0x84, 0x53, 0xd1, 0x00, 0xed,
  7979. 0x20, 0xfc, 0xb1, 0x5b, 0x6a, 0xcb, 0xbe, 0x39, 0x4a, 0x4c, 0x58, 0xcf,
  7980. 0xd0, 0xef, 0xaa, 0xfb, 0x43, 0x4d, 0x33, 0x85, 0x45, 0xf9, 0x02, 0x7f,
  7981. 0x50, 0x3c, 0x9f, 0xa8, 0x51, 0xa3, 0x40, 0x8f, 0x92, 0x9d, 0x38, 0xf5,
  7982. 0xbc, 0xb6, 0xda, 0x21, 0x10, 0xff, 0xf3, 0xd2, 0xcd, 0x0c, 0x13, 0xec,
  7983. 0x5f, 0x97, 0x44, 0x17, 0xc4, 0xa7, 0x7e, 0x3d, 0x64, 0x5d, 0x19, 0x73,
  7984. 0x60, 0x81, 0x4f, 0xdc, 0x22, 0x2a, 0x90, 0x88, 0x46, 0xee, 0xb8, 0x14,
  7985. 0xde, 0x5e, 0x0b, 0xdb, 0xe0, 0x32, 0x3a, 0x0a, 0x49, 0x06, 0x24, 0x5c,
  7986. 0xc2, 0xd3, 0xac, 0x62, 0x91, 0x95, 0xe4, 0x79, 0xe7, 0xc8, 0x37, 0x6d,
  7987. 0x8d, 0xd5, 0x4e, 0xa9, 0x6c, 0x56, 0xf4, 0xea, 0x65, 0x7a, 0xae, 0x08,
  7988. 0xba, 0x78, 0x25, 0x2e, 0x1c, 0xa6, 0xb4, 0xc6, 0xe8, 0xdd, 0x74, 0x1f,
  7989. 0x4b, 0xbd, 0x8b, 0x8a, 0x70, 0x3e, 0xb5, 0x66, 0x48, 0x03, 0xf6, 0x0e,
  7990. 0x61, 0x35, 0x57, 0xb9, 0x86, 0xc1, 0x1d, 0x9e, 0xe1, 0xf8, 0x98, 0x11,
  7991. 0x69, 0xd9, 0x8e, 0x94, 0x9b, 0x1e, 0x87, 0xe9, 0xce, 0x55, 0x28, 0xdf,
  7992. 0x8c, 0xa1, 0x89, 0x0d, 0xbf, 0xe6, 0x42, 0x68, 0x41, 0x99, 0x2d, 0x0f,
  7993. 0xb0, 0x54, 0xbb, 0x16]);
  7994. var inv_s = new Uint8Array([
  7995. 0x52, 0x09, 0x6a, 0xd5, 0x30, 0x36, 0xa5, 0x38, 0xbf, 0x40, 0xa3, 0x9e,
  7996. 0x81, 0xf3, 0xd7, 0xfb, 0x7c, 0xe3, 0x39, 0x82, 0x9b, 0x2f, 0xff, 0x87,
  7997. 0x34, 0x8e, 0x43, 0x44, 0xc4, 0xde, 0xe9, 0xcb, 0x54, 0x7b, 0x94, 0x32,
  7998. 0xa6, 0xc2, 0x23, 0x3d, 0xee, 0x4c, 0x95, 0x0b, 0x42, 0xfa, 0xc3, 0x4e,
  7999. 0x08, 0x2e, 0xa1, 0x66, 0x28, 0xd9, 0x24, 0xb2, 0x76, 0x5b, 0xa2, 0x49,
  8000. 0x6d, 0x8b, 0xd1, 0x25, 0x72, 0xf8, 0xf6, 0x64, 0x86, 0x68, 0x98, 0x16,
  8001. 0xd4, 0xa4, 0x5c, 0xcc, 0x5d, 0x65, 0xb6, 0x92, 0x6c, 0x70, 0x48, 0x50,
  8002. 0xfd, 0xed, 0xb9, 0xda, 0x5e, 0x15, 0x46, 0x57, 0xa7, 0x8d, 0x9d, 0x84,
  8003. 0x90, 0xd8, 0xab, 0x00, 0x8c, 0xbc, 0xd3, 0x0a, 0xf7, 0xe4, 0x58, 0x05,
  8004. 0xb8, 0xb3, 0x45, 0x06, 0xd0, 0x2c, 0x1e, 0x8f, 0xca, 0x3f, 0x0f, 0x02,
  8005. 0xc1, 0xaf, 0xbd, 0x03, 0x01, 0x13, 0x8a, 0x6b, 0x3a, 0x91, 0x11, 0x41,
  8006. 0x4f, 0x67, 0xdc, 0xea, 0x97, 0xf2, 0xcf, 0xce, 0xf0, 0xb4, 0xe6, 0x73,
  8007. 0x96, 0xac, 0x74, 0x22, 0xe7, 0xad, 0x35, 0x85, 0xe2, 0xf9, 0x37, 0xe8,
  8008. 0x1c, 0x75, 0xdf, 0x6e, 0x47, 0xf1, 0x1a, 0x71, 0x1d, 0x29, 0xc5, 0x89,
  8009. 0x6f, 0xb7, 0x62, 0x0e, 0xaa, 0x18, 0xbe, 0x1b, 0xfc, 0x56, 0x3e, 0x4b,
  8010. 0xc6, 0xd2, 0x79, 0x20, 0x9a, 0xdb, 0xc0, 0xfe, 0x78, 0xcd, 0x5a, 0xf4,
  8011. 0x1f, 0xdd, 0xa8, 0x33, 0x88, 0x07, 0xc7, 0x31, 0xb1, 0x12, 0x10, 0x59,
  8012. 0x27, 0x80, 0xec, 0x5f, 0x60, 0x51, 0x7f, 0xa9, 0x19, 0xb5, 0x4a, 0x0d,
  8013. 0x2d, 0xe5, 0x7a, 0x9f, 0x93, 0xc9, 0x9c, 0xef, 0xa0, 0xe0, 0x3b, 0x4d,
  8014. 0xae, 0x2a, 0xf5, 0xb0, 0xc8, 0xeb, 0xbb, 0x3c, 0x83, 0x53, 0x99, 0x61,
  8015. 0x17, 0x2b, 0x04, 0x7e, 0xba, 0x77, 0xd6, 0x26, 0xe1, 0x69, 0x14, 0x63,
  8016. 0x55, 0x21, 0x0c, 0x7d]);
  8017. var mixCol = new Uint8Array(256);
  8018. for (var i = 0; i < 256; i++) {
  8019. if (i < 128) {
  8020. mixCol[i] = i << 1;
  8021. } else {
  8022. mixCol[i] = (i << 1) ^ 0x1b;
  8023. }
  8024. }
  8025. var mix = new Uint32Array([
  8026. 0x00000000, 0x0e090d0b, 0x1c121a16, 0x121b171d, 0x3824342c, 0x362d3927,
  8027. 0x24362e3a, 0x2a3f2331, 0x70486858, 0x7e416553, 0x6c5a724e, 0x62537f45,
  8028. 0x486c5c74, 0x4665517f, 0x547e4662, 0x5a774b69, 0xe090d0b0, 0xee99ddbb,
  8029. 0xfc82caa6, 0xf28bc7ad, 0xd8b4e49c, 0xd6bde997, 0xc4a6fe8a, 0xcaaff381,
  8030. 0x90d8b8e8, 0x9ed1b5e3, 0x8ccaa2fe, 0x82c3aff5, 0xa8fc8cc4, 0xa6f581cf,
  8031. 0xb4ee96d2, 0xbae79bd9, 0xdb3bbb7b, 0xd532b670, 0xc729a16d, 0xc920ac66,
  8032. 0xe31f8f57, 0xed16825c, 0xff0d9541, 0xf104984a, 0xab73d323, 0xa57ade28,
  8033. 0xb761c935, 0xb968c43e, 0x9357e70f, 0x9d5eea04, 0x8f45fd19, 0x814cf012,
  8034. 0x3bab6bcb, 0x35a266c0, 0x27b971dd, 0x29b07cd6, 0x038f5fe7, 0x0d8652ec,
  8035. 0x1f9d45f1, 0x119448fa, 0x4be30393, 0x45ea0e98, 0x57f11985, 0x59f8148e,
  8036. 0x73c737bf, 0x7dce3ab4, 0x6fd52da9, 0x61dc20a2, 0xad766df6, 0xa37f60fd,
  8037. 0xb16477e0, 0xbf6d7aeb, 0x955259da, 0x9b5b54d1, 0x894043cc, 0x87494ec7,
  8038. 0xdd3e05ae, 0xd33708a5, 0xc12c1fb8, 0xcf2512b3, 0xe51a3182, 0xeb133c89,
  8039. 0xf9082b94, 0xf701269f, 0x4de6bd46, 0x43efb04d, 0x51f4a750, 0x5ffdaa5b,
  8040. 0x75c2896a, 0x7bcb8461, 0x69d0937c, 0x67d99e77, 0x3daed51e, 0x33a7d815,
  8041. 0x21bccf08, 0x2fb5c203, 0x058ae132, 0x0b83ec39, 0x1998fb24, 0x1791f62f,
  8042. 0x764dd68d, 0x7844db86, 0x6a5fcc9b, 0x6456c190, 0x4e69e2a1, 0x4060efaa,
  8043. 0x527bf8b7, 0x5c72f5bc, 0x0605bed5, 0x080cb3de, 0x1a17a4c3, 0x141ea9c8,
  8044. 0x3e218af9, 0x302887f2, 0x223390ef, 0x2c3a9de4, 0x96dd063d, 0x98d40b36,
  8045. 0x8acf1c2b, 0x84c61120, 0xaef93211, 0xa0f03f1a, 0xb2eb2807, 0xbce2250c,
  8046. 0xe6956e65, 0xe89c636e, 0xfa877473, 0xf48e7978, 0xdeb15a49, 0xd0b85742,
  8047. 0xc2a3405f, 0xccaa4d54, 0x41ecdaf7, 0x4fe5d7fc, 0x5dfec0e1, 0x53f7cdea,
  8048. 0x79c8eedb, 0x77c1e3d0, 0x65daf4cd, 0x6bd3f9c6, 0x31a4b2af, 0x3fadbfa4,
  8049. 0x2db6a8b9, 0x23bfa5b2, 0x09808683, 0x07898b88, 0x15929c95, 0x1b9b919e,
  8050. 0xa17c0a47, 0xaf75074c, 0xbd6e1051, 0xb3671d5a, 0x99583e6b, 0x97513360,
  8051. 0x854a247d, 0x8b432976, 0xd134621f, 0xdf3d6f14, 0xcd267809, 0xc32f7502,
  8052. 0xe9105633, 0xe7195b38, 0xf5024c25, 0xfb0b412e, 0x9ad7618c, 0x94de6c87,
  8053. 0x86c57b9a, 0x88cc7691, 0xa2f355a0, 0xacfa58ab, 0xbee14fb6, 0xb0e842bd,
  8054. 0xea9f09d4, 0xe49604df, 0xf68d13c2, 0xf8841ec9, 0xd2bb3df8, 0xdcb230f3,
  8055. 0xcea927ee, 0xc0a02ae5, 0x7a47b13c, 0x744ebc37, 0x6655ab2a, 0x685ca621,
  8056. 0x42638510, 0x4c6a881b, 0x5e719f06, 0x5078920d, 0x0a0fd964, 0x0406d46f,
  8057. 0x161dc372, 0x1814ce79, 0x322bed48, 0x3c22e043, 0x2e39f75e, 0x2030fa55,
  8058. 0xec9ab701, 0xe293ba0a, 0xf088ad17, 0xfe81a01c, 0xd4be832d, 0xdab78e26,
  8059. 0xc8ac993b, 0xc6a59430, 0x9cd2df59, 0x92dbd252, 0x80c0c54f, 0x8ec9c844,
  8060. 0xa4f6eb75, 0xaaffe67e, 0xb8e4f163, 0xb6edfc68, 0x0c0a67b1, 0x02036aba,
  8061. 0x10187da7, 0x1e1170ac, 0x342e539d, 0x3a275e96, 0x283c498b, 0x26354480,
  8062. 0x7c420fe9, 0x724b02e2, 0x605015ff, 0x6e5918f4, 0x44663bc5, 0x4a6f36ce,
  8063. 0x587421d3, 0x567d2cd8, 0x37a10c7a, 0x39a80171, 0x2bb3166c, 0x25ba1b67,
  8064. 0x0f853856, 0x018c355d, 0x13972240, 0x1d9e2f4b, 0x47e96422, 0x49e06929,
  8065. 0x5bfb7e34, 0x55f2733f, 0x7fcd500e, 0x71c45d05, 0x63df4a18, 0x6dd64713,
  8066. 0xd731dcca, 0xd938d1c1, 0xcb23c6dc, 0xc52acbd7, 0xef15e8e6, 0xe11ce5ed,
  8067. 0xf307f2f0, 0xfd0efffb, 0xa779b492, 0xa970b999, 0xbb6bae84, 0xb562a38f,
  8068. 0x9f5d80be, 0x91548db5, 0x834f9aa8, 0x8d4697a3]);
  8069. function expandKey256(cipherKey) {
  8070. var b = 240, result = new Uint8Array(b);
  8071. var r = 1;
  8072. result.set(cipherKey);
  8073. for (var j = 32, i = 1; j < b; ++i) {
  8074. if (j % 32 === 16) {
  8075. t1 = s[t1];
  8076. t2 = s[t2];
  8077. t3 = s[t3];
  8078. t4 = s[t4];
  8079. } else if (j % 32 === 0) {
  8080. // RotWord
  8081. var t1 = result[j - 3], t2 = result[j - 2],
  8082. t3 = result[j - 1], t4 = result[j - 4];
  8083. // SubWord
  8084. t1 = s[t1];
  8085. t2 = s[t2];
  8086. t3 = s[t3];
  8087. t4 = s[t4];
  8088. // Rcon
  8089. t1 = t1 ^ r;
  8090. if ((r <<= 1) >= 256) {
  8091. r = (r ^ 0x1b) & 0xFF;
  8092. }
  8093. }
  8094. for (var n = 0; n < 4; ++n) {
  8095. result[j] = (t1 ^= result[j - 32]);
  8096. j++;
  8097. result[j] = (t2 ^= result[j - 32]);
  8098. j++;
  8099. result[j] = (t3 ^= result[j - 32]);
  8100. j++;
  8101. result[j] = (t4 ^= result[j - 32]);
  8102. j++;
  8103. }
  8104. }
  8105. return result;
  8106. }
  8107. function decrypt256(input, key) {
  8108. var state = new Uint8Array(16);
  8109. state.set(input);
  8110. var i, j, k;
  8111. var t, u, v;
  8112. // AddRoundKey
  8113. for (j = 0, k = 224; j < 16; ++j, ++k) {
  8114. state[j] ^= key[k];
  8115. }
  8116. for (i = 13; i >= 1; --i) {
  8117. // InvShiftRows
  8118. t = state[13];
  8119. state[13] = state[9];
  8120. state[9] = state[5];
  8121. state[5] = state[1];
  8122. state[1] = t;
  8123. t = state[14];
  8124. u = state[10];
  8125. state[14] = state[6];
  8126. state[10] = state[2];
  8127. state[6] = t;
  8128. state[2] = u;
  8129. t = state[15];
  8130. u = state[11];
  8131. v = state[7];
  8132. state[15] = state[3];
  8133. state[11] = t;
  8134. state[7] = u;
  8135. state[3] = v;
  8136. // InvSubBytes
  8137. for (j = 0; j < 16; ++j) {
  8138. state[j] = inv_s[state[j]];
  8139. }
  8140. // AddRoundKey
  8141. for (j = 0, k = i * 16; j < 16; ++j, ++k) {
  8142. state[j] ^= key[k];
  8143. }
  8144. // InvMixColumns
  8145. for (j = 0; j < 16; j += 4) {
  8146. var s0 = mix[state[j]], s1 = mix[state[j + 1]],
  8147. s2 = mix[state[j + 2]], s3 = mix[state[j + 3]];
  8148. t = (s0 ^ (s1 >>> 8) ^ (s1 << 24) ^ (s2 >>> 16) ^ (s2 << 16) ^
  8149. (s3 >>> 24) ^ (s3 << 8));
  8150. state[j] = (t >>> 24) & 0xFF;
  8151. state[j + 1] = (t >> 16) & 0xFF;
  8152. state[j + 2] = (t >> 8) & 0xFF;
  8153. state[j + 3] = t & 0xFF;
  8154. }
  8155. }
  8156. // InvShiftRows
  8157. t = state[13];
  8158. state[13] = state[9];
  8159. state[9] = state[5];
  8160. state[5] = state[1];
  8161. state[1] = t;
  8162. t = state[14];
  8163. u = state[10];
  8164. state[14] = state[6];
  8165. state[10] = state[2];
  8166. state[6] = t;
  8167. state[2] = u;
  8168. t = state[15];
  8169. u = state[11];
  8170. v = state[7];
  8171. state[15] = state[3];
  8172. state[11] = t;
  8173. state[7] = u;
  8174. state[3] = v;
  8175. for (j = 0; j < 16; ++j) {
  8176. // InvSubBytes
  8177. state[j] = inv_s[state[j]];
  8178. // AddRoundKey
  8179. state[j] ^= key[j];
  8180. }
  8181. return state;
  8182. }
  8183. function encrypt256(input, key) {
  8184. var t, u, v, k;
  8185. var state = new Uint8Array(16);
  8186. state.set(input);
  8187. for (j = 0; j < 16; ++j) {
  8188. // AddRoundKey
  8189. state[j] ^= key[j];
  8190. }
  8191. for (i = 1; i < 14; i++) {
  8192. //SubBytes
  8193. for (j = 0; j < 16; ++j) {
  8194. state[j] = s[state[j]];
  8195. }
  8196. //ShiftRows
  8197. v = state[1];
  8198. state[1] = state[5];
  8199. state[5] = state[9];
  8200. state[9] = state[13];
  8201. state[13] = v;
  8202. v = state[2];
  8203. u = state[6];
  8204. state[2] = state[10];
  8205. state[6] = state[14];
  8206. state[10] = v;
  8207. state[14] = u;
  8208. v = state[3];
  8209. u = state[7];
  8210. t = state[11];
  8211. state[3] = state[15];
  8212. state[7] = v;
  8213. state[11] = u;
  8214. state[15] = t;
  8215. //MixColumns
  8216. for (var j = 0; j < 16; j += 4) {
  8217. var s0 = state[j + 0], s1 = state[j + 1];
  8218. var s2 = state[j + 2], s3 = state[j + 3];
  8219. t = s0 ^ s1 ^ s2 ^ s3;
  8220. state[j + 0] ^= t ^ mixCol[s0 ^ s1];
  8221. state[j + 1] ^= t ^ mixCol[s1 ^ s2];
  8222. state[j + 2] ^= t ^ mixCol[s2 ^ s3];
  8223. state[j + 3] ^= t ^ mixCol[s3 ^ s0];
  8224. }
  8225. //AddRoundKey
  8226. for (j = 0, k = i * 16; j < 16; ++j, ++k) {
  8227. state[j] ^= key[k];
  8228. }
  8229. }
  8230. //SubBytes
  8231. for (j = 0; j < 16; ++j) {
  8232. state[j] = s[state[j]];
  8233. }
  8234. //ShiftRows
  8235. v = state[1];
  8236. state[1] = state[5];
  8237. state[5] = state[9];
  8238. state[9] = state[13];
  8239. state[13] = v;
  8240. v = state[2];
  8241. u = state[6];
  8242. state[2] = state[10];
  8243. state[6] = state[14];
  8244. state[10] = v;
  8245. state[14] = u;
  8246. v = state[3];
  8247. u = state[7];
  8248. t = state[11];
  8249. state[3] = state[15];
  8250. state[7] = v;
  8251. state[11] = u;
  8252. state[15] = t;
  8253. //AddRoundKey
  8254. for (j = 0, k = 224; j < 16; ++j, ++k) {
  8255. state[j] ^= key[k];
  8256. }
  8257. return state;
  8258. }
  8259. function AES256Cipher(key) {
  8260. this.key = expandKey256(key);
  8261. this.buffer = new Uint8Array(16);
  8262. this.bufferPosition = 0;
  8263. }
  8264. function decryptBlock2(data, finalize) {
  8265. var i, j, ii, sourceLength = data.length,
  8266. buffer = this.buffer, bufferLength = this.bufferPosition,
  8267. result = [], iv = this.iv;
  8268. for (i = 0; i < sourceLength; ++i) {
  8269. buffer[bufferLength] = data[i];
  8270. ++bufferLength;
  8271. if (bufferLength < 16) {
  8272. continue;
  8273. }
  8274. // buffer is full, decrypting
  8275. var plain = decrypt256(buffer, this.key);
  8276. // xor-ing the IV vector to get plain text
  8277. for (j = 0; j < 16; ++j) {
  8278. plain[j] ^= iv[j];
  8279. }
  8280. iv = buffer;
  8281. result.push(plain);
  8282. buffer = new Uint8Array(16);
  8283. bufferLength = 0;
  8284. }
  8285. // saving incomplete buffer
  8286. this.buffer = buffer;
  8287. this.bufferLength = bufferLength;
  8288. this.iv = iv;
  8289. if (result.length === 0) {
  8290. return new Uint8Array([]);
  8291. }
  8292. // combining plain text blocks into one
  8293. var outputLength = 16 * result.length;
  8294. if (finalize) {
  8295. // undo a padding that is described in RFC 2898
  8296. var lastBlock = result[result.length - 1];
  8297. var psLen = lastBlock[15];
  8298. if (psLen <= 16) {
  8299. for (i = 15, ii = 16 - psLen; i >= ii; --i) {
  8300. if (lastBlock[i] !== psLen) {
  8301. // Invalid padding, assume that the block has no padding.
  8302. psLen = 0;
  8303. break;
  8304. }
  8305. }
  8306. outputLength -= psLen;
  8307. result[result.length - 1] = lastBlock.subarray(0, 16 - psLen);
  8308. }
  8309. }
  8310. var output = new Uint8Array(outputLength);
  8311. for (i = 0, j = 0, ii = result.length; i < ii; ++i, j += 16) {
  8312. output.set(result[i], j);
  8313. }
  8314. return output;
  8315. }
  8316. AES256Cipher.prototype = {
  8317. decryptBlock: function AES256Cipher_decryptBlock(data, finalize, iv) {
  8318. var i, sourceLength = data.length;
  8319. var buffer = this.buffer, bufferLength = this.bufferPosition;
  8320. // if not supplied an IV wait for IV values
  8321. // they are at the start of the stream
  8322. if (iv) {
  8323. this.iv = iv;
  8324. } else {
  8325. for (i = 0; bufferLength < 16 &&
  8326. i < sourceLength; ++i, ++bufferLength) {
  8327. buffer[bufferLength] = data[i];
  8328. }
  8329. if (bufferLength < 16) {
  8330. //need more data
  8331. this.bufferLength = bufferLength;
  8332. return new Uint8Array([]);
  8333. }
  8334. this.iv = buffer;
  8335. data = data.subarray(16);
  8336. }
  8337. this.buffer = new Uint8Array(16);
  8338. this.bufferLength = 0;
  8339. // starting decryption
  8340. this.decryptBlock = decryptBlock2;
  8341. return this.decryptBlock(data, finalize);
  8342. },
  8343. encrypt: function AES256Cipher_encrypt(data, iv) {
  8344. var i, j, ii, sourceLength = data.length,
  8345. buffer = this.buffer, bufferLength = this.bufferPosition,
  8346. result = [];
  8347. if (!iv) {
  8348. iv = new Uint8Array(16);
  8349. }
  8350. for (i = 0; i < sourceLength; ++i) {
  8351. buffer[bufferLength] = data[i];
  8352. ++bufferLength;
  8353. if (bufferLength < 16) {
  8354. continue;
  8355. }
  8356. for (j = 0; j < 16; ++j) {
  8357. buffer[j] ^= iv[j];
  8358. }
  8359. // buffer is full, encrypting
  8360. var cipher = encrypt256(buffer, this.key);
  8361. this.iv = cipher;
  8362. result.push(cipher);
  8363. buffer = new Uint8Array(16);
  8364. bufferLength = 0;
  8365. }
  8366. // saving incomplete buffer
  8367. this.buffer = buffer;
  8368. this.bufferLength = bufferLength;
  8369. this.iv = iv;
  8370. if (result.length === 0) {
  8371. return new Uint8Array([]);
  8372. }
  8373. // combining plain text blocks into one
  8374. var outputLength = 16 * result.length;
  8375. var output = new Uint8Array(outputLength);
  8376. for (i = 0, j = 0, ii = result.length; i < ii; ++i, j += 16) {
  8377. output.set(result[i], j);
  8378. }
  8379. return output;
  8380. }
  8381. };
  8382. return AES256Cipher;
  8383. })();
  8384. var PDF17 = (function PDF17Closure() {
  8385. function compareByteArrays(array1, array2) {
  8386. if (array1.length !== array2.length) {
  8387. return false;
  8388. }
  8389. for (var i = 0; i < array1.length; i++) {
  8390. if (array1[i] !== array2[i]) {
  8391. return false;
  8392. }
  8393. }
  8394. return true;
  8395. }
  8396. function PDF17() {
  8397. }
  8398. PDF17.prototype = {
  8399. checkOwnerPassword: function PDF17_checkOwnerPassword(password,
  8400. ownerValidationSalt,
  8401. userBytes,
  8402. ownerPassword) {
  8403. var hashData = new Uint8Array(password.length + 56);
  8404. hashData.set(password, 0);
  8405. hashData.set(ownerValidationSalt, password.length);
  8406. hashData.set(userBytes, password.length + ownerValidationSalt.length);
  8407. var result = calculateSHA256(hashData, 0, hashData.length);
  8408. return compareByteArrays(result, ownerPassword);
  8409. },
  8410. checkUserPassword: function PDF17_checkUserPassword(password,
  8411. userValidationSalt,
  8412. userPassword) {
  8413. var hashData = new Uint8Array(password.length + 8);
  8414. hashData.set(password, 0);
  8415. hashData.set(userValidationSalt, password.length);
  8416. var result = calculateSHA256(hashData, 0, hashData.length);
  8417. return compareByteArrays(result, userPassword);
  8418. },
  8419. getOwnerKey: function PDF17_getOwnerKey(password, ownerKeySalt, userBytes,
  8420. ownerEncryption) {
  8421. var hashData = new Uint8Array(password.length + 56);
  8422. hashData.set(password, 0);
  8423. hashData.set(ownerKeySalt, password.length);
  8424. hashData.set(userBytes, password.length + ownerKeySalt.length);
  8425. var key = calculateSHA256(hashData, 0, hashData.length);
  8426. var cipher = new AES256Cipher(key);
  8427. return cipher.decryptBlock(ownerEncryption,
  8428. false,
  8429. new Uint8Array(16));
  8430. },
  8431. getUserKey: function PDF17_getUserKey(password, userKeySalt,
  8432. userEncryption) {
  8433. var hashData = new Uint8Array(password.length + 8);
  8434. hashData.set(password, 0);
  8435. hashData.set(userKeySalt, password.length);
  8436. //key is the decryption key for the UE string
  8437. var key = calculateSHA256(hashData, 0, hashData.length);
  8438. var cipher = new AES256Cipher(key);
  8439. return cipher.decryptBlock(userEncryption,
  8440. false,
  8441. new Uint8Array(16));
  8442. }
  8443. };
  8444. return PDF17;
  8445. })();
  8446. var PDF20 = (function PDF20Closure() {
  8447. function concatArrays(array1, array2) {
  8448. var t = new Uint8Array(array1.length + array2.length);
  8449. t.set(array1, 0);
  8450. t.set(array2, array1.length);
  8451. return t;
  8452. }
  8453. function calculatePDF20Hash(password, input, userBytes) {
  8454. //This refers to Algorithm 2.B as defined in ISO 32000-2
  8455. var k = calculateSHA256(input, 0, input.length).subarray(0, 32);
  8456. var e = [0];
  8457. var i = 0;
  8458. while (i < 64 || e[e.length - 1] > i - 32) {
  8459. var arrayLength = password.length + k.length + userBytes.length;
  8460. var k1 = new Uint8Array(arrayLength * 64);
  8461. var array = concatArrays(password, k);
  8462. array = concatArrays(array, userBytes);
  8463. for (var j = 0, pos = 0; j < 64; j++, pos += arrayLength) {
  8464. k1.set(array, pos);
  8465. }
  8466. //AES128 CBC NO PADDING with
  8467. //first 16 bytes of k as the key and the second 16 as the iv.
  8468. var cipher = new AES128Cipher(k.subarray(0, 16));
  8469. e = cipher.encrypt(k1, k.subarray(16, 32));
  8470. //Now we have to take the first 16 bytes of an unsigned
  8471. //big endian integer... and compute the remainder
  8472. //modulo 3.... That is a fairly large number and
  8473. //JavaScript isn't going to handle that well...
  8474. //So we're using a trick that allows us to perform
  8475. //modulo math byte by byte
  8476. var remainder = 0;
  8477. for (var z = 0; z < 16; z++) {
  8478. remainder *= (256 % 3);
  8479. remainder %= 3;
  8480. remainder += ((e[z] >>> 0) % 3);
  8481. remainder %= 3;
  8482. }
  8483. if (remainder === 0) {
  8484. k = calculateSHA256(e, 0, e.length);
  8485. }
  8486. else if (remainder === 1) {
  8487. k = calculateSHA384(e, 0, e.length);
  8488. }
  8489. else if (remainder === 2) {
  8490. k = calculateSHA512(e, 0, e.length);
  8491. }
  8492. i++;
  8493. }
  8494. return k.subarray(0, 32);
  8495. }
  8496. function PDF20() {
  8497. }
  8498. function compareByteArrays(array1, array2) {
  8499. if (array1.length !== array2.length) {
  8500. return false;
  8501. }
  8502. for (var i = 0; i < array1.length; i++) {
  8503. if (array1[i] !== array2[i]) {
  8504. return false;
  8505. }
  8506. }
  8507. return true;
  8508. }
  8509. PDF20.prototype = {
  8510. hash: function PDF20_hash(password, concatBytes, userBytes) {
  8511. return calculatePDF20Hash(password, concatBytes, userBytes);
  8512. },
  8513. checkOwnerPassword: function PDF20_checkOwnerPassword(password,
  8514. ownerValidationSalt,
  8515. userBytes,
  8516. ownerPassword) {
  8517. var hashData = new Uint8Array(password.length + 56);
  8518. hashData.set(password, 0);
  8519. hashData.set(ownerValidationSalt, password.length);
  8520. hashData.set(userBytes, password.length + ownerValidationSalt.length);
  8521. var result = calculatePDF20Hash(password, hashData, userBytes);
  8522. return compareByteArrays(result, ownerPassword);
  8523. },
  8524. checkUserPassword: function PDF20_checkUserPassword(password,
  8525. userValidationSalt,
  8526. userPassword) {
  8527. var hashData = new Uint8Array(password.length + 8);
  8528. hashData.set(password, 0);
  8529. hashData.set(userValidationSalt, password.length);
  8530. var result = calculatePDF20Hash(password, hashData, []);
  8531. return compareByteArrays(result, userPassword);
  8532. },
  8533. getOwnerKey: function PDF20_getOwnerKey(password, ownerKeySalt, userBytes,
  8534. ownerEncryption) {
  8535. var hashData = new Uint8Array(password.length + 56);
  8536. hashData.set(password, 0);
  8537. hashData.set(ownerKeySalt, password.length);
  8538. hashData.set(userBytes, password.length + ownerKeySalt.length);
  8539. var key = calculatePDF20Hash(password, hashData, userBytes);
  8540. var cipher = new AES256Cipher(key);
  8541. return cipher.decryptBlock(ownerEncryption,
  8542. false,
  8543. new Uint8Array(16));
  8544. },
  8545. getUserKey: function PDF20_getUserKey(password, userKeySalt,
  8546. userEncryption) {
  8547. var hashData = new Uint8Array(password.length + 8);
  8548. hashData.set(password, 0);
  8549. hashData.set(userKeySalt, password.length);
  8550. //key is the decryption key for the UE string
  8551. var key = calculatePDF20Hash(password, hashData, []);
  8552. var cipher = new AES256Cipher(key);
  8553. return cipher.decryptBlock(userEncryption,
  8554. false,
  8555. new Uint8Array(16));
  8556. }
  8557. };
  8558. return PDF20;
  8559. })();
  8560. var CipherTransform = (function CipherTransformClosure() {
  8561. function CipherTransform(stringCipherConstructor, streamCipherConstructor) {
  8562. this.stringCipherConstructor = stringCipherConstructor;
  8563. this.streamCipherConstructor = streamCipherConstructor;
  8564. }
  8565. CipherTransform.prototype = {
  8566. createStream: function CipherTransform_createStream(stream, length) {
  8567. var cipher = new this.streamCipherConstructor();
  8568. return new DecryptStream(stream, length,
  8569. function cipherTransformDecryptStream(data, finalize) {
  8570. return cipher.decryptBlock(data, finalize);
  8571. }
  8572. );
  8573. },
  8574. decryptString: function CipherTransform_decryptString(s) {
  8575. var cipher = new this.stringCipherConstructor();
  8576. var data = stringToBytes(s);
  8577. data = cipher.decryptBlock(data, true);
  8578. return bytesToString(data);
  8579. }
  8580. };
  8581. return CipherTransform;
  8582. })();
  8583. var CipherTransformFactory = (function CipherTransformFactoryClosure() {
  8584. var defaultPasswordBytes = new Uint8Array([
  8585. 0x28, 0xBF, 0x4E, 0x5E, 0x4E, 0x75, 0x8A, 0x41,
  8586. 0x64, 0x00, 0x4E, 0x56, 0xFF, 0xFA, 0x01, 0x08,
  8587. 0x2E, 0x2E, 0x00, 0xB6, 0xD0, 0x68, 0x3E, 0x80,
  8588. 0x2F, 0x0C, 0xA9, 0xFE, 0x64, 0x53, 0x69, 0x7A]);
  8589. function createEncryptionKey20(revision, password, ownerPassword,
  8590. ownerValidationSalt, ownerKeySalt, uBytes,
  8591. userPassword, userValidationSalt, userKeySalt,
  8592. ownerEncryption, userEncryption, perms) {
  8593. if (password) {
  8594. var passwordLength = Math.min(127, password.length);
  8595. password = password.subarray(0, passwordLength);
  8596. } else {
  8597. password = [];
  8598. }
  8599. var pdfAlgorithm;
  8600. if (revision === 6) {
  8601. pdfAlgorithm = new PDF20();
  8602. } else {
  8603. pdfAlgorithm = new PDF17();
  8604. }
  8605. if (pdfAlgorithm) {
  8606. if (pdfAlgorithm.checkUserPassword(password, userValidationSalt,
  8607. userPassword)) {
  8608. return pdfAlgorithm.getUserKey(password, userKeySalt, userEncryption);
  8609. } else if (pdfAlgorithm.checkOwnerPassword(password, ownerValidationSalt,
  8610. uBytes,
  8611. ownerPassword)) {
  8612. return pdfAlgorithm.getOwnerKey(password, ownerKeySalt, uBytes,
  8613. ownerEncryption);
  8614. }
  8615. }
  8616. return null;
  8617. }
  8618. function prepareKeyData(fileId, password, ownerPassword, userPassword,
  8619. flags, revision, keyLength, encryptMetadata) {
  8620. var hashDataSize = 40 + ownerPassword.length + fileId.length;
  8621. var hashData = new Uint8Array(hashDataSize), i = 0, j, n;
  8622. if (password) {
  8623. n = Math.min(32, password.length);
  8624. for (; i < n; ++i) {
  8625. hashData[i] = password[i];
  8626. }
  8627. }
  8628. j = 0;
  8629. while (i < 32) {
  8630. hashData[i++] = defaultPasswordBytes[j++];
  8631. }
  8632. // as now the padded password in the hashData[0..i]
  8633. for (j = 0, n = ownerPassword.length; j < n; ++j) {
  8634. hashData[i++] = ownerPassword[j];
  8635. }
  8636. hashData[i++] = flags & 0xFF;
  8637. hashData[i++] = (flags >> 8) & 0xFF;
  8638. hashData[i++] = (flags >> 16) & 0xFF;
  8639. hashData[i++] = (flags >>> 24) & 0xFF;
  8640. for (j = 0, n = fileId.length; j < n; ++j) {
  8641. hashData[i++] = fileId[j];
  8642. }
  8643. if (revision >= 4 && !encryptMetadata) {
  8644. hashData[i++] = 0xFF;
  8645. hashData[i++] = 0xFF;
  8646. hashData[i++] = 0xFF;
  8647. hashData[i++] = 0xFF;
  8648. }
  8649. var hash = calculateMD5(hashData, 0, i);
  8650. var keyLengthInBytes = keyLength >> 3;
  8651. if (revision >= 3) {
  8652. for (j = 0; j < 50; ++j) {
  8653. hash = calculateMD5(hash, 0, keyLengthInBytes);
  8654. }
  8655. }
  8656. var encryptionKey = hash.subarray(0, keyLengthInBytes);
  8657. var cipher, checkData;
  8658. if (revision >= 3) {
  8659. for (i = 0; i < 32; ++i) {
  8660. hashData[i] = defaultPasswordBytes[i];
  8661. }
  8662. for (j = 0, n = fileId.length; j < n; ++j) {
  8663. hashData[i++] = fileId[j];
  8664. }
  8665. cipher = new ARCFourCipher(encryptionKey);
  8666. checkData = cipher.encryptBlock(calculateMD5(hashData, 0, i));
  8667. n = encryptionKey.length;
  8668. var derivedKey = new Uint8Array(n), k;
  8669. for (j = 1; j <= 19; ++j) {
  8670. for (k = 0; k < n; ++k) {
  8671. derivedKey[k] = encryptionKey[k] ^ j;
  8672. }
  8673. cipher = new ARCFourCipher(derivedKey);
  8674. checkData = cipher.encryptBlock(checkData);
  8675. }
  8676. for (j = 0, n = checkData.length; j < n; ++j) {
  8677. if (userPassword[j] !== checkData[j]) {
  8678. return null;
  8679. }
  8680. }
  8681. } else {
  8682. cipher = new ARCFourCipher(encryptionKey);
  8683. checkData = cipher.encryptBlock(defaultPasswordBytes);
  8684. for (j = 0, n = checkData.length; j < n; ++j) {
  8685. if (userPassword[j] !== checkData[j]) {
  8686. return null;
  8687. }
  8688. }
  8689. }
  8690. return encryptionKey;
  8691. }
  8692. function decodeUserPassword(password, ownerPassword, revision, keyLength) {
  8693. var hashData = new Uint8Array(32), i = 0, j, n;
  8694. n = Math.min(32, password.length);
  8695. for (; i < n; ++i) {
  8696. hashData[i] = password[i];
  8697. }
  8698. j = 0;
  8699. while (i < 32) {
  8700. hashData[i++] = defaultPasswordBytes[j++];
  8701. }
  8702. var hash = calculateMD5(hashData, 0, i);
  8703. var keyLengthInBytes = keyLength >> 3;
  8704. if (revision >= 3) {
  8705. for (j = 0; j < 50; ++j) {
  8706. hash = calculateMD5(hash, 0, hash.length);
  8707. }
  8708. }
  8709. var cipher, userPassword;
  8710. if (revision >= 3) {
  8711. userPassword = ownerPassword;
  8712. var derivedKey = new Uint8Array(keyLengthInBytes), k;
  8713. for (j = 19; j >= 0; j--) {
  8714. for (k = 0; k < keyLengthInBytes; ++k) {
  8715. derivedKey[k] = hash[k] ^ j;
  8716. }
  8717. cipher = new ARCFourCipher(derivedKey);
  8718. userPassword = cipher.encryptBlock(userPassword);
  8719. }
  8720. } else {
  8721. cipher = new ARCFourCipher(hash.subarray(0, keyLengthInBytes));
  8722. userPassword = cipher.encryptBlock(ownerPassword);
  8723. }
  8724. return userPassword;
  8725. }
  8726. var identityName = Name.get('Identity');
  8727. function CipherTransformFactory(dict, fileId, password) {
  8728. var filter = dict.get('Filter');
  8729. if (!isName(filter) || filter.name !== 'Standard') {
  8730. error('unknown encryption method');
  8731. }
  8732. this.dict = dict;
  8733. var algorithm = dict.get('V');
  8734. if (!isInt(algorithm) ||
  8735. (algorithm !== 1 && algorithm !== 2 && algorithm !== 4 &&
  8736. algorithm !== 5)) {
  8737. error('unsupported encryption algorithm');
  8738. }
  8739. this.algorithm = algorithm;
  8740. var keyLength = dict.get('Length') || 40;
  8741. if (!isInt(keyLength) ||
  8742. keyLength < 40 || (keyLength % 8) !== 0) {
  8743. error('invalid key length');
  8744. }
  8745. // prepare keys
  8746. var ownerPassword = stringToBytes(dict.get('O')).subarray(0, 32);
  8747. var userPassword = stringToBytes(dict.get('U')).subarray(0, 32);
  8748. var flags = dict.get('P');
  8749. var revision = dict.get('R');
  8750. // meaningful when V is 4 or 5
  8751. var encryptMetadata = ((algorithm === 4 || algorithm === 5) &&
  8752. dict.get('EncryptMetadata') !== false);
  8753. this.encryptMetadata = encryptMetadata;
  8754. var fileIdBytes = stringToBytes(fileId);
  8755. var passwordBytes;
  8756. if (password) {
  8757. passwordBytes = stringToBytes(password);
  8758. }
  8759. var encryptionKey;
  8760. if (algorithm !== 5) {
  8761. encryptionKey = prepareKeyData(fileIdBytes, passwordBytes,
  8762. ownerPassword, userPassword, flags,
  8763. revision, keyLength, encryptMetadata);
  8764. }
  8765. else {
  8766. var ownerValidationSalt = stringToBytes(dict.get('O')).subarray(32, 40);
  8767. var ownerKeySalt = stringToBytes(dict.get('O')).subarray(40, 48);
  8768. var uBytes = stringToBytes(dict.get('U')).subarray(0, 48);
  8769. var userValidationSalt = stringToBytes(dict.get('U')).subarray(32, 40);
  8770. var userKeySalt = stringToBytes(dict.get('U')).subarray(40, 48);
  8771. var ownerEncryption = stringToBytes(dict.get('OE'));
  8772. var userEncryption = stringToBytes(dict.get('UE'));
  8773. var perms = stringToBytes(dict.get('Perms'));
  8774. encryptionKey =
  8775. createEncryptionKey20(revision, passwordBytes,
  8776. ownerPassword, ownerValidationSalt,
  8777. ownerKeySalt, uBytes,
  8778. userPassword, userValidationSalt,
  8779. userKeySalt, ownerEncryption,
  8780. userEncryption, perms);
  8781. }
  8782. if (!encryptionKey && !password) {
  8783. throw new PasswordException('No password given',
  8784. PasswordResponses.NEED_PASSWORD);
  8785. } else if (!encryptionKey && password) {
  8786. // Attempting use the password as an owner password
  8787. var decodedPassword = decodeUserPassword(passwordBytes, ownerPassword,
  8788. revision, keyLength);
  8789. encryptionKey = prepareKeyData(fileIdBytes, decodedPassword,
  8790. ownerPassword, userPassword, flags,
  8791. revision, keyLength, encryptMetadata);
  8792. }
  8793. if (!encryptionKey) {
  8794. throw new PasswordException('Incorrect Password',
  8795. PasswordResponses.INCORRECT_PASSWORD);
  8796. }
  8797. this.encryptionKey = encryptionKey;
  8798. if (algorithm >= 4) {
  8799. this.cf = dict.get('CF');
  8800. this.stmf = dict.get('StmF') || identityName;
  8801. this.strf = dict.get('StrF') || identityName;
  8802. this.eff = dict.get('EFF') || this.stmf;
  8803. }
  8804. }
  8805. function buildObjectKey(num, gen, encryptionKey, isAes) {
  8806. var key = new Uint8Array(encryptionKey.length + 9), i, n;
  8807. for (i = 0, n = encryptionKey.length; i < n; ++i) {
  8808. key[i] = encryptionKey[i];
  8809. }
  8810. key[i++] = num & 0xFF;
  8811. key[i++] = (num >> 8) & 0xFF;
  8812. key[i++] = (num >> 16) & 0xFF;
  8813. key[i++] = gen & 0xFF;
  8814. key[i++] = (gen >> 8) & 0xFF;
  8815. if (isAes) {
  8816. key[i++] = 0x73;
  8817. key[i++] = 0x41;
  8818. key[i++] = 0x6C;
  8819. key[i++] = 0x54;
  8820. }
  8821. var hash = calculateMD5(key, 0, i);
  8822. return hash.subarray(0, Math.min(encryptionKey.length + 5, 16));
  8823. }
  8824. function buildCipherConstructor(cf, name, num, gen, key) {
  8825. var cryptFilter = cf.get(name.name);
  8826. var cfm;
  8827. if (cryptFilter !== null && cryptFilter !== undefined) {
  8828. cfm = cryptFilter.get('CFM');
  8829. }
  8830. if (!cfm || cfm.name === 'None') {
  8831. return function cipherTransformFactoryBuildCipherConstructorNone() {
  8832. return new NullCipher();
  8833. };
  8834. }
  8835. if ('V2' === cfm.name) {
  8836. return function cipherTransformFactoryBuildCipherConstructorV2() {
  8837. return new ARCFourCipher(buildObjectKey(num, gen, key, false));
  8838. };
  8839. }
  8840. if ('AESV2' === cfm.name) {
  8841. return function cipherTransformFactoryBuildCipherConstructorAESV2() {
  8842. return new AES128Cipher(buildObjectKey(num, gen, key, true));
  8843. };
  8844. }
  8845. if ('AESV3' === cfm.name) {
  8846. return function cipherTransformFactoryBuildCipherConstructorAESV3() {
  8847. return new AES256Cipher(key);
  8848. };
  8849. }
  8850. error('Unknown crypto method');
  8851. }
  8852. CipherTransformFactory.prototype = {
  8853. createCipherTransform:
  8854. function CipherTransformFactory_createCipherTransform(num, gen) {
  8855. if (this.algorithm === 4 || this.algorithm === 5) {
  8856. return new CipherTransform(
  8857. buildCipherConstructor(this.cf, this.stmf,
  8858. num, gen, this.encryptionKey),
  8859. buildCipherConstructor(this.cf, this.strf,
  8860. num, gen, this.encryptionKey));
  8861. }
  8862. // algorithms 1 and 2
  8863. var key = buildObjectKey(num, gen, this.encryptionKey, false);
  8864. var cipherConstructor = function buildCipherCipherConstructor() {
  8865. return new ARCFourCipher(key);
  8866. };
  8867. return new CipherTransform(cipherConstructor, cipherConstructor);
  8868. }
  8869. };
  8870. return CipherTransformFactory;
  8871. })();
  8872. var PatternType = {
  8873. FUNCTION_BASED: 1,
  8874. AXIAL: 2,
  8875. RADIAL: 3,
  8876. FREE_FORM_MESH: 4,
  8877. LATTICE_FORM_MESH: 5,
  8878. COONS_PATCH_MESH: 6,
  8879. TENSOR_PATCH_MESH: 7
  8880. };
  8881. var Pattern = (function PatternClosure() {
  8882. // Constructor should define this.getPattern
  8883. function Pattern() {
  8884. error('should not call Pattern constructor');
  8885. }
  8886. Pattern.prototype = {
  8887. // Input: current Canvas context
  8888. // Output: the appropriate fillStyle or strokeStyle
  8889. getPattern: function Pattern_getPattern(ctx) {
  8890. error('Should not call Pattern.getStyle: ' + ctx);
  8891. }
  8892. };
  8893. Pattern.parseShading = function Pattern_parseShading(shading, matrix, xref,
  8894. res) {
  8895. var dict = isStream(shading) ? shading.dict : shading;
  8896. var type = dict.get('ShadingType');
  8897. try {
  8898. switch (type) {
  8899. case PatternType.AXIAL:
  8900. case PatternType.RADIAL:
  8901. // Both radial and axial shadings are handled by RadialAxial shading.
  8902. return new Shadings.RadialAxial(dict, matrix, xref, res);
  8903. case PatternType.FREE_FORM_MESH:
  8904. case PatternType.LATTICE_FORM_MESH:
  8905. case PatternType.COONS_PATCH_MESH:
  8906. case PatternType.TENSOR_PATCH_MESH:
  8907. return new Shadings.Mesh(shading, matrix, xref, res);
  8908. default:
  8909. throw new Error('Unknown PatternType: ' + type);
  8910. }
  8911. } catch (ex) {
  8912. if (ex instanceof MissingDataException) {
  8913. throw ex;
  8914. }
  8915. UnsupportedManager.notify(UNSUPPORTED_FEATURES.shadingPattern);
  8916. warn(ex);
  8917. return new Shadings.Dummy();
  8918. }
  8919. };
  8920. return Pattern;
  8921. })();
  8922. var Shadings = {};
  8923. // A small number to offset the first/last color stops so we can insert ones to
  8924. // support extend. Number.MIN_VALUE appears to be too small and breaks the
  8925. // extend. 1e-7 works in FF but chrome seems to use an even smaller sized number
  8926. // internally so we have to go bigger.
  8927. Shadings.SMALL_NUMBER = 1e-2;
  8928. // Radial and axial shading have very similar implementations
  8929. // If needed, the implementations can be broken into two classes
  8930. Shadings.RadialAxial = (function RadialAxialClosure() {
  8931. function RadialAxial(dict, matrix, xref, res) {
  8932. this.matrix = matrix;
  8933. this.coordsArr = dict.get('Coords');
  8934. this.shadingType = dict.get('ShadingType');
  8935. this.type = 'Pattern';
  8936. var cs = dict.get('ColorSpace', 'CS');
  8937. cs = ColorSpace.parse(cs, xref, res);
  8938. this.cs = cs;
  8939. var t0 = 0.0, t1 = 1.0;
  8940. if (dict.has('Domain')) {
  8941. var domainArr = dict.get('Domain');
  8942. t0 = domainArr[0];
  8943. t1 = domainArr[1];
  8944. }
  8945. var extendStart = false, extendEnd = false;
  8946. if (dict.has('Extend')) {
  8947. var extendArr = dict.get('Extend');
  8948. extendStart = extendArr[0];
  8949. extendEnd = extendArr[1];
  8950. }
  8951. if (this.shadingType === PatternType.RADIAL &&
  8952. (!extendStart || !extendEnd)) {
  8953. // Radial gradient only currently works if either circle is fully within
  8954. // the other circle.
  8955. var x1 = this.coordsArr[0];
  8956. var y1 = this.coordsArr[1];
  8957. var r1 = this.coordsArr[2];
  8958. var x2 = this.coordsArr[3];
  8959. var y2 = this.coordsArr[4];
  8960. var r2 = this.coordsArr[5];
  8961. var distance = Math.sqrt((x1 - x2) * (x1 - x2) + (y1 - y2) * (y1 - y2));
  8962. if (r1 <= r2 + distance &&
  8963. r2 <= r1 + distance) {
  8964. warn('Unsupported radial gradient.');
  8965. }
  8966. }
  8967. this.extendStart = extendStart;
  8968. this.extendEnd = extendEnd;
  8969. var fnObj = dict.get('Function');
  8970. var fn = PDFFunction.parseArray(xref, fnObj);
  8971. // 10 samples seems good enough for now, but probably won't work
  8972. // if there are sharp color changes. Ideally, we would implement
  8973. // the spec faithfully and add lossless optimizations.
  8974. var diff = t1 - t0;
  8975. var step = diff / 10;
  8976. var colorStops = this.colorStops = [];
  8977. // Protect against bad domains so we don't end up in an infinte loop below.
  8978. if (t0 >= t1 || step <= 0) {
  8979. // Acrobat doesn't seem to handle these cases so we'll ignore for
  8980. // now.
  8981. info('Bad shading domain.');
  8982. return;
  8983. }
  8984. var color = new Float32Array(cs.numComps), ratio = new Float32Array(1);
  8985. var rgbColor;
  8986. for (var i = t0; i <= t1; i += step) {
  8987. ratio[0] = i;
  8988. fn(ratio, 0, color, 0);
  8989. rgbColor = cs.getRgb(color, 0);
  8990. var cssColor = Util.makeCssRgb(rgbColor[0], rgbColor[1], rgbColor[2]);
  8991. colorStops.push([(i - t0) / diff, cssColor]);
  8992. }
  8993. var background = 'transparent';
  8994. if (dict.has('Background')) {
  8995. rgbColor = cs.getRgb(dict.get('Background'), 0);
  8996. background = Util.makeCssRgb(rgbColor[0], rgbColor[1], rgbColor[2]);
  8997. }
  8998. if (!extendStart) {
  8999. // Insert a color stop at the front and offset the first real color stop
  9000. // so it doesn't conflict with the one we insert.
  9001. colorStops.unshift([0, background]);
  9002. colorStops[1][0] += Shadings.SMALL_NUMBER;
  9003. }
  9004. if (!extendEnd) {
  9005. // Same idea as above in extendStart but for the end.
  9006. colorStops[colorStops.length - 1][0] -= Shadings.SMALL_NUMBER;
  9007. colorStops.push([1, background]);
  9008. }
  9009. this.colorStops = colorStops;
  9010. }
  9011. RadialAxial.prototype = {
  9012. getIR: function RadialAxial_getIR() {
  9013. var coordsArr = this.coordsArr;
  9014. var shadingType = this.shadingType;
  9015. var type, p0, p1, r0, r1;
  9016. if (shadingType === PatternType.AXIAL) {
  9017. p0 = [coordsArr[0], coordsArr[1]];
  9018. p1 = [coordsArr[2], coordsArr[3]];
  9019. r0 = null;
  9020. r1 = null;
  9021. type = 'axial';
  9022. } else if (shadingType === PatternType.RADIAL) {
  9023. p0 = [coordsArr[0], coordsArr[1]];
  9024. p1 = [coordsArr[3], coordsArr[4]];
  9025. r0 = coordsArr[2];
  9026. r1 = coordsArr[5];
  9027. type = 'radial';
  9028. } else {
  9029. error('getPattern type unknown: ' + shadingType);
  9030. }
  9031. var matrix = this.matrix;
  9032. if (matrix) {
  9033. p0 = Util.applyTransform(p0, matrix);
  9034. p1 = Util.applyTransform(p1, matrix);
  9035. }
  9036. return ['RadialAxial', type, this.colorStops, p0, p1, r0, r1];
  9037. }
  9038. };
  9039. return RadialAxial;
  9040. })();
  9041. // All mesh shading. For now, they will be presented as set of the triangles
  9042. // to be drawn on the canvas and rgb color for each vertex.
  9043. Shadings.Mesh = (function MeshClosure() {
  9044. function MeshStreamReader(stream, context) {
  9045. this.stream = stream;
  9046. this.context = context;
  9047. this.buffer = 0;
  9048. this.bufferLength = 0;
  9049. var numComps = context.numComps;
  9050. this.tmpCompsBuf = new Float32Array(numComps);
  9051. var csNumComps = context.colorSpace;
  9052. this.tmpCsCompsBuf = context.colorFn ? new Float32Array(csNumComps) :
  9053. this.tmpCompsBuf;
  9054. }
  9055. MeshStreamReader.prototype = {
  9056. get hasData() {
  9057. if (this.stream.end) {
  9058. return this.stream.pos < this.stream.end;
  9059. }
  9060. if (this.bufferLength > 0) {
  9061. return true;
  9062. }
  9063. var nextByte = this.stream.getByte();
  9064. if (nextByte < 0) {
  9065. return false;
  9066. }
  9067. this.buffer = nextByte;
  9068. this.bufferLength = 8;
  9069. return true;
  9070. },
  9071. readBits: function MeshStreamReader_readBits(n) {
  9072. var buffer = this.buffer;
  9073. var bufferLength = this.bufferLength;
  9074. if (n === 32) {
  9075. if (bufferLength === 0) {
  9076. return ((this.stream.getByte() << 24) |
  9077. (this.stream.getByte() << 16) | (this.stream.getByte() << 8) |
  9078. this.stream.getByte()) >>> 0;
  9079. }
  9080. buffer = (buffer << 24) | (this.stream.getByte() << 16) |
  9081. (this.stream.getByte() << 8) | this.stream.getByte();
  9082. var nextByte = this.stream.getByte();
  9083. this.buffer = nextByte & ((1 << bufferLength) - 1);
  9084. return ((buffer << (8 - bufferLength)) |
  9085. ((nextByte & 0xFF) >> bufferLength)) >>> 0;
  9086. }
  9087. if (n === 8 && bufferLength === 0) {
  9088. return this.stream.getByte();
  9089. }
  9090. while (bufferLength < n) {
  9091. buffer = (buffer << 8) | this.stream.getByte();
  9092. bufferLength += 8;
  9093. }
  9094. bufferLength -= n;
  9095. this.bufferLength = bufferLength;
  9096. this.buffer = buffer & ((1 << bufferLength) - 1);
  9097. return buffer >> bufferLength;
  9098. },
  9099. align: function MeshStreamReader_align() {
  9100. this.buffer = 0;
  9101. this.bufferLength = 0;
  9102. },
  9103. readFlag: function MeshStreamReader_readFlag() {
  9104. return this.readBits(this.context.bitsPerFlag);
  9105. },
  9106. readCoordinate: function MeshStreamReader_readCoordinate() {
  9107. var bitsPerCoordinate = this.context.bitsPerCoordinate;
  9108. var xi = this.readBits(bitsPerCoordinate);
  9109. var yi = this.readBits(bitsPerCoordinate);
  9110. var decode = this.context.decode;
  9111. var scale = bitsPerCoordinate < 32 ? 1 / ((1 << bitsPerCoordinate) - 1) :
  9112. 2.3283064365386963e-10; // 2 ^ -32
  9113. return [
  9114. xi * scale * (decode[1] - decode[0]) + decode[0],
  9115. yi * scale * (decode[3] - decode[2]) + decode[2]
  9116. ];
  9117. },
  9118. readComponents: function MeshStreamReader_readComponents() {
  9119. var numComps = this.context.numComps;
  9120. var bitsPerComponent = this.context.bitsPerComponent;
  9121. var scale = bitsPerComponent < 32 ? 1 / ((1 << bitsPerComponent) - 1) :
  9122. 2.3283064365386963e-10; // 2 ^ -32
  9123. var decode = this.context.decode;
  9124. var components = this.tmpCompsBuf;
  9125. for (var i = 0, j = 4; i < numComps; i++, j += 2) {
  9126. var ci = this.readBits(bitsPerComponent);
  9127. components[i] = ci * scale * (decode[j + 1] - decode[j]) + decode[j];
  9128. }
  9129. var color = this.tmpCsCompsBuf;
  9130. if (this.context.colorFn) {
  9131. this.context.colorFn(components, 0, color, 0);
  9132. }
  9133. return this.context.colorSpace.getRgb(color, 0);
  9134. }
  9135. };
  9136. function decodeType4Shading(mesh, reader) {
  9137. var coords = mesh.coords;
  9138. var colors = mesh.colors;
  9139. var operators = [];
  9140. var ps = []; // not maintaining cs since that will match ps
  9141. var verticesLeft = 0; // assuming we have all data to start a new triangle
  9142. while (reader.hasData) {
  9143. var f = reader.readFlag();
  9144. var coord = reader.readCoordinate();
  9145. var color = reader.readComponents();
  9146. if (verticesLeft === 0) { // ignoring flags if we started a triangle
  9147. assert(0 <= f && f <= 2, 'Unknown type4 flag');
  9148. switch (f) {
  9149. case 0:
  9150. verticesLeft = 3;
  9151. break;
  9152. case 1:
  9153. ps.push(ps[ps.length - 2], ps[ps.length - 1]);
  9154. verticesLeft = 1;
  9155. break;
  9156. case 2:
  9157. ps.push(ps[ps.length - 3], ps[ps.length - 1]);
  9158. verticesLeft = 1;
  9159. break;
  9160. }
  9161. operators.push(f);
  9162. }
  9163. ps.push(coords.length);
  9164. coords.push(coord);
  9165. colors.push(color);
  9166. verticesLeft--;
  9167. reader.align();
  9168. }
  9169. var psPacked = new Int32Array(ps);
  9170. mesh.figures.push({
  9171. type: 'triangles',
  9172. coords: psPacked,
  9173. colors: psPacked
  9174. });
  9175. }
  9176. function decodeType5Shading(mesh, reader, verticesPerRow) {
  9177. var coords = mesh.coords;
  9178. var colors = mesh.colors;
  9179. var ps = []; // not maintaining cs since that will match ps
  9180. while (reader.hasData) {
  9181. var coord = reader.readCoordinate();
  9182. var color = reader.readComponents();
  9183. ps.push(coords.length);
  9184. coords.push(coord);
  9185. colors.push(color);
  9186. }
  9187. var psPacked = new Int32Array(ps);
  9188. mesh.figures.push({
  9189. type: 'lattice',
  9190. coords: psPacked,
  9191. colors: psPacked,
  9192. verticesPerRow: verticesPerRow
  9193. });
  9194. }
  9195. var MIN_SPLIT_PATCH_CHUNKS_AMOUNT = 3;
  9196. var MAX_SPLIT_PATCH_CHUNKS_AMOUNT = 20;
  9197. var TRIANGLE_DENSITY = 20; // count of triangles per entire mesh bounds
  9198. var getB = (function getBClosure() {
  9199. function buildB(count) {
  9200. var lut = [];
  9201. for (var i = 0; i <= count; i++) {
  9202. var t = i / count, t_ = 1 - t;
  9203. lut.push(new Float32Array([t_ * t_ * t_, 3 * t * t_ * t_,
  9204. 3 * t * t * t_, t * t * t]));
  9205. }
  9206. return lut;
  9207. }
  9208. var cache = [];
  9209. return function getB(count) {
  9210. if (!cache[count]) {
  9211. cache[count] = buildB(count);
  9212. }
  9213. return cache[count];
  9214. };
  9215. })();
  9216. function buildFigureFromPatch(mesh, index) {
  9217. var figure = mesh.figures[index];
  9218. assert(figure.type === 'patch', 'Unexpected patch mesh figure');
  9219. var coords = mesh.coords, colors = mesh.colors;
  9220. var pi = figure.coords;
  9221. var ci = figure.colors;
  9222. var figureMinX = Math.min(coords[pi[0]][0], coords[pi[3]][0],
  9223. coords[pi[12]][0], coords[pi[15]][0]);
  9224. var figureMinY = Math.min(coords[pi[0]][1], coords[pi[3]][1],
  9225. coords[pi[12]][1], coords[pi[15]][1]);
  9226. var figureMaxX = Math.max(coords[pi[0]][0], coords[pi[3]][0],
  9227. coords[pi[12]][0], coords[pi[15]][0]);
  9228. var figureMaxY = Math.max(coords[pi[0]][1], coords[pi[3]][1],
  9229. coords[pi[12]][1], coords[pi[15]][1]);
  9230. var splitXBy = Math.ceil((figureMaxX - figureMinX) * TRIANGLE_DENSITY /
  9231. (mesh.bounds[2] - mesh.bounds[0]));
  9232. splitXBy = Math.max(MIN_SPLIT_PATCH_CHUNKS_AMOUNT,
  9233. Math.min(MAX_SPLIT_PATCH_CHUNKS_AMOUNT, splitXBy));
  9234. var splitYBy = Math.ceil((figureMaxY - figureMinY) * TRIANGLE_DENSITY /
  9235. (mesh.bounds[3] - mesh.bounds[1]));
  9236. splitYBy = Math.max(MIN_SPLIT_PATCH_CHUNKS_AMOUNT,
  9237. Math.min(MAX_SPLIT_PATCH_CHUNKS_AMOUNT, splitYBy));
  9238. var verticesPerRow = splitXBy + 1;
  9239. var figureCoords = new Int32Array((splitYBy + 1) * verticesPerRow);
  9240. var figureColors = new Int32Array((splitYBy + 1) * verticesPerRow);
  9241. var k = 0;
  9242. var cl = new Uint8Array(3), cr = new Uint8Array(3);
  9243. var c0 = colors[ci[0]], c1 = colors[ci[1]],
  9244. c2 = colors[ci[2]], c3 = colors[ci[3]];
  9245. var bRow = getB(splitYBy), bCol = getB(splitXBy);
  9246. for (var row = 0; row <= splitYBy; row++) {
  9247. cl[0] = ((c0[0] * (splitYBy - row) + c2[0] * row) / splitYBy) | 0;
  9248. cl[1] = ((c0[1] * (splitYBy - row) + c2[1] * row) / splitYBy) | 0;
  9249. cl[2] = ((c0[2] * (splitYBy - row) + c2[2] * row) / splitYBy) | 0;
  9250. cr[0] = ((c1[0] * (splitYBy - row) + c3[0] * row) / splitYBy) | 0;
  9251. cr[1] = ((c1[1] * (splitYBy - row) + c3[1] * row) / splitYBy) | 0;
  9252. cr[2] = ((c1[2] * (splitYBy - row) + c3[2] * row) / splitYBy) | 0;
  9253. for (var col = 0; col <= splitXBy; col++, k++) {
  9254. if ((row === 0 || row === splitYBy) &&
  9255. (col === 0 || col === splitXBy)) {
  9256. continue;
  9257. }
  9258. var x = 0, y = 0;
  9259. var q = 0;
  9260. for (var i = 0; i <= 3; i++) {
  9261. for (var j = 0; j <= 3; j++, q++) {
  9262. var m = bRow[row][i] * bCol[col][j];
  9263. x += coords[pi[q]][0] * m;
  9264. y += coords[pi[q]][1] * m;
  9265. }
  9266. }
  9267. figureCoords[k] = coords.length;
  9268. coords.push([x, y]);
  9269. figureColors[k] = colors.length;
  9270. var newColor = new Uint8Array(3);
  9271. newColor[0] = ((cl[0] * (splitXBy - col) + cr[0] * col) / splitXBy) | 0;
  9272. newColor[1] = ((cl[1] * (splitXBy - col) + cr[1] * col) / splitXBy) | 0;
  9273. newColor[2] = ((cl[2] * (splitXBy - col) + cr[2] * col) / splitXBy) | 0;
  9274. colors.push(newColor);
  9275. }
  9276. }
  9277. figureCoords[0] = pi[0];
  9278. figureColors[0] = ci[0];
  9279. figureCoords[splitXBy] = pi[3];
  9280. figureColors[splitXBy] = ci[1];
  9281. figureCoords[verticesPerRow * splitYBy] = pi[12];
  9282. figureColors[verticesPerRow * splitYBy] = ci[2];
  9283. figureCoords[verticesPerRow * splitYBy + splitXBy] = pi[15];
  9284. figureColors[verticesPerRow * splitYBy + splitXBy] = ci[3];
  9285. mesh.figures[index] = {
  9286. type: 'lattice',
  9287. coords: figureCoords,
  9288. colors: figureColors,
  9289. verticesPerRow: verticesPerRow
  9290. };
  9291. }
  9292. function decodeType6Shading(mesh, reader) {
  9293. // A special case of Type 7. The p11, p12, p21, p22 automatically filled
  9294. var coords = mesh.coords;
  9295. var colors = mesh.colors;
  9296. var ps = new Int32Array(16); // p00, p10, ..., p30, p01, ..., p33
  9297. var cs = new Int32Array(4); // c00, c30, c03, c33
  9298. while (reader.hasData) {
  9299. var f = reader.readFlag();
  9300. assert(0 <= f && f <= 3, 'Unknown type6 flag');
  9301. var i, ii;
  9302. var pi = coords.length;
  9303. for (i = 0, ii = (f !== 0 ? 8 : 12); i < ii; i++) {
  9304. coords.push(reader.readCoordinate());
  9305. }
  9306. var ci = colors.length;
  9307. for (i = 0, ii = (f !== 0 ? 2 : 4); i < ii; i++) {
  9308. colors.push(reader.readComponents());
  9309. }
  9310. var tmp1, tmp2, tmp3, tmp4;
  9311. switch (f) {
  9312. case 0:
  9313. ps[12] = pi + 3; ps[13] = pi + 4; ps[14] = pi + 5; ps[15] = pi + 6;
  9314. ps[ 8] = pi + 2; /* values for 5, 6, 9, 10 are */ ps[11] = pi + 7;
  9315. ps[ 4] = pi + 1; /* calculated below */ ps[ 7] = pi + 8;
  9316. ps[ 0] = pi; ps[ 1] = pi + 11; ps[ 2] = pi + 10; ps[ 3] = pi + 9;
  9317. cs[2] = ci + 1; cs[3] = ci + 2;
  9318. cs[0] = ci; cs[1] = ci + 3;
  9319. break;
  9320. case 1:
  9321. tmp1 = ps[12]; tmp2 = ps[13]; tmp3 = ps[14]; tmp4 = ps[15];
  9322. ps[12] = pi + 5; ps[13] = pi + 4; ps[14] = pi + 3; ps[15] = pi + 2;
  9323. ps[ 8] = pi + 6; /* values for 5, 6, 9, 10 are */ ps[11] = pi + 1;
  9324. ps[ 4] = pi + 7; /* calculated below */ ps[ 7] = pi;
  9325. ps[ 0] = tmp1; ps[ 1] = tmp2; ps[ 2] = tmp3; ps[ 3] = tmp4;
  9326. tmp1 = cs[2]; tmp2 = cs[3];
  9327. cs[2] = ci + 1; cs[3] = ci;
  9328. cs[0] = tmp1; cs[1] = tmp2;
  9329. break;
  9330. case 2:
  9331. ps[12] = ps[15]; ps[13] = pi + 7; ps[14] = pi + 6; ps[15] = pi + 5;
  9332. ps[ 8] = ps[11]; /* values for 5, 6, 9, 10 are */ ps[11] = pi + 4;
  9333. ps[ 4] = ps[7]; /* calculated below */ ps[ 7] = pi + 3;
  9334. ps[ 0] = ps[3]; ps[ 1] = pi; ps[ 2] = pi + 1; ps[ 3] = pi + 2;
  9335. cs[2] = cs[3]; cs[3] = ci + 1;
  9336. cs[0] = cs[1]; cs[1] = ci;
  9337. break;
  9338. case 3:
  9339. ps[12] = ps[0]; ps[13] = ps[1]; ps[14] = ps[2]; ps[15] = ps[3];
  9340. ps[ 8] = pi; /* values for 5, 6, 9, 10 are */ ps[11] = pi + 7;
  9341. ps[ 4] = pi + 1; /* calculated below */ ps[ 7] = pi + 6;
  9342. ps[ 0] = pi + 2; ps[ 1] = pi + 3; ps[ 2] = pi + 4; ps[ 3] = pi + 5;
  9343. cs[2] = cs[0]; cs[3] = cs[1];
  9344. cs[0] = ci; cs[1] = ci + 1;
  9345. break;
  9346. }
  9347. // set p11, p12, p21, p22
  9348. ps[5] = coords.length;
  9349. coords.push([
  9350. (-4 * coords[ps[0]][0] - coords[ps[15]][0] +
  9351. 6 * (coords[ps[4]][0] + coords[ps[1]][0]) -
  9352. 2 * (coords[ps[12]][0] + coords[ps[3]][0]) +
  9353. 3 * (coords[ps[13]][0] + coords[ps[7]][0])) / 9,
  9354. (-4 * coords[ps[0]][1] - coords[ps[15]][1] +
  9355. 6 * (coords[ps[4]][1] + coords[ps[1]][1]) -
  9356. 2 * (coords[ps[12]][1] + coords[ps[3]][1]) +
  9357. 3 * (coords[ps[13]][1] + coords[ps[7]][1])) / 9
  9358. ]);
  9359. ps[6] = coords.length;
  9360. coords.push([
  9361. (-4 * coords[ps[3]][0] - coords[ps[12]][0] +
  9362. 6 * (coords[ps[2]][0] + coords[ps[7]][0]) -
  9363. 2 * (coords[ps[0]][0] + coords[ps[15]][0]) +
  9364. 3 * (coords[ps[4]][0] + coords[ps[14]][0])) / 9,
  9365. (-4 * coords[ps[3]][1] - coords[ps[12]][1] +
  9366. 6 * (coords[ps[2]][1] + coords[ps[7]][1]) -
  9367. 2 * (coords[ps[0]][1] + coords[ps[15]][1]) +
  9368. 3 * (coords[ps[4]][1] + coords[ps[14]][1])) / 9
  9369. ]);
  9370. ps[9] = coords.length;
  9371. coords.push([
  9372. (-4 * coords[ps[12]][0] - coords[ps[3]][0] +
  9373. 6 * (coords[ps[8]][0] + coords[ps[13]][0]) -
  9374. 2 * (coords[ps[0]][0] + coords[ps[15]][0]) +
  9375. 3 * (coords[ps[11]][0] + coords[ps[1]][0])) / 9,
  9376. (-4 * coords[ps[12]][1] - coords[ps[3]][1] +
  9377. 6 * (coords[ps[8]][1] + coords[ps[13]][1]) -
  9378. 2 * (coords[ps[0]][1] + coords[ps[15]][1]) +
  9379. 3 * (coords[ps[11]][1] + coords[ps[1]][1])) / 9
  9380. ]);
  9381. ps[10] = coords.length;
  9382. coords.push([
  9383. (-4 * coords[ps[15]][0] - coords[ps[0]][0] +
  9384. 6 * (coords[ps[11]][0] + coords[ps[14]][0]) -
  9385. 2 * (coords[ps[12]][0] + coords[ps[3]][0]) +
  9386. 3 * (coords[ps[2]][0] + coords[ps[8]][0])) / 9,
  9387. (-4 * coords[ps[15]][1] - coords[ps[0]][1] +
  9388. 6 * (coords[ps[11]][1] + coords[ps[14]][1]) -
  9389. 2 * (coords[ps[12]][1] + coords[ps[3]][1]) +
  9390. 3 * (coords[ps[2]][1] + coords[ps[8]][1])) / 9
  9391. ]);
  9392. mesh.figures.push({
  9393. type: 'patch',
  9394. coords: new Int32Array(ps), // making copies of ps and cs
  9395. colors: new Int32Array(cs)
  9396. });
  9397. }
  9398. }
  9399. function decodeType7Shading(mesh, reader) {
  9400. var coords = mesh.coords;
  9401. var colors = mesh.colors;
  9402. var ps = new Int32Array(16); // p00, p10, ..., p30, p01, ..., p33
  9403. var cs = new Int32Array(4); // c00, c30, c03, c33
  9404. while (reader.hasData) {
  9405. var f = reader.readFlag();
  9406. assert(0 <= f && f <= 3, 'Unknown type7 flag');
  9407. var i, ii;
  9408. var pi = coords.length;
  9409. for (i = 0, ii = (f !== 0 ? 12 : 16); i < ii; i++) {
  9410. coords.push(reader.readCoordinate());
  9411. }
  9412. var ci = colors.length;
  9413. for (i = 0, ii = (f !== 0 ? 2 : 4); i < ii; i++) {
  9414. colors.push(reader.readComponents());
  9415. }
  9416. var tmp1, tmp2, tmp3, tmp4;
  9417. switch (f) {
  9418. case 0:
  9419. ps[12] = pi + 3; ps[13] = pi + 4; ps[14] = pi + 5; ps[15] = pi + 6;
  9420. ps[ 8] = pi + 2; ps[ 9] = pi + 13; ps[10] = pi + 14; ps[11] = pi + 7;
  9421. ps[ 4] = pi + 1; ps[ 5] = pi + 12; ps[ 6] = pi + 15; ps[ 7] = pi + 8;
  9422. ps[ 0] = pi; ps[ 1] = pi + 11; ps[ 2] = pi + 10; ps[ 3] = pi + 9;
  9423. cs[2] = ci + 1; cs[3] = ci + 2;
  9424. cs[0] = ci; cs[1] = ci + 3;
  9425. break;
  9426. case 1:
  9427. tmp1 = ps[12]; tmp2 = ps[13]; tmp3 = ps[14]; tmp4 = ps[15];
  9428. ps[12] = pi + 5; ps[13] = pi + 4; ps[14] = pi + 3; ps[15] = pi + 2;
  9429. ps[ 8] = pi + 6; ps[ 9] = pi + 11; ps[10] = pi + 10; ps[11] = pi + 1;
  9430. ps[ 4] = pi + 7; ps[ 5] = pi + 8; ps[ 6] = pi + 9; ps[ 7] = pi;
  9431. ps[ 0] = tmp1; ps[ 1] = tmp2; ps[ 2] = tmp3; ps[ 3] = tmp4;
  9432. tmp1 = cs[2]; tmp2 = cs[3];
  9433. cs[2] = ci + 1; cs[3] = ci;
  9434. cs[0] = tmp1; cs[1] = tmp2;
  9435. break;
  9436. case 2:
  9437. ps[12] = ps[15]; ps[13] = pi + 7; ps[14] = pi + 6; ps[15] = pi + 5;
  9438. ps[ 8] = ps[11]; ps[ 9] = pi + 8; ps[10] = pi + 11; ps[11] = pi + 4;
  9439. ps[ 4] = ps[7]; ps[ 5] = pi + 9; ps[ 6] = pi + 10; ps[ 7] = pi + 3;
  9440. ps[ 0] = ps[3]; ps[ 1] = pi; ps[ 2] = pi + 1; ps[ 3] = pi + 2;
  9441. cs[2] = cs[3]; cs[3] = ci + 1;
  9442. cs[0] = cs[1]; cs[1] = ci;
  9443. break;
  9444. case 3:
  9445. ps[12] = ps[0]; ps[13] = ps[1]; ps[14] = ps[2]; ps[15] = ps[3];
  9446. ps[ 8] = pi; ps[ 9] = pi + 9; ps[10] = pi + 8; ps[11] = pi + 7;
  9447. ps[ 4] = pi + 1; ps[ 5] = pi + 10; ps[ 6] = pi + 11; ps[ 7] = pi + 6;
  9448. ps[ 0] = pi + 2; ps[ 1] = pi + 3; ps[ 2] = pi + 4; ps[ 3] = pi + 5;
  9449. cs[2] = cs[0]; cs[3] = cs[1];
  9450. cs[0] = ci; cs[1] = ci + 1;
  9451. break;
  9452. }
  9453. mesh.figures.push({
  9454. type: 'patch',
  9455. coords: new Int32Array(ps), // making copies of ps and cs
  9456. colors: new Int32Array(cs)
  9457. });
  9458. }
  9459. }
  9460. function updateBounds(mesh) {
  9461. var minX = mesh.coords[0][0], minY = mesh.coords[0][1],
  9462. maxX = minX, maxY = minY;
  9463. for (var i = 1, ii = mesh.coords.length; i < ii; i++) {
  9464. var x = mesh.coords[i][0], y = mesh.coords[i][1];
  9465. minX = minX > x ? x : minX;
  9466. minY = minY > y ? y : minY;
  9467. maxX = maxX < x ? x : maxX;
  9468. maxY = maxY < y ? y : maxY;
  9469. }
  9470. mesh.bounds = [minX, minY, maxX, maxY];
  9471. }
  9472. function packData(mesh) {
  9473. var i, ii, j, jj;
  9474. var coords = mesh.coords;
  9475. var coordsPacked = new Float32Array(coords.length * 2);
  9476. for (i = 0, j = 0, ii = coords.length; i < ii; i++) {
  9477. var xy = coords[i];
  9478. coordsPacked[j++] = xy[0];
  9479. coordsPacked[j++] = xy[1];
  9480. }
  9481. mesh.coords = coordsPacked;
  9482. var colors = mesh.colors;
  9483. var colorsPacked = new Uint8Array(colors.length * 3);
  9484. for (i = 0, j = 0, ii = colors.length; i < ii; i++) {
  9485. var c = colors[i];
  9486. colorsPacked[j++] = c[0];
  9487. colorsPacked[j++] = c[1];
  9488. colorsPacked[j++] = c[2];
  9489. }
  9490. mesh.colors = colorsPacked;
  9491. var figures = mesh.figures;
  9492. for (i = 0, ii = figures.length; i < ii; i++) {
  9493. var figure = figures[i], ps = figure.coords, cs = figure.colors;
  9494. for (j = 0, jj = ps.length; j < jj; j++) {
  9495. ps[j] *= 2;
  9496. cs[j] *= 3;
  9497. }
  9498. }
  9499. }
  9500. function Mesh(stream, matrix, xref, res) {
  9501. assert(isStream(stream), 'Mesh data is not a stream');
  9502. var dict = stream.dict;
  9503. this.matrix = matrix;
  9504. this.shadingType = dict.get('ShadingType');
  9505. this.type = 'Pattern';
  9506. this.bbox = dict.get('BBox');
  9507. var cs = dict.get('ColorSpace', 'CS');
  9508. cs = ColorSpace.parse(cs, xref, res);
  9509. this.cs = cs;
  9510. this.background = dict.has('Background') ?
  9511. cs.getRgb(dict.get('Background'), 0) : null;
  9512. var fnObj = dict.get('Function');
  9513. var fn = fnObj ? PDFFunction.parseArray(xref, fnObj) : null;
  9514. this.coords = [];
  9515. this.colors = [];
  9516. this.figures = [];
  9517. var decodeContext = {
  9518. bitsPerCoordinate: dict.get('BitsPerCoordinate'),
  9519. bitsPerComponent: dict.get('BitsPerComponent'),
  9520. bitsPerFlag: dict.get('BitsPerFlag'),
  9521. decode: dict.get('Decode'),
  9522. colorFn: fn,
  9523. colorSpace: cs,
  9524. numComps: fn ? 1 : cs.numComps
  9525. };
  9526. var reader = new MeshStreamReader(stream, decodeContext);
  9527. var patchMesh = false;
  9528. switch (this.shadingType) {
  9529. case PatternType.FREE_FORM_MESH:
  9530. decodeType4Shading(this, reader);
  9531. break;
  9532. case PatternType.LATTICE_FORM_MESH:
  9533. var verticesPerRow = dict.get('VerticesPerRow') | 0;
  9534. assert(verticesPerRow >= 2, 'Invalid VerticesPerRow');
  9535. decodeType5Shading(this, reader, verticesPerRow);
  9536. break;
  9537. case PatternType.COONS_PATCH_MESH:
  9538. decodeType6Shading(this, reader);
  9539. patchMesh = true;
  9540. break;
  9541. case PatternType.TENSOR_PATCH_MESH:
  9542. decodeType7Shading(this, reader);
  9543. patchMesh = true;
  9544. break;
  9545. default:
  9546. error('Unsupported mesh type.');
  9547. break;
  9548. }
  9549. if (patchMesh) {
  9550. // dirty bounds calculation for determining, how dense shall be triangles
  9551. updateBounds(this);
  9552. for (var i = 0, ii = this.figures.length; i < ii; i++) {
  9553. buildFigureFromPatch(this, i);
  9554. }
  9555. }
  9556. // calculate bounds
  9557. updateBounds(this);
  9558. packData(this);
  9559. }
  9560. Mesh.prototype = {
  9561. getIR: function Mesh_getIR() {
  9562. return ['Mesh', this.shadingType, this.coords, this.colors, this.figures,
  9563. this.bounds, this.matrix, this.bbox, this.background];
  9564. }
  9565. };
  9566. return Mesh;
  9567. })();
  9568. Shadings.Dummy = (function DummyClosure() {
  9569. function Dummy() {
  9570. this.type = 'Pattern';
  9571. }
  9572. Dummy.prototype = {
  9573. getIR: function Dummy_getIR() {
  9574. return ['Dummy'];
  9575. }
  9576. };
  9577. return Dummy;
  9578. })();
  9579. function getTilingPatternIR(operatorList, dict, args) {
  9580. var matrix = dict.get('Matrix');
  9581. var bbox = dict.get('BBox');
  9582. var xstep = dict.get('XStep');
  9583. var ystep = dict.get('YStep');
  9584. var paintType = dict.get('PaintType');
  9585. var tilingType = dict.get('TilingType');
  9586. return [
  9587. 'TilingPattern', args, operatorList, matrix, bbox, xstep, ystep,
  9588. paintType, tilingType
  9589. ];
  9590. }
  9591. var PartialEvaluator = (function PartialEvaluatorClosure() {
  9592. function PartialEvaluator(pdfManager, xref, handler, pageIndex,
  9593. uniquePrefix, idCounters, fontCache) {
  9594. this.pdfManager = pdfManager;
  9595. this.xref = xref;
  9596. this.handler = handler;
  9597. this.pageIndex = pageIndex;
  9598. this.uniquePrefix = uniquePrefix;
  9599. this.idCounters = idCounters;
  9600. this.fontCache = fontCache;
  9601. }
  9602. // Trying to minimize Date.now() usage and check every 100 time
  9603. var TIME_SLOT_DURATION_MS = 20;
  9604. var CHECK_TIME_EVERY = 100;
  9605. function TimeSlotManager() {
  9606. this.reset();
  9607. }
  9608. TimeSlotManager.prototype = {
  9609. check: function TimeSlotManager_check() {
  9610. if (++this.checked < CHECK_TIME_EVERY) {
  9611. return false;
  9612. }
  9613. this.checked = 0;
  9614. return this.endTime <= Date.now();
  9615. },
  9616. reset: function TimeSlotManager_reset() {
  9617. this.endTime = Date.now() + TIME_SLOT_DURATION_MS;
  9618. this.checked = 0;
  9619. }
  9620. };
  9621. var deferred = Promise.resolve();
  9622. var TILING_PATTERN = 1, SHADING_PATTERN = 2;
  9623. PartialEvaluator.prototype = {
  9624. hasBlendModes: function PartialEvaluator_hasBlendModes(resources) {
  9625. if (!isDict(resources)) {
  9626. return false;
  9627. }
  9628. var processed = Object.create(null);
  9629. if (resources.objId) {
  9630. processed[resources.objId] = true;
  9631. }
  9632. var nodes = [resources];
  9633. while (nodes.length) {
  9634. var key;
  9635. var node = nodes.shift();
  9636. // First check the current resources for blend modes.
  9637. var graphicStates = node.get('ExtGState');
  9638. if (isDict(graphicStates)) {
  9639. graphicStates = graphicStates.getAll();
  9640. for (key in graphicStates) {
  9641. var graphicState = graphicStates[key];
  9642. var bm = graphicState['BM'];
  9643. if (isName(bm) && bm.name !== 'Normal') {
  9644. return true;
  9645. }
  9646. }
  9647. }
  9648. // Descend into the XObjects to look for more resources and blend modes.
  9649. var xObjects = node.get('XObject');
  9650. if (!isDict(xObjects)) {
  9651. continue;
  9652. }
  9653. xObjects = xObjects.getAll();
  9654. for (key in xObjects) {
  9655. var xObject = xObjects[key];
  9656. if (!isStream(xObject)) {
  9657. continue;
  9658. }
  9659. if (xObject.dict.objId) {
  9660. if (processed[xObject.dict.objId]) {
  9661. // stream has objId and is processed already
  9662. continue;
  9663. }
  9664. processed[xObject.dict.objId] = true;
  9665. }
  9666. var xResources = xObject.dict.get('Resources');
  9667. // Checking objId to detect an infinite loop.
  9668. if (isDict(xResources) &&
  9669. (!xResources.objId || !processed[xResources.objId])) {
  9670. nodes.push(xResources);
  9671. if (xResources.objId) {
  9672. processed[xResources.objId] = true;
  9673. }
  9674. }
  9675. }
  9676. }
  9677. return false;
  9678. },
  9679. buildFormXObject: function PartialEvaluator_buildFormXObject(resources,
  9680. xobj, smask,
  9681. operatorList,
  9682. initialState) {
  9683. var matrix = xobj.dict.get('Matrix');
  9684. var bbox = xobj.dict.get('BBox');
  9685. var group = xobj.dict.get('Group');
  9686. if (group) {
  9687. var groupOptions = {
  9688. matrix: matrix,
  9689. bbox: bbox,
  9690. smask: smask,
  9691. isolated: false,
  9692. knockout: false
  9693. };
  9694. var groupSubtype = group.get('S');
  9695. var colorSpace;
  9696. if (isName(groupSubtype) && groupSubtype.name === 'Transparency') {
  9697. groupOptions.isolated = (group.get('I') || false);
  9698. groupOptions.knockout = (group.get('K') || false);
  9699. colorSpace = (group.has('CS') ?
  9700. ColorSpace.parse(group.get('CS'), this.xref, resources) : null);
  9701. }
  9702. if (smask && smask.backdrop) {
  9703. colorSpace = colorSpace || ColorSpace.singletons.rgb;
  9704. smask.backdrop = colorSpace.getRgb(smask.backdrop, 0);
  9705. }
  9706. operatorList.addOp(OPS.beginGroup, [groupOptions]);
  9707. }
  9708. operatorList.addOp(OPS.paintFormXObjectBegin, [matrix, bbox]);
  9709. return this.getOperatorList(xobj,
  9710. (xobj.dict.get('Resources') || resources), operatorList, initialState).
  9711. then(function () {
  9712. operatorList.addOp(OPS.paintFormXObjectEnd, []);
  9713. if (group) {
  9714. operatorList.addOp(OPS.endGroup, [groupOptions]);
  9715. }
  9716. });
  9717. },
  9718. buildPaintImageXObject:
  9719. function PartialEvaluator_buildPaintImageXObject(resources, image,
  9720. inline, operatorList,
  9721. cacheKey, imageCache) {
  9722. var self = this;
  9723. var dict = image.dict;
  9724. var w = dict.get('Width', 'W');
  9725. var h = dict.get('Height', 'H');
  9726. if (!(w && isNum(w)) || !(h && isNum(h))) {
  9727. warn('Image dimensions are missing, or not numbers.');
  9728. return;
  9729. }
  9730. if (PDFJS.maxImageSize !== -1 && w * h > PDFJS.maxImageSize) {
  9731. warn('Image exceeded maximum allowed size and was removed.');
  9732. return;
  9733. }
  9734. var imageMask = (dict.get('ImageMask', 'IM') || false);
  9735. var imgData, args;
  9736. if (imageMask) {
  9737. // This depends on a tmpCanvas being filled with the
  9738. // current fillStyle, such that processing the pixel
  9739. // data can't be done here. Instead of creating a
  9740. // complete PDFImage, only read the information needed
  9741. // for later.
  9742. var width = dict.get('Width', 'W');
  9743. var height = dict.get('Height', 'H');
  9744. var bitStrideLength = (width + 7) >> 3;
  9745. var imgArray = image.getBytes(bitStrideLength * height);
  9746. var decode = dict.get('Decode', 'D');
  9747. var inverseDecode = (!!decode && decode[0] > 0);
  9748. imgData = PDFImage.createMask(imgArray, width, height,
  9749. image instanceof DecodeStream,
  9750. inverseDecode);
  9751. imgData.cached = true;
  9752. args = [imgData];
  9753. operatorList.addOp(OPS.paintImageMaskXObject, args);
  9754. if (cacheKey) {
  9755. imageCache[cacheKey] = {
  9756. fn: OPS.paintImageMaskXObject,
  9757. args: args
  9758. };
  9759. }
  9760. return;
  9761. }
  9762. var softMask = (dict.get('SMask', 'SM') || false);
  9763. var mask = (dict.get('Mask') || false);
  9764. var SMALL_IMAGE_DIMENSIONS = 200;
  9765. // Inlining small images into the queue as RGB data
  9766. if (inline && !softMask && !mask && !(image instanceof JpegStream) &&
  9767. (w + h) < SMALL_IMAGE_DIMENSIONS) {
  9768. var imageObj = new PDFImage(this.xref, resources, image,
  9769. inline, null, null);
  9770. // We force the use of RGBA_32BPP images here, because we can't handle
  9771. // any other kind.
  9772. imgData = imageObj.createImageData(/* forceRGBA = */ true);
  9773. operatorList.addOp(OPS.paintInlineImageXObject, [imgData]);
  9774. return;
  9775. }
  9776. // If there is no imageMask, create the PDFImage and a lot
  9777. // of image processing can be done here.
  9778. var uniquePrefix = (this.uniquePrefix || '');
  9779. var objId = 'img_' + uniquePrefix + (++this.idCounters.obj);
  9780. operatorList.addDependency(objId);
  9781. args = [objId, w, h];
  9782. if (!softMask && !mask && image instanceof JpegStream &&
  9783. image.isNativelySupported(this.xref, resources)) {
  9784. // These JPEGs don't need any more processing so we can just send it.
  9785. operatorList.addOp(OPS.paintJpegXObject, args);
  9786. this.handler.send('obj',
  9787. [objId, this.pageIndex, 'JpegStream', image.getIR()]);
  9788. return;
  9789. }
  9790. PDFImage.buildImage(self.handler, self.xref, resources, image, inline).
  9791. then(function(imageObj) {
  9792. var imgData = imageObj.createImageData(/* forceRGBA = */ false);
  9793. self.handler.send('obj', [objId, self.pageIndex, 'Image', imgData],
  9794. [imgData.data.buffer]);
  9795. }).then(undefined, function (reason) {
  9796. warn('Unable to decode image: ' + reason);
  9797. self.handler.send('obj', [objId, self.pageIndex, 'Image', null]);
  9798. });
  9799. operatorList.addOp(OPS.paintImageXObject, args);
  9800. if (cacheKey) {
  9801. imageCache[cacheKey] = {
  9802. fn: OPS.paintImageXObject,
  9803. args: args
  9804. };
  9805. }
  9806. },
  9807. handleSMask: function PartialEvaluator_handleSmask(smask, resources,
  9808. operatorList,
  9809. stateManager) {
  9810. var smaskContent = smask.get('G');
  9811. var smaskOptions = {
  9812. subtype: smask.get('S').name,
  9813. backdrop: smask.get('BC')
  9814. };
  9815. return this.buildFormXObject(resources, smaskContent, smaskOptions,
  9816. operatorList, stateManager.state.clone());
  9817. },
  9818. handleTilingType:
  9819. function PartialEvaluator_handleTilingType(fn, args, resources,
  9820. pattern, patternDict,
  9821. operatorList) {
  9822. // Create an IR of the pattern code.
  9823. var tilingOpList = new OperatorList();
  9824. return this.getOperatorList(pattern,
  9825. (patternDict.get('Resources') || resources), tilingOpList).
  9826. then(function () {
  9827. // Add the dependencies to the parent operator list so they are
  9828. // resolved before sub operator list is executed synchronously.
  9829. operatorList.addDependencies(tilingOpList.dependencies);
  9830. operatorList.addOp(fn, getTilingPatternIR({
  9831. fnArray: tilingOpList.fnArray,
  9832. argsArray: tilingOpList.argsArray
  9833. }, patternDict, args));
  9834. });
  9835. },
  9836. handleSetFont:
  9837. function PartialEvaluator_handleSetFont(resources, fontArgs, fontRef,
  9838. operatorList, state) {
  9839. // TODO(mack): Not needed?
  9840. var fontName;
  9841. if (fontArgs) {
  9842. fontArgs = fontArgs.slice();
  9843. fontName = fontArgs[0].name;
  9844. }
  9845. var self = this;
  9846. return this.loadFont(fontName, fontRef, this.xref, resources).then(
  9847. function (translated) {
  9848. if (!translated.font.isType3Font) {
  9849. return translated;
  9850. }
  9851. return translated.loadType3Data(self, resources, operatorList).then(
  9852. function () {
  9853. return translated;
  9854. });
  9855. }).then(function (translated) {
  9856. state.font = translated.font;
  9857. translated.send(self.handler);
  9858. return translated.loadedName;
  9859. });
  9860. },
  9861. handleText: function PartialEvaluator_handleText(chars, state) {
  9862. var font = state.font;
  9863. var glyphs = font.charsToGlyphs(chars);
  9864. var isAddToPathSet = !!(state.textRenderingMode &
  9865. TextRenderingMode.ADD_TO_PATH_FLAG);
  9866. if (font.data && (isAddToPathSet || PDFJS.disableFontFace)) {
  9867. var buildPath = function (fontChar) {
  9868. if (!font.renderer.hasBuiltPath(fontChar)) {
  9869. var path = font.renderer.getPathJs(fontChar);
  9870. this.handler.send('commonobj', [
  9871. font.loadedName + '_path_' + fontChar,
  9872. 'FontPath',
  9873. path
  9874. ]);
  9875. }
  9876. }.bind(this);
  9877. for (var i = 0, ii = glyphs.length; i < ii; i++) {
  9878. var glyph = glyphs[i];
  9879. if (glyph === null) {
  9880. continue;
  9881. }
  9882. buildPath(glyph.fontChar);
  9883. // If the glyph has an accent we need to build a path for its
  9884. // fontChar too, otherwise CanvasGraphics_paintChar will fail.
  9885. var accent = glyph.accent;
  9886. if (accent && accent.fontChar) {
  9887. buildPath(accent.fontChar);
  9888. }
  9889. }
  9890. }
  9891. return glyphs;
  9892. },
  9893. setGState: function PartialEvaluator_setGState(resources, gState,
  9894. operatorList, xref,
  9895. stateManager) {
  9896. // This array holds the converted/processed state data.
  9897. var gStateObj = [];
  9898. var gStateMap = gState.map;
  9899. var self = this;
  9900. var promise = Promise.resolve();
  9901. for (var key in gStateMap) {
  9902. var value = gStateMap[key];
  9903. switch (key) {
  9904. case 'Type':
  9905. break;
  9906. case 'LW':
  9907. case 'LC':
  9908. case 'LJ':
  9909. case 'ML':
  9910. case 'D':
  9911. case 'RI':
  9912. case 'FL':
  9913. case 'CA':
  9914. case 'ca':
  9915. gStateObj.push([key, value]);
  9916. break;
  9917. case 'Font':
  9918. promise = promise.then(function () {
  9919. return self.handleSetFont(resources, null, value[0],
  9920. operatorList, stateManager.state).
  9921. then(function (loadedName) {
  9922. operatorList.addDependency(loadedName);
  9923. gStateObj.push([key, [loadedName, value[1]]]);
  9924. });
  9925. });
  9926. break;
  9927. case 'BM':
  9928. gStateObj.push([key, value]);
  9929. break;
  9930. case 'SMask':
  9931. if (isName(value) && value.name === 'None') {
  9932. gStateObj.push([key, false]);
  9933. break;
  9934. }
  9935. var dict = xref.fetchIfRef(value);
  9936. if (isDict(dict)) {
  9937. promise = promise.then(function () {
  9938. return self.handleSMask(dict, resources, operatorList,
  9939. stateManager);
  9940. });
  9941. gStateObj.push([key, true]);
  9942. } else {
  9943. warn('Unsupported SMask type');
  9944. }
  9945. break;
  9946. // Only generate info log messages for the following since
  9947. // they are unlikely to have a big impact on the rendering.
  9948. case 'OP':
  9949. case 'op':
  9950. case 'OPM':
  9951. case 'BG':
  9952. case 'BG2':
  9953. case 'UCR':
  9954. case 'UCR2':
  9955. case 'TR':
  9956. case 'TR2':
  9957. case 'HT':
  9958. case 'SM':
  9959. case 'SA':
  9960. case 'AIS':
  9961. case 'TK':
  9962. // TODO implement these operators.
  9963. info('graphic state operator ' + key);
  9964. break;
  9965. default:
  9966. info('Unknown graphic state operator ' + key);
  9967. break;
  9968. }
  9969. }
  9970. return promise.then(function () {
  9971. if (gStateObj.length >= 0) {
  9972. operatorList.addOp(OPS.setGState, [gStateObj]);
  9973. }
  9974. });
  9975. },
  9976. loadFont: function PartialEvaluator_loadFont(fontName, font, xref,
  9977. resources) {
  9978. function errorFont() {
  9979. return Promise.resolve(new TranslatedFont('g_font_error',
  9980. new ErrorFont('Font ' + fontName + ' is not available'), font));
  9981. }
  9982. var fontRef;
  9983. if (font) { // Loading by ref.
  9984. assert(isRef(font));
  9985. fontRef = font;
  9986. } else { // Loading by name.
  9987. var fontRes = resources.get('Font');
  9988. if (fontRes) {
  9989. fontRef = fontRes.getRaw(fontName);
  9990. } else {
  9991. warn('fontRes not available');
  9992. return errorFont();
  9993. }
  9994. }
  9995. if (!fontRef) {
  9996. warn('fontRef not available');
  9997. return errorFont();
  9998. }
  9999. if (this.fontCache.has(fontRef)) {
  10000. return this.fontCache.get(fontRef);
  10001. }
  10002. font = xref.fetchIfRef(fontRef);
  10003. if (!isDict(font)) {
  10004. return errorFont();
  10005. }
  10006. // We are holding font.translated references just for fontRef that are not
  10007. // dictionaries (Dict). See explanation below.
  10008. if (font.translated) {
  10009. return font.translated;
  10010. }
  10011. var fontCapability = createPromiseCapability();
  10012. var preEvaluatedFont = this.preEvaluateFont(font, xref);
  10013. var descriptor = preEvaluatedFont.descriptor;
  10014. var fontID = fontRef.num + '_' + fontRef.gen;
  10015. if (isDict(descriptor)) {
  10016. if (!descriptor.fontAliases) {
  10017. descriptor.fontAliases = Object.create(null);
  10018. }
  10019. var fontAliases = descriptor.fontAliases;
  10020. var hash = preEvaluatedFont.hash;
  10021. if (fontAliases[hash]) {
  10022. var aliasFontRef = fontAliases[hash].aliasRef;
  10023. if (aliasFontRef && this.fontCache.has(aliasFontRef)) {
  10024. this.fontCache.putAlias(fontRef, aliasFontRef);
  10025. return this.fontCache.get(fontRef);
  10026. }
  10027. }
  10028. if (!fontAliases[hash]) {
  10029. fontAliases[hash] = {
  10030. fontID: Font.getFontID()
  10031. };
  10032. }
  10033. fontAliases[hash].aliasRef = fontRef;
  10034. fontID = fontAliases[hash].fontID;
  10035. }
  10036. // Workaround for bad PDF generators that don't reference fonts
  10037. // properly, i.e. by not using an object identifier.
  10038. // Check if the fontRef is a Dict (as opposed to a standard object),
  10039. // in which case we don't cache the font and instead reference it by
  10040. // fontName in font.loadedName below.
  10041. var fontRefIsDict = isDict(fontRef);
  10042. if (!fontRefIsDict) {
  10043. this.fontCache.put(fontRef, fontCapability.promise);
  10044. }
  10045. // Keep track of each font we translated so the caller can
  10046. // load them asynchronously before calling display on a page.
  10047. font.loadedName = 'g_font_' + (fontRefIsDict ?
  10048. fontName.replace(/\W/g, '') : fontID);
  10049. font.translated = fontCapability.promise;
  10050. // TODO move promises into translate font
  10051. var translatedPromise;
  10052. try {
  10053. translatedPromise = Promise.resolve(
  10054. this.translateFont(preEvaluatedFont, xref));
  10055. } catch (e) {
  10056. translatedPromise = Promise.reject(e);
  10057. }
  10058. translatedPromise.then(function (translatedFont) {
  10059. if (translatedFont.fontType !== undefined) {
  10060. var xrefFontStats = xref.stats.fontTypes;
  10061. xrefFontStats[translatedFont.fontType] = true;
  10062. }
  10063. fontCapability.resolve(new TranslatedFont(font.loadedName,
  10064. translatedFont, font));
  10065. }, function (reason) {
  10066. // TODO fontCapability.reject?
  10067. UnsupportedManager.notify(UNSUPPORTED_FEATURES.font);
  10068. try {
  10069. // error, but it's still nice to have font type reported
  10070. var descriptor = preEvaluatedFont.descriptor;
  10071. var fontFile3 = descriptor && descriptor.get('FontFile3');
  10072. var subtype = fontFile3 && fontFile3.get('Subtype');
  10073. var fontType = getFontType(preEvaluatedFont.type,
  10074. subtype && subtype.name);
  10075. var xrefFontStats = xref.stats.fontTypes;
  10076. xrefFontStats[fontType] = true;
  10077. } catch (ex) { }
  10078. fontCapability.resolve(new TranslatedFont(font.loadedName,
  10079. new ErrorFont(reason instanceof Error ? reason.message : reason),
  10080. font));
  10081. });
  10082. return fontCapability.promise;
  10083. },
  10084. buildPath: function PartialEvaluator_buildPath(operatorList, fn, args) {
  10085. var lastIndex = operatorList.length - 1;
  10086. if (!args) {
  10087. args = [];
  10088. }
  10089. if (lastIndex < 0 ||
  10090. operatorList.fnArray[lastIndex] !== OPS.constructPath) {
  10091. operatorList.addOp(OPS.constructPath, [[fn], args]);
  10092. } else {
  10093. var opArgs = operatorList.argsArray[lastIndex];
  10094. opArgs[0].push(fn);
  10095. Array.prototype.push.apply(opArgs[1], args);
  10096. }
  10097. },
  10098. handleColorN: function PartialEvaluator_handleColorN(operatorList, fn, args,
  10099. cs, patterns, resources, xref) {
  10100. // compile tiling patterns
  10101. var patternName = args[args.length - 1];
  10102. // SCN/scn applies patterns along with normal colors
  10103. var pattern;
  10104. if (isName(patternName) &&
  10105. (pattern = patterns.get(patternName.name))) {
  10106. var dict = (isStream(pattern) ? pattern.dict : pattern);
  10107. var typeNum = dict.get('PatternType');
  10108. if (typeNum === TILING_PATTERN) {
  10109. var color = cs.base ? cs.base.getRgb(args, 0) : null;
  10110. return this.handleTilingType(fn, color, resources, pattern,
  10111. dict, operatorList);
  10112. } else if (typeNum === SHADING_PATTERN) {
  10113. var shading = dict.get('Shading');
  10114. var matrix = dict.get('Matrix');
  10115. pattern = Pattern.parseShading(shading, matrix, xref, resources);
  10116. operatorList.addOp(fn, pattern.getIR());
  10117. return Promise.resolve();
  10118. } else {
  10119. return Promise.reject('Unknown PatternType: ' + typeNum);
  10120. }
  10121. }
  10122. // TODO shall we fail here?
  10123. operatorList.addOp(fn, args);
  10124. return Promise.resolve();
  10125. },
  10126. getOperatorList: function PartialEvaluator_getOperatorList(stream,
  10127. resources,
  10128. operatorList,
  10129. initialState) {
  10130. var self = this;
  10131. var xref = this.xref;
  10132. var imageCache = {};
  10133. assert(operatorList);
  10134. resources = (resources || Dict.empty);
  10135. var xobjs = (resources.get('XObject') || Dict.empty);
  10136. var patterns = (resources.get('Pattern') || Dict.empty);
  10137. var stateManager = new StateManager(initialState || new EvalState());
  10138. var preprocessor = new EvaluatorPreprocessor(stream, xref, stateManager);
  10139. var timeSlotManager = new TimeSlotManager();
  10140. return new Promise(function next(resolve, reject) {
  10141. timeSlotManager.reset();
  10142. var stop, operation = {}, i, ii, cs;
  10143. while (!(stop = timeSlotManager.check())) {
  10144. // The arguments parsed by read() are used beyond this loop, so we
  10145. // cannot reuse the same array on each iteration. Therefore we pass
  10146. // in |null| as the initial value (see the comment on
  10147. // EvaluatorPreprocessor_read() for why).
  10148. operation.args = null;
  10149. if (!(preprocessor.read(operation))) {
  10150. break;
  10151. }
  10152. var args = operation.args;
  10153. var fn = operation.fn;
  10154. switch (fn | 0) {
  10155. case OPS.paintXObject:
  10156. if (args[0].code) {
  10157. break;
  10158. }
  10159. // eagerly compile XForm objects
  10160. var name = args[0].name;
  10161. if (imageCache[name] !== undefined) {
  10162. operatorList.addOp(imageCache[name].fn, imageCache[name].args);
  10163. args = null;
  10164. continue;
  10165. }
  10166. var xobj = xobjs.get(name);
  10167. if (xobj) {
  10168. assert(isStream(xobj), 'XObject should be a stream');
  10169. var type = xobj.dict.get('Subtype');
  10170. assert(isName(type),
  10171. 'XObject should have a Name subtype');
  10172. if (type.name === 'Form') {
  10173. stateManager.save();
  10174. return self.buildFormXObject(resources, xobj, null,
  10175. operatorList,
  10176. stateManager.state.clone()).
  10177. then(function () {
  10178. stateManager.restore();
  10179. next(resolve, reject);
  10180. }, reject);
  10181. } else if (type.name === 'Image') {
  10182. self.buildPaintImageXObject(resources, xobj, false,
  10183. operatorList, name, imageCache);
  10184. args = null;
  10185. continue;
  10186. } else if (type.name === 'PS') {
  10187. // PostScript XObjects are unused when viewing documents.
  10188. // See section 4.7.1 of Adobe's PDF reference.
  10189. info('Ignored XObject subtype PS');
  10190. continue;
  10191. } else {
  10192. error('Unhandled XObject subtype ' + type.name);
  10193. }
  10194. }
  10195. break;
  10196. case OPS.setFont:
  10197. var fontSize = args[1];
  10198. // eagerly collect all fonts
  10199. return self.handleSetFont(resources, args, null,
  10200. operatorList, stateManager.state).
  10201. then(function (loadedName) {
  10202. operatorList.addDependency(loadedName);
  10203. operatorList.addOp(OPS.setFont, [loadedName, fontSize]);
  10204. next(resolve, reject);
  10205. }, reject);
  10206. case OPS.endInlineImage:
  10207. var cacheKey = args[0].cacheKey;
  10208. if (cacheKey) {
  10209. var cacheEntry = imageCache[cacheKey];
  10210. if (cacheEntry !== undefined) {
  10211. operatorList.addOp(cacheEntry.fn, cacheEntry.args);
  10212. args = null;
  10213. continue;
  10214. }
  10215. }
  10216. self.buildPaintImageXObject(resources, args[0], true,
  10217. operatorList, cacheKey, imageCache);
  10218. args = null;
  10219. continue;
  10220. case OPS.showText:
  10221. args[0] = self.handleText(args[0], stateManager.state);
  10222. break;
  10223. case OPS.showSpacedText:
  10224. var arr = args[0];
  10225. var combinedGlyphs = [];
  10226. var arrLength = arr.length;
  10227. for (i = 0; i < arrLength; ++i) {
  10228. var arrItem = arr[i];
  10229. if (isString(arrItem)) {
  10230. Array.prototype.push.apply(combinedGlyphs,
  10231. self.handleText(arrItem, stateManager.state));
  10232. } else if (isNum(arrItem)) {
  10233. combinedGlyphs.push(arrItem);
  10234. }
  10235. }
  10236. args[0] = combinedGlyphs;
  10237. fn = OPS.showText;
  10238. break;
  10239. case OPS.nextLineShowText:
  10240. operatorList.addOp(OPS.nextLine);
  10241. args[0] = self.handleText(args[0], stateManager.state);
  10242. fn = OPS.showText;
  10243. break;
  10244. case OPS.nextLineSetSpacingShowText:
  10245. operatorList.addOp(OPS.nextLine);
  10246. operatorList.addOp(OPS.setWordSpacing, [args.shift()]);
  10247. operatorList.addOp(OPS.setCharSpacing, [args.shift()]);
  10248. args[0] = self.handleText(args[0], stateManager.state);
  10249. fn = OPS.showText;
  10250. break;
  10251. case OPS.setTextRenderingMode:
  10252. stateManager.state.textRenderingMode = args[0];
  10253. break;
  10254. case OPS.setFillColorSpace:
  10255. stateManager.state.fillColorSpace =
  10256. ColorSpace.parse(args[0], xref, resources);
  10257. continue;
  10258. case OPS.setStrokeColorSpace:
  10259. stateManager.state.strokeColorSpace =
  10260. ColorSpace.parse(args[0], xref, resources);
  10261. continue;
  10262. case OPS.setFillColor:
  10263. cs = stateManager.state.fillColorSpace;
  10264. args = cs.getRgb(args, 0);
  10265. fn = OPS.setFillRGBColor;
  10266. break;
  10267. case OPS.setStrokeColor:
  10268. cs = stateManager.state.strokeColorSpace;
  10269. args = cs.getRgb(args, 0);
  10270. fn = OPS.setStrokeRGBColor;
  10271. break;
  10272. case OPS.setFillGray:
  10273. stateManager.state.fillColorSpace = ColorSpace.singletons.gray;
  10274. args = ColorSpace.singletons.gray.getRgb(args, 0);
  10275. fn = OPS.setFillRGBColor;
  10276. break;
  10277. case OPS.setStrokeGray:
  10278. stateManager.state.strokeColorSpace = ColorSpace.singletons.gray;
  10279. args = ColorSpace.singletons.gray.getRgb(args, 0);
  10280. fn = OPS.setStrokeRGBColor;
  10281. break;
  10282. case OPS.setFillCMYKColor:
  10283. stateManager.state.fillColorSpace = ColorSpace.singletons.cmyk;
  10284. args = ColorSpace.singletons.cmyk.getRgb(args, 0);
  10285. fn = OPS.setFillRGBColor;
  10286. break;
  10287. case OPS.setStrokeCMYKColor:
  10288. stateManager.state.strokeColorSpace = ColorSpace.singletons.cmyk;
  10289. args = ColorSpace.singletons.cmyk.getRgb(args, 0);
  10290. fn = OPS.setStrokeRGBColor;
  10291. break;
  10292. case OPS.setFillRGBColor:
  10293. stateManager.state.fillColorSpace = ColorSpace.singletons.rgb;
  10294. args = ColorSpace.singletons.rgb.getRgb(args, 0);
  10295. break;
  10296. case OPS.setStrokeRGBColor:
  10297. stateManager.state.strokeColorSpace = ColorSpace.singletons.rgb;
  10298. args = ColorSpace.singletons.rgb.getRgb(args, 0);
  10299. break;
  10300. case OPS.setFillColorN:
  10301. cs = stateManager.state.fillColorSpace;
  10302. if (cs.name === 'Pattern') {
  10303. return self.handleColorN(operatorList, OPS.setFillColorN,
  10304. args, cs, patterns, resources, xref).then(function() {
  10305. next(resolve, reject);
  10306. }, reject);
  10307. }
  10308. args = cs.getRgb(args, 0);
  10309. fn = OPS.setFillRGBColor;
  10310. break;
  10311. case OPS.setStrokeColorN:
  10312. cs = stateManager.state.strokeColorSpace;
  10313. if (cs.name === 'Pattern') {
  10314. return self.handleColorN(operatorList, OPS.setStrokeColorN,
  10315. args, cs, patterns, resources, xref).then(function() {
  10316. next(resolve, reject);
  10317. }, reject);
  10318. }
  10319. args = cs.getRgb(args, 0);
  10320. fn = OPS.setStrokeRGBColor;
  10321. break;
  10322. case OPS.shadingFill:
  10323. var shadingRes = resources.get('Shading');
  10324. if (!shadingRes) {
  10325. error('No shading resource found');
  10326. }
  10327. var shading = shadingRes.get(args[0].name);
  10328. if (!shading) {
  10329. error('No shading object found');
  10330. }
  10331. var shadingFill = Pattern.parseShading(shading, null, xref,
  10332. resources);
  10333. var patternIR = shadingFill.getIR();
  10334. args = [patternIR];
  10335. fn = OPS.shadingFill;
  10336. break;
  10337. case OPS.setGState:
  10338. var dictName = args[0];
  10339. var extGState = resources.get('ExtGState');
  10340. if (!isDict(extGState) || !extGState.has(dictName.name)) {
  10341. break;
  10342. }
  10343. var gState = extGState.get(dictName.name);
  10344. return self.setGState(resources, gState, operatorList, xref,
  10345. stateManager).then(function() {
  10346. next(resolve, reject);
  10347. }, reject);
  10348. case OPS.moveTo:
  10349. case OPS.lineTo:
  10350. case OPS.curveTo:
  10351. case OPS.curveTo2:
  10352. case OPS.curveTo3:
  10353. case OPS.closePath:
  10354. self.buildPath(operatorList, fn, args);
  10355. continue;
  10356. case OPS.rectangle:
  10357. self.buildPath(operatorList, fn, args);
  10358. continue;
  10359. }
  10360. operatorList.addOp(fn, args);
  10361. }
  10362. if (stop) {
  10363. deferred.then(function () {
  10364. next(resolve, reject);
  10365. });
  10366. return;
  10367. }
  10368. // Some PDFs don't close all restores inside object/form.
  10369. // Closing those for them.
  10370. for (i = 0, ii = preprocessor.savedStatesDepth; i < ii; i++) {
  10371. operatorList.addOp(OPS.restore, []);
  10372. }
  10373. resolve();
  10374. });
  10375. },
  10376. getTextContent: function PartialEvaluator_getTextContent(stream, resources,
  10377. stateManager) {
  10378. stateManager = (stateManager || new StateManager(new TextState()));
  10379. var textContent = {
  10380. items: [],
  10381. styles: Object.create(null)
  10382. };
  10383. var bidiTexts = textContent.items;
  10384. var SPACE_FACTOR = 0.3;
  10385. var MULTI_SPACE_FACTOR = 1.5;
  10386. var self = this;
  10387. var xref = this.xref;
  10388. resources = (xref.fetchIfRef(resources) || Dict.empty);
  10389. // The xobj is parsed iff it's needed, e.g. if there is a `DO` cmd.
  10390. var xobjs = null;
  10391. var xobjsCache = {};
  10392. var preprocessor = new EvaluatorPreprocessor(stream, xref, stateManager);
  10393. var textState;
  10394. function newTextChunk() {
  10395. var font = textState.font;
  10396. if (!(font.loadedName in textContent.styles)) {
  10397. textContent.styles[font.loadedName] = {
  10398. fontFamily: font.fallbackName,
  10399. ascent: font.ascent,
  10400. descent: font.descent,
  10401. vertical: font.vertical
  10402. };
  10403. }
  10404. return {
  10405. // |str| is initially an array which we push individual chars to, and
  10406. // then runBidi() overwrites it with the final string.
  10407. str: [],
  10408. dir: null,
  10409. width: 0,
  10410. height: 0,
  10411. transform: null,
  10412. fontName: font.loadedName
  10413. };
  10414. }
  10415. function runBidi(textChunk) {
  10416. var str = textChunk.str.join('');
  10417. var bidiResult = PDFJS.bidi(str, -1, textState.font.vertical);
  10418. textChunk.str = bidiResult.str;
  10419. textChunk.dir = bidiResult.dir;
  10420. return textChunk;
  10421. }
  10422. function handleSetFont(fontName, fontRef) {
  10423. return self.loadFont(fontName, fontRef, xref, resources).
  10424. then(function (translated) {
  10425. textState.font = translated.font;
  10426. textState.fontMatrix = translated.font.fontMatrix ||
  10427. FONT_IDENTITY_MATRIX;
  10428. });
  10429. }
  10430. function buildTextGeometry(chars, textChunk) {
  10431. var font = textState.font;
  10432. textChunk = textChunk || newTextChunk();
  10433. if (!textChunk.transform) {
  10434. // 9.4.4 Text Space Details
  10435. var tsm = [textState.fontSize * textState.textHScale, 0,
  10436. 0, textState.fontSize,
  10437. 0, textState.textRise];
  10438. var trm = textChunk.transform = Util.transform(textState.ctm,
  10439. Util.transform(textState.textMatrix, tsm));
  10440. if (!font.vertical) {
  10441. textChunk.height = Math.sqrt(trm[2] * trm[2] + trm[3] * trm[3]);
  10442. } else {
  10443. textChunk.width = Math.sqrt(trm[0] * trm[0] + trm[1] * trm[1]);
  10444. }
  10445. }
  10446. var width = 0;
  10447. var height = 0;
  10448. var glyphs = font.charsToGlyphs(chars);
  10449. var defaultVMetrics = font.defaultVMetrics;
  10450. for (var i = 0; i < glyphs.length; i++) {
  10451. var glyph = glyphs[i];
  10452. if (!glyph) { // Previous glyph was a space.
  10453. width += textState.wordSpacing * textState.textHScale;
  10454. continue;
  10455. }
  10456. var vMetricX = null;
  10457. var vMetricY = null;
  10458. var glyphWidth = null;
  10459. if (font.vertical) {
  10460. if (glyph.vmetric) {
  10461. glyphWidth = glyph.vmetric[0];
  10462. vMetricX = glyph.vmetric[1];
  10463. vMetricY = glyph.vmetric[2];
  10464. } else {
  10465. glyphWidth = glyph.width;
  10466. vMetricX = glyph.width * 0.5;
  10467. vMetricY = defaultVMetrics[2];
  10468. }
  10469. } else {
  10470. glyphWidth = glyph.width;
  10471. }
  10472. var glyphUnicode = glyph.unicode;
  10473. if (NormalizedUnicodes[glyphUnicode] !== undefined) {
  10474. glyphUnicode = NormalizedUnicodes[glyphUnicode];
  10475. }
  10476. glyphUnicode = reverseIfRtl(glyphUnicode);
  10477. // The following will calculate the x and y of the individual glyphs.
  10478. // if (font.vertical) {
  10479. // tsm[4] -= vMetricX * Math.abs(textState.fontSize) *
  10480. // textState.fontMatrix[0];
  10481. // tsm[5] -= vMetricY * textState.fontSize *
  10482. // textState.fontMatrix[0];
  10483. // }
  10484. // var trm = Util.transform(textState.textMatrix, tsm);
  10485. // var pt = Util.applyTransform([trm[4], trm[5]], textState.ctm);
  10486. // var x = pt[0];
  10487. // var y = pt[1];
  10488. var tx = 0;
  10489. var ty = 0;
  10490. if (!font.vertical) {
  10491. var w0 = glyphWidth * textState.fontMatrix[0];
  10492. tx = (w0 * textState.fontSize + textState.charSpacing) *
  10493. textState.textHScale;
  10494. width += tx;
  10495. } else {
  10496. var w1 = glyphWidth * textState.fontMatrix[0];
  10497. ty = w1 * textState.fontSize + textState.charSpacing;
  10498. height += ty;
  10499. }
  10500. textState.translateTextMatrix(tx, ty);
  10501. textChunk.str.push(glyphUnicode);
  10502. }
  10503. var a = textState.textLineMatrix[0];
  10504. var b = textState.textLineMatrix[1];
  10505. var scaleLineX = Math.sqrt(a * a + b * b);
  10506. a = textState.ctm[0];
  10507. b = textState.ctm[1];
  10508. var scaleCtmX = Math.sqrt(a * a + b * b);
  10509. if (!font.vertical) {
  10510. textChunk.width += width * scaleCtmX * scaleLineX;
  10511. } else {
  10512. textChunk.height += Math.abs(height * scaleCtmX * scaleLineX);
  10513. }
  10514. return textChunk;
  10515. }
  10516. var timeSlotManager = new TimeSlotManager();
  10517. return new Promise(function next(resolve, reject) {
  10518. timeSlotManager.reset();
  10519. var stop, operation = {}, args = [];
  10520. while (!(stop = timeSlotManager.check())) {
  10521. // The arguments parsed by read() are not used beyond this loop, so
  10522. // we can reuse the same array on every iteration, thus avoiding
  10523. // unnecessary allocations.
  10524. args.length = 0;
  10525. operation.args = args;
  10526. if (!(preprocessor.read(operation))) {
  10527. break;
  10528. }
  10529. textState = stateManager.state;
  10530. var fn = operation.fn;
  10531. args = operation.args;
  10532. switch (fn | 0) {
  10533. case OPS.setFont:
  10534. textState.fontSize = args[1];
  10535. return handleSetFont(args[0].name).then(function() {
  10536. next(resolve, reject);
  10537. }, reject);
  10538. case OPS.setTextRise:
  10539. textState.textRise = args[0];
  10540. break;
  10541. case OPS.setHScale:
  10542. textState.textHScale = args[0] / 100;
  10543. break;
  10544. case OPS.setLeading:
  10545. textState.leading = args[0];
  10546. break;
  10547. case OPS.moveText:
  10548. textState.translateTextLineMatrix(args[0], args[1]);
  10549. textState.textMatrix = textState.textLineMatrix.slice();
  10550. break;
  10551. case OPS.setLeadingMoveText:
  10552. textState.leading = -args[1];
  10553. textState.translateTextLineMatrix(args[0], args[1]);
  10554. textState.textMatrix = textState.textLineMatrix.slice();
  10555. break;
  10556. case OPS.nextLine:
  10557. textState.carriageReturn();
  10558. break;
  10559. case OPS.setTextMatrix:
  10560. textState.setTextMatrix(args[0], args[1], args[2], args[3],
  10561. args[4], args[5]);
  10562. textState.setTextLineMatrix(args[0], args[1], args[2], args[3],
  10563. args[4], args[5]);
  10564. break;
  10565. case OPS.setCharSpacing:
  10566. textState.charSpacing = args[0];
  10567. break;
  10568. case OPS.setWordSpacing:
  10569. textState.wordSpacing = args[0];
  10570. break;
  10571. case OPS.beginText:
  10572. textState.textMatrix = IDENTITY_MATRIX.slice();
  10573. textState.textLineMatrix = IDENTITY_MATRIX.slice();
  10574. break;
  10575. case OPS.showSpacedText:
  10576. var items = args[0];
  10577. var textChunk = newTextChunk();
  10578. var offset;
  10579. for (var j = 0, jj = items.length; j < jj; j++) {
  10580. if (typeof items[j] === 'string') {
  10581. buildTextGeometry(items[j], textChunk);
  10582. } else {
  10583. var val = items[j] / 1000;
  10584. if (!textState.font.vertical) {
  10585. offset = -val * textState.fontSize * textState.textHScale *
  10586. textState.textMatrix[0];
  10587. textState.translateTextMatrix(offset, 0);
  10588. textChunk.width += offset;
  10589. } else {
  10590. offset = -val * textState.fontSize *
  10591. textState.textMatrix[3];
  10592. textState.translateTextMatrix(0, offset);
  10593. textChunk.height += offset;
  10594. }
  10595. if (items[j] < 0 && textState.font.spaceWidth > 0) {
  10596. var fakeSpaces = -items[j] / textState.font.spaceWidth;
  10597. if (fakeSpaces > MULTI_SPACE_FACTOR) {
  10598. fakeSpaces = Math.round(fakeSpaces);
  10599. while (fakeSpaces--) {
  10600. textChunk.str.push(' ');
  10601. }
  10602. } else if (fakeSpaces > SPACE_FACTOR) {
  10603. textChunk.str.push(' ');
  10604. }
  10605. }
  10606. }
  10607. }
  10608. bidiTexts.push(runBidi(textChunk));
  10609. break;
  10610. case OPS.showText:
  10611. bidiTexts.push(runBidi(buildTextGeometry(args[0])));
  10612. break;
  10613. case OPS.nextLineShowText:
  10614. textState.carriageReturn();
  10615. bidiTexts.push(runBidi(buildTextGeometry(args[0])));
  10616. break;
  10617. case OPS.nextLineSetSpacingShowText:
  10618. textState.wordSpacing = args[0];
  10619. textState.charSpacing = args[1];
  10620. textState.carriageReturn();
  10621. bidiTexts.push(runBidi(buildTextGeometry(args[2])));
  10622. break;
  10623. case OPS.paintXObject:
  10624. if (args[0].code) {
  10625. break;
  10626. }
  10627. if (!xobjs) {
  10628. xobjs = (resources.get('XObject') || Dict.empty);
  10629. }
  10630. var name = args[0].name;
  10631. if (xobjsCache.key === name) {
  10632. if (xobjsCache.texts) {
  10633. Util.appendToArray(bidiTexts, xobjsCache.texts.items);
  10634. Util.extendObj(textContent.styles, xobjsCache.texts.styles);
  10635. }
  10636. break;
  10637. }
  10638. var xobj = xobjs.get(name);
  10639. if (!xobj) {
  10640. break;
  10641. }
  10642. assert(isStream(xobj), 'XObject should be a stream');
  10643. var type = xobj.dict.get('Subtype');
  10644. assert(isName(type),
  10645. 'XObject should have a Name subtype');
  10646. if ('Form' !== type.name) {
  10647. xobjsCache.key = name;
  10648. xobjsCache.texts = null;
  10649. break;
  10650. }
  10651. stateManager.save();
  10652. var matrix = xobj.dict.get('Matrix');
  10653. if (isArray(matrix) && matrix.length === 6) {
  10654. stateManager.transform(matrix);
  10655. }
  10656. return self.getTextContent(xobj,
  10657. xobj.dict.get('Resources') || resources, stateManager).
  10658. then(function (formTextContent) {
  10659. Util.appendToArray(bidiTexts, formTextContent.items);
  10660. Util.extendObj(textContent.styles, formTextContent.styles);
  10661. stateManager.restore();
  10662. xobjsCache.key = name;
  10663. xobjsCache.texts = formTextContent;
  10664. next(resolve, reject);
  10665. }, reject);
  10666. case OPS.setGState:
  10667. var dictName = args[0];
  10668. var extGState = resources.get('ExtGState');
  10669. if (!isDict(extGState) || !extGState.has(dictName.name)) {
  10670. break;
  10671. }
  10672. var gsStateMap = extGState.get(dictName.name);
  10673. var gsStateFont = null;
  10674. for (var key in gsStateMap) {
  10675. if (key === 'Font') {
  10676. assert(!gsStateFont);
  10677. gsStateFont = gsStateMap[key];
  10678. }
  10679. }
  10680. if (gsStateFont) {
  10681. textState.fontSize = gsStateFont[1];
  10682. return handleSetFont(gsStateFont[0]).then(function() {
  10683. next(resolve, reject);
  10684. }, reject);
  10685. }
  10686. break;
  10687. } // switch
  10688. } // while
  10689. if (stop) {
  10690. deferred.then(function () {
  10691. next(resolve, reject);
  10692. });
  10693. return;
  10694. }
  10695. resolve(textContent);
  10696. });
  10697. },
  10698. extractDataStructures: function
  10699. partialEvaluatorExtractDataStructures(dict, baseDict,
  10700. xref, properties) {
  10701. // 9.10.2
  10702. var toUnicode = (dict.get('ToUnicode') || baseDict.get('ToUnicode'));
  10703. if (toUnicode) {
  10704. properties.toUnicode = this.readToUnicode(toUnicode);
  10705. }
  10706. if (properties.composite) {
  10707. // CIDSystemInfo helps to match CID to glyphs
  10708. var cidSystemInfo = dict.get('CIDSystemInfo');
  10709. if (isDict(cidSystemInfo)) {
  10710. properties.cidSystemInfo = {
  10711. registry: cidSystemInfo.get('Registry'),
  10712. ordering: cidSystemInfo.get('Ordering'),
  10713. supplement: cidSystemInfo.get('Supplement')
  10714. };
  10715. }
  10716. var cidToGidMap = dict.get('CIDToGIDMap');
  10717. if (isStream(cidToGidMap)) {
  10718. properties.cidToGidMap = this.readCidToGidMap(cidToGidMap);
  10719. }
  10720. }
  10721. // Based on 9.6.6 of the spec the encoding can come from multiple places
  10722. // and depends on the font type. The base encoding and differences are
  10723. // read here, but the encoding that is actually used is chosen during
  10724. // glyph mapping in the font.
  10725. // TODO: Loading the built in encoding in the font would allow the
  10726. // differences to be merged in here not require us to hold on to it.
  10727. var differences = [];
  10728. var baseEncodingName = null;
  10729. var encoding;
  10730. if (dict.has('Encoding')) {
  10731. encoding = dict.get('Encoding');
  10732. if (isDict(encoding)) {
  10733. baseEncodingName = encoding.get('BaseEncoding');
  10734. baseEncodingName = (isName(baseEncodingName) ?
  10735. baseEncodingName.name : null);
  10736. // Load the differences between the base and original
  10737. if (encoding.has('Differences')) {
  10738. var diffEncoding = encoding.get('Differences');
  10739. var index = 0;
  10740. for (var j = 0, jj = diffEncoding.length; j < jj; j++) {
  10741. var data = diffEncoding[j];
  10742. if (isNum(data)) {
  10743. index = data;
  10744. } else {
  10745. differences[index++] = data.name;
  10746. }
  10747. }
  10748. }
  10749. } else if (isName(encoding)) {
  10750. baseEncodingName = encoding.name;
  10751. } else {
  10752. error('Encoding is not a Name nor a Dict');
  10753. }
  10754. // According to table 114 if the encoding is a named encoding it must be
  10755. // one of these predefined encodings.
  10756. if ((baseEncodingName !== 'MacRomanEncoding' &&
  10757. baseEncodingName !== 'MacExpertEncoding' &&
  10758. baseEncodingName !== 'WinAnsiEncoding')) {
  10759. baseEncodingName = null;
  10760. }
  10761. }
  10762. if (baseEncodingName) {
  10763. properties.defaultEncoding = Encodings[baseEncodingName].slice();
  10764. } else {
  10765. encoding = (properties.type === 'TrueType' ?
  10766. Encodings.WinAnsiEncoding : Encodings.StandardEncoding);
  10767. // The Symbolic attribute can be misused for regular fonts
  10768. // Heuristic: we have to check if the font is a standard one also
  10769. if (!!(properties.flags & FontFlags.Symbolic)) {
  10770. encoding = Encodings.MacRomanEncoding;
  10771. if (!properties.file) {
  10772. if (/Symbol/i.test(properties.name)) {
  10773. encoding = Encodings.SymbolSetEncoding;
  10774. } else if (/Dingbats/i.test(properties.name)) {
  10775. encoding = Encodings.ZapfDingbatsEncoding;
  10776. }
  10777. }
  10778. }
  10779. properties.defaultEncoding = encoding;
  10780. }
  10781. properties.differences = differences;
  10782. properties.baseEncodingName = baseEncodingName;
  10783. properties.dict = dict;
  10784. },
  10785. readToUnicode: function PartialEvaluator_readToUnicode(toUnicode) {
  10786. var cmap, cmapObj = toUnicode;
  10787. if (isName(cmapObj)) {
  10788. cmap = CMapFactory.create(cmapObj,
  10789. { url: PDFJS.cMapUrl, packed: PDFJS.cMapPacked }, null);
  10790. if (cmap instanceof IdentityCMap) {
  10791. return new IdentityToUnicodeMap(0, 0xFFFF);
  10792. }
  10793. return new ToUnicodeMap(cmap.getMap());
  10794. } else if (isStream(cmapObj)) {
  10795. cmap = CMapFactory.create(cmapObj,
  10796. { url: PDFJS.cMapUrl, packed: PDFJS.cMapPacked }, null);
  10797. if (cmap instanceof IdentityCMap) {
  10798. return new IdentityToUnicodeMap(0, 0xFFFF);
  10799. }
  10800. cmap = cmap.getMap();
  10801. // Convert UTF-16BE
  10802. // NOTE: cmap can be a sparse array, so use forEach instead of for(;;)
  10803. // to iterate over all keys.
  10804. cmap.forEach(function(token, i) {
  10805. var str = [];
  10806. for (var k = 0; k < token.length; k += 2) {
  10807. var w1 = (token.charCodeAt(k) << 8) | token.charCodeAt(k + 1);
  10808. if ((w1 & 0xF800) !== 0xD800) { // w1 < 0xD800 || w1 > 0xDFFF
  10809. str.push(w1);
  10810. continue;
  10811. }
  10812. k += 2;
  10813. var w2 = (token.charCodeAt(k) << 8) | token.charCodeAt(k + 1);
  10814. str.push(((w1 & 0x3ff) << 10) + (w2 & 0x3ff) + 0x10000);
  10815. }
  10816. cmap[i] = String.fromCharCode.apply(String, str);
  10817. });
  10818. return new ToUnicodeMap(cmap);
  10819. }
  10820. return null;
  10821. },
  10822. readCidToGidMap: function PartialEvaluator_readCidToGidMap(cidToGidStream) {
  10823. // Extract the encoding from the CIDToGIDMap
  10824. var glyphsData = cidToGidStream.getBytes();
  10825. // Set encoding 0 to later verify the font has an encoding
  10826. var result = [];
  10827. for (var j = 0, jj = glyphsData.length; j < jj; j++) {
  10828. var glyphID = (glyphsData[j++] << 8) | glyphsData[j];
  10829. if (glyphID === 0) {
  10830. continue;
  10831. }
  10832. var code = j >> 1;
  10833. result[code] = glyphID;
  10834. }
  10835. return result;
  10836. },
  10837. extractWidths: function PartialEvaluator_extractWidths(dict, xref,
  10838. descriptor,
  10839. properties) {
  10840. var glyphsWidths = [];
  10841. var defaultWidth = 0;
  10842. var glyphsVMetrics = [];
  10843. var defaultVMetrics;
  10844. var i, ii, j, jj, start, code, widths;
  10845. if (properties.composite) {
  10846. defaultWidth = dict.get('DW') || 1000;
  10847. widths = dict.get('W');
  10848. if (widths) {
  10849. for (i = 0, ii = widths.length; i < ii; i++) {
  10850. start = widths[i++];
  10851. code = xref.fetchIfRef(widths[i]);
  10852. if (isArray(code)) {
  10853. for (j = 0, jj = code.length; j < jj; j++) {
  10854. glyphsWidths[start++] = code[j];
  10855. }
  10856. } else {
  10857. var width = widths[++i];
  10858. for (j = start; j <= code; j++) {
  10859. glyphsWidths[j] = width;
  10860. }
  10861. }
  10862. }
  10863. }
  10864. if (properties.vertical) {
  10865. var vmetrics = (dict.get('DW2') || [880, -1000]);
  10866. defaultVMetrics = [vmetrics[1], defaultWidth * 0.5, vmetrics[0]];
  10867. vmetrics = dict.get('W2');
  10868. if (vmetrics) {
  10869. for (i = 0, ii = vmetrics.length; i < ii; i++) {
  10870. start = vmetrics[i++];
  10871. code = xref.fetchIfRef(vmetrics[i]);
  10872. if (isArray(code)) {
  10873. for (j = 0, jj = code.length; j < jj; j++) {
  10874. glyphsVMetrics[start++] = [code[j++], code[j++], code[j]];
  10875. }
  10876. } else {
  10877. var vmetric = [vmetrics[++i], vmetrics[++i], vmetrics[++i]];
  10878. for (j = start; j <= code; j++) {
  10879. glyphsVMetrics[j] = vmetric;
  10880. }
  10881. }
  10882. }
  10883. }
  10884. }
  10885. } else {
  10886. var firstChar = properties.firstChar;
  10887. widths = dict.get('Widths');
  10888. if (widths) {
  10889. j = firstChar;
  10890. for (i = 0, ii = widths.length; i < ii; i++) {
  10891. glyphsWidths[j++] = widths[i];
  10892. }
  10893. defaultWidth = (parseFloat(descriptor.get('MissingWidth')) || 0);
  10894. } else {
  10895. // Trying get the BaseFont metrics (see comment above).
  10896. var baseFontName = dict.get('BaseFont');
  10897. if (isName(baseFontName)) {
  10898. var metrics = this.getBaseFontMetrics(baseFontName.name);
  10899. glyphsWidths = this.buildCharCodeToWidth(metrics.widths,
  10900. properties);
  10901. defaultWidth = metrics.defaultWidth;
  10902. }
  10903. }
  10904. }
  10905. // Heuristic: detection of monospace font by checking all non-zero widths
  10906. var isMonospace = true;
  10907. var firstWidth = defaultWidth;
  10908. for (var glyph in glyphsWidths) {
  10909. var glyphWidth = glyphsWidths[glyph];
  10910. if (!glyphWidth) {
  10911. continue;
  10912. }
  10913. if (!firstWidth) {
  10914. firstWidth = glyphWidth;
  10915. continue;
  10916. }
  10917. if (firstWidth !== glyphWidth) {
  10918. isMonospace = false;
  10919. break;
  10920. }
  10921. }
  10922. if (isMonospace) {
  10923. properties.flags |= FontFlags.FixedPitch;
  10924. }
  10925. properties.defaultWidth = defaultWidth;
  10926. properties.widths = glyphsWidths;
  10927. properties.defaultVMetrics = defaultVMetrics;
  10928. properties.vmetrics = glyphsVMetrics;
  10929. },
  10930. isSerifFont: function PartialEvaluator_isSerifFont(baseFontName) {
  10931. // Simulating descriptor flags attribute
  10932. var fontNameWoStyle = baseFontName.split('-')[0];
  10933. return (fontNameWoStyle in serifFonts) ||
  10934. (fontNameWoStyle.search(/serif/gi) !== -1);
  10935. },
  10936. getBaseFontMetrics: function PartialEvaluator_getBaseFontMetrics(name) {
  10937. var defaultWidth = 0;
  10938. var widths = [];
  10939. var monospace = false;
  10940. var lookupName = (stdFontMap[name] || name);
  10941. if (!(lookupName in Metrics)) {
  10942. // Use default fonts for looking up font metrics if the passed
  10943. // font is not a base font
  10944. if (this.isSerifFont(name)) {
  10945. lookupName = 'Times-Roman';
  10946. } else {
  10947. lookupName = 'Helvetica';
  10948. }
  10949. }
  10950. var glyphWidths = Metrics[lookupName];
  10951. if (isNum(glyphWidths)) {
  10952. defaultWidth = glyphWidths;
  10953. monospace = true;
  10954. } else {
  10955. widths = glyphWidths;
  10956. }
  10957. return {
  10958. defaultWidth: defaultWidth,
  10959. monospace: monospace,
  10960. widths: widths
  10961. };
  10962. },
  10963. buildCharCodeToWidth:
  10964. function PartialEvaluator_bulildCharCodeToWidth(widthsByGlyphName,
  10965. properties) {
  10966. var widths = Object.create(null);
  10967. var differences = properties.differences;
  10968. var encoding = properties.defaultEncoding;
  10969. for (var charCode = 0; charCode < 256; charCode++) {
  10970. if (charCode in differences &&
  10971. widthsByGlyphName[differences[charCode]]) {
  10972. widths[charCode] = widthsByGlyphName[differences[charCode]];
  10973. continue;
  10974. }
  10975. if (charCode in encoding && widthsByGlyphName[encoding[charCode]]) {
  10976. widths[charCode] = widthsByGlyphName[encoding[charCode]];
  10977. continue;
  10978. }
  10979. }
  10980. return widths;
  10981. },
  10982. preEvaluateFont: function PartialEvaluator_preEvaluateFont(dict, xref) {
  10983. var baseDict = dict;
  10984. var type = dict.get('Subtype');
  10985. assert(isName(type), 'invalid font Subtype');
  10986. var composite = false;
  10987. var uint8array;
  10988. if (type.name === 'Type0') {
  10989. // If font is a composite
  10990. // - get the descendant font
  10991. // - set the type according to the descendant font
  10992. // - get the FontDescriptor from the descendant font
  10993. var df = dict.get('DescendantFonts');
  10994. if (!df) {
  10995. error('Descendant fonts are not specified');
  10996. }
  10997. dict = (isArray(df) ? xref.fetchIfRef(df[0]) : df);
  10998. type = dict.get('Subtype');
  10999. assert(isName(type), 'invalid font Subtype');
  11000. composite = true;
  11001. }
  11002. var descriptor = dict.get('FontDescriptor');
  11003. if (descriptor) {
  11004. var hash = new MurmurHash3_64();
  11005. var encoding = baseDict.getRaw('Encoding');
  11006. if (isName(encoding)) {
  11007. hash.update(encoding.name);
  11008. } else if (isRef(encoding)) {
  11009. hash.update(encoding.num + '_' + encoding.gen);
  11010. } else if (isDict(encoding)) {
  11011. var keys = encoding.getKeys();
  11012. for (var i = 0, ii = keys.length; i < ii; i++) {
  11013. var entry = encoding.getRaw(keys[i]);
  11014. if (isName(entry)) {
  11015. hash.update(entry.name);
  11016. } else if (isRef(entry)) {
  11017. hash.update(entry.num + '_' + entry.gen);
  11018. } else if (isArray(entry)) { // 'Differences' entry.
  11019. // Ideally we should check the contents of the array, but to avoid
  11020. // parsing it here and then again in |extractDataStructures|,
  11021. // we only use the array length for now (fixes bug1157493.pdf).
  11022. hash.update(entry.length.toString());
  11023. }
  11024. }
  11025. }
  11026. var toUnicode = dict.get('ToUnicode') || baseDict.get('ToUnicode');
  11027. if (isStream(toUnicode)) {
  11028. var stream = toUnicode.str || toUnicode;
  11029. uint8array = stream.buffer ?
  11030. new Uint8Array(stream.buffer.buffer, 0, stream.bufferLength) :
  11031. new Uint8Array(stream.bytes.buffer,
  11032. stream.start, stream.end - stream.start);
  11033. hash.update(uint8array);
  11034. } else if (isName(toUnicode)) {
  11035. hash.update(toUnicode.name);
  11036. }
  11037. var widths = dict.get('Widths') || baseDict.get('Widths');
  11038. if (widths) {
  11039. uint8array = new Uint8Array(new Uint32Array(widths).buffer);
  11040. hash.update(uint8array);
  11041. }
  11042. }
  11043. return {
  11044. descriptor: descriptor,
  11045. dict: dict,
  11046. baseDict: baseDict,
  11047. composite: composite,
  11048. type: type.name,
  11049. hash: hash ? hash.hexdigest() : ''
  11050. };
  11051. },
  11052. translateFont: function PartialEvaluator_translateFont(preEvaluatedFont,
  11053. xref) {
  11054. var baseDict = preEvaluatedFont.baseDict;
  11055. var dict = preEvaluatedFont.dict;
  11056. var composite = preEvaluatedFont.composite;
  11057. var descriptor = preEvaluatedFont.descriptor;
  11058. var type = preEvaluatedFont.type;
  11059. var maxCharIndex = (composite ? 0xFFFF : 0xFF);
  11060. var properties;
  11061. if (!descriptor) {
  11062. if (type === 'Type3') {
  11063. // FontDescriptor is only required for Type3 fonts when the document
  11064. // is a tagged pdf. Create a barbebones one to get by.
  11065. descriptor = new Dict(null);
  11066. descriptor.set('FontName', Name.get(type));
  11067. } else {
  11068. // Before PDF 1.5 if the font was one of the base 14 fonts, having a
  11069. // FontDescriptor was not required.
  11070. // This case is here for compatibility.
  11071. var baseFontName = dict.get('BaseFont');
  11072. if (!isName(baseFontName)) {
  11073. error('Base font is not specified');
  11074. }
  11075. // Using base font name as a font name.
  11076. baseFontName = baseFontName.name.replace(/[,_]/g, '-');
  11077. var metrics = this.getBaseFontMetrics(baseFontName);
  11078. // Simulating descriptor flags attribute
  11079. var fontNameWoStyle = baseFontName.split('-')[0];
  11080. var flags =
  11081. (this.isSerifFont(fontNameWoStyle) ? FontFlags.Serif : 0) |
  11082. (metrics.monospace ? FontFlags.FixedPitch : 0) |
  11083. (symbolsFonts[fontNameWoStyle] ? FontFlags.Symbolic :
  11084. FontFlags.Nonsymbolic);
  11085. properties = {
  11086. type: type,
  11087. name: baseFontName,
  11088. widths: metrics.widths,
  11089. defaultWidth: metrics.defaultWidth,
  11090. flags: flags,
  11091. firstChar: 0,
  11092. lastChar: maxCharIndex
  11093. };
  11094. this.extractDataStructures(dict, dict, xref, properties);
  11095. properties.widths = this.buildCharCodeToWidth(metrics.widths,
  11096. properties);
  11097. return new Font(baseFontName, null, properties);
  11098. }
  11099. }
  11100. // According to the spec if 'FontDescriptor' is declared, 'FirstChar',
  11101. // 'LastChar' and 'Widths' should exist too, but some PDF encoders seem
  11102. // to ignore this rule when a variant of a standart font is used.
  11103. // TODO Fill the width array depending on which of the base font this is
  11104. // a variant.
  11105. var firstChar = (dict.get('FirstChar') || 0);
  11106. var lastChar = (dict.get('LastChar') || maxCharIndex);
  11107. var fontName = descriptor.get('FontName');
  11108. var baseFont = dict.get('BaseFont');
  11109. // Some bad PDFs have a string as the font name.
  11110. if (isString(fontName)) {
  11111. fontName = Name.get(fontName);
  11112. }
  11113. if (isString(baseFont)) {
  11114. baseFont = Name.get(baseFont);
  11115. }
  11116. if (type !== 'Type3') {
  11117. var fontNameStr = fontName && fontName.name;
  11118. var baseFontStr = baseFont && baseFont.name;
  11119. if (fontNameStr !== baseFontStr) {
  11120. info('The FontDescriptor\'s FontName is "' + fontNameStr +
  11121. '" but should be the same as the Font\'s BaseFont "' +
  11122. baseFontStr + '"');
  11123. // Workaround for cases where e.g. fontNameStr = 'Arial' and
  11124. // baseFontStr = 'Arial,Bold' (needed when no font file is embedded).
  11125. if (fontNameStr && baseFontStr &&
  11126. baseFontStr.indexOf(fontNameStr) === 0) {
  11127. fontName = baseFont;
  11128. }
  11129. }
  11130. }
  11131. fontName = (fontName || baseFont);
  11132. assert(isName(fontName), 'invalid font name');
  11133. var fontFile = descriptor.get('FontFile', 'FontFile2', 'FontFile3');
  11134. if (fontFile) {
  11135. if (fontFile.dict) {
  11136. var subtype = fontFile.dict.get('Subtype');
  11137. if (subtype) {
  11138. subtype = subtype.name;
  11139. }
  11140. var length1 = fontFile.dict.get('Length1');
  11141. var length2 = fontFile.dict.get('Length2');
  11142. }
  11143. }
  11144. properties = {
  11145. type: type,
  11146. name: fontName.name,
  11147. subtype: subtype,
  11148. file: fontFile,
  11149. length1: length1,
  11150. length2: length2,
  11151. loadedName: baseDict.loadedName,
  11152. composite: composite,
  11153. wideChars: composite,
  11154. fixedPitch: false,
  11155. fontMatrix: (dict.get('FontMatrix') || FONT_IDENTITY_MATRIX),
  11156. firstChar: firstChar || 0,
  11157. lastChar: (lastChar || maxCharIndex),
  11158. bbox: descriptor.get('FontBBox'),
  11159. ascent: descriptor.get('Ascent'),
  11160. descent: descriptor.get('Descent'),
  11161. xHeight: descriptor.get('XHeight'),
  11162. capHeight: descriptor.get('CapHeight'),
  11163. flags: descriptor.get('Flags'),
  11164. italicAngle: descriptor.get('ItalicAngle'),
  11165. coded: false
  11166. };
  11167. if (composite) {
  11168. var cidEncoding = baseDict.get('Encoding');
  11169. if (isName(cidEncoding)) {
  11170. properties.cidEncoding = cidEncoding.name;
  11171. }
  11172. properties.cMap = CMapFactory.create(cidEncoding,
  11173. { url: PDFJS.cMapUrl, packed: PDFJS.cMapPacked }, null);
  11174. properties.vertical = properties.cMap.vertical;
  11175. }
  11176. this.extractDataStructures(dict, baseDict, xref, properties);
  11177. this.extractWidths(dict, xref, descriptor, properties);
  11178. if (type === 'Type3') {
  11179. properties.isType3Font = true;
  11180. }
  11181. return new Font(fontName.name, fontFile, properties);
  11182. }
  11183. };
  11184. return PartialEvaluator;
  11185. })();
  11186. var TranslatedFont = (function TranslatedFontClosure() {
  11187. function TranslatedFont(loadedName, font, dict) {
  11188. this.loadedName = loadedName;
  11189. this.font = font;
  11190. this.dict = dict;
  11191. this.type3Loaded = null;
  11192. this.sent = false;
  11193. }
  11194. TranslatedFont.prototype = {
  11195. send: function (handler) {
  11196. if (this.sent) {
  11197. return;
  11198. }
  11199. var fontData = this.font.exportData();
  11200. handler.send('commonobj', [
  11201. this.loadedName,
  11202. 'Font',
  11203. fontData
  11204. ]);
  11205. this.sent = true;
  11206. },
  11207. loadType3Data: function (evaluator, resources, parentOperatorList) {
  11208. assert(this.font.isType3Font);
  11209. if (this.type3Loaded) {
  11210. return this.type3Loaded;
  11211. }
  11212. var translatedFont = this.font;
  11213. var loadCharProcsPromise = Promise.resolve();
  11214. var charProcs = this.dict.get('CharProcs').getAll();
  11215. var fontResources = this.dict.get('Resources') || resources;
  11216. var charProcKeys = Object.keys(charProcs);
  11217. var charProcOperatorList = {};
  11218. for (var i = 0, n = charProcKeys.length; i < n; ++i) {
  11219. loadCharProcsPromise = loadCharProcsPromise.then(function (key) {
  11220. var glyphStream = charProcs[key];
  11221. var operatorList = new OperatorList();
  11222. return evaluator.getOperatorList(glyphStream, fontResources,
  11223. operatorList).then(function () {
  11224. charProcOperatorList[key] = operatorList.getIR();
  11225. // Add the dependencies to the parent operator list so they are
  11226. // resolved before sub operator list is executed synchronously.
  11227. parentOperatorList.addDependencies(operatorList.dependencies);
  11228. }, function (reason) {
  11229. warn('Type3 font resource \"' + key + '\" is not available');
  11230. var operatorList = new OperatorList();
  11231. charProcOperatorList[key] = operatorList.getIR();
  11232. });
  11233. }.bind(this, charProcKeys[i]));
  11234. }
  11235. this.type3Loaded = loadCharProcsPromise.then(function () {
  11236. translatedFont.charProcOperatorList = charProcOperatorList;
  11237. });
  11238. return this.type3Loaded;
  11239. }
  11240. };
  11241. return TranslatedFont;
  11242. })();
  11243. var OperatorList = (function OperatorListClosure() {
  11244. var CHUNK_SIZE = 1000;
  11245. var CHUNK_SIZE_ABOUT = CHUNK_SIZE - 5; // close to chunk size
  11246. function getTransfers(queue) {
  11247. var transfers = [];
  11248. var fnArray = queue.fnArray, argsArray = queue.argsArray;
  11249. for (var i = 0, ii = queue.length; i < ii; i++) {
  11250. switch (fnArray[i]) {
  11251. case OPS.paintInlineImageXObject:
  11252. case OPS.paintInlineImageXObjectGroup:
  11253. case OPS.paintImageMaskXObject:
  11254. var arg = argsArray[i][0]; // first param in imgData
  11255. if (!arg.cached) {
  11256. transfers.push(arg.data.buffer);
  11257. }
  11258. break;
  11259. }
  11260. }
  11261. return transfers;
  11262. }
  11263. function OperatorList(intent, messageHandler, pageIndex) {
  11264. this.messageHandler = messageHandler;
  11265. this.fnArray = [];
  11266. this.argsArray = [];
  11267. this.dependencies = {};
  11268. this.pageIndex = pageIndex;
  11269. this.intent = intent;
  11270. }
  11271. OperatorList.prototype = {
  11272. get length() {
  11273. return this.argsArray.length;
  11274. },
  11275. addOp: function(fn, args) {
  11276. this.fnArray.push(fn);
  11277. this.argsArray.push(args);
  11278. if (this.messageHandler) {
  11279. if (this.fnArray.length >= CHUNK_SIZE) {
  11280. this.flush();
  11281. } else if (this.fnArray.length >= CHUNK_SIZE_ABOUT &&
  11282. (fn === OPS.restore || fn === OPS.endText)) {
  11283. // heuristic to flush on boundary of restore or endText
  11284. this.flush();
  11285. }
  11286. }
  11287. },
  11288. addDependency: function(dependency) {
  11289. if (dependency in this.dependencies) {
  11290. return;
  11291. }
  11292. this.dependencies[dependency] = true;
  11293. this.addOp(OPS.dependency, [dependency]);
  11294. },
  11295. addDependencies: function(dependencies) {
  11296. for (var key in dependencies) {
  11297. this.addDependency(key);
  11298. }
  11299. },
  11300. addOpList: function(opList) {
  11301. Util.extendObj(this.dependencies, opList.dependencies);
  11302. for (var i = 0, ii = opList.length; i < ii; i++) {
  11303. this.addOp(opList.fnArray[i], opList.argsArray[i]);
  11304. }
  11305. },
  11306. getIR: function() {
  11307. return {
  11308. fnArray: this.fnArray,
  11309. argsArray: this.argsArray,
  11310. length: this.length
  11311. };
  11312. },
  11313. flush: function(lastChunk) {
  11314. if (this.intent !== 'oplist') {
  11315. new QueueOptimizer().optimize(this);
  11316. }
  11317. var transfers = getTransfers(this);
  11318. this.messageHandler.send('RenderPageChunk', {
  11319. operatorList: {
  11320. fnArray: this.fnArray,
  11321. argsArray: this.argsArray,
  11322. lastChunk: lastChunk,
  11323. length: this.length
  11324. },
  11325. pageIndex: this.pageIndex,
  11326. intent: this.intent
  11327. }, transfers);
  11328. this.dependencies = {};
  11329. this.fnArray.length = 0;
  11330. this.argsArray.length = 0;
  11331. }
  11332. };
  11333. return OperatorList;
  11334. })();
  11335. var StateManager = (function StateManagerClosure() {
  11336. function StateManager(initialState) {
  11337. this.state = initialState;
  11338. this.stateStack = [];
  11339. }
  11340. StateManager.prototype = {
  11341. save: function () {
  11342. var old = this.state;
  11343. this.stateStack.push(this.state);
  11344. this.state = old.clone();
  11345. },
  11346. restore: function () {
  11347. var prev = this.stateStack.pop();
  11348. if (prev) {
  11349. this.state = prev;
  11350. }
  11351. },
  11352. transform: function (args) {
  11353. this.state.ctm = Util.transform(this.state.ctm, args);
  11354. }
  11355. };
  11356. return StateManager;
  11357. })();
  11358. var TextState = (function TextStateClosure() {
  11359. function TextState() {
  11360. this.ctm = new Float32Array(IDENTITY_MATRIX);
  11361. this.fontSize = 0;
  11362. this.font = null;
  11363. this.fontMatrix = FONT_IDENTITY_MATRIX;
  11364. this.textMatrix = IDENTITY_MATRIX.slice();
  11365. this.textLineMatrix = IDENTITY_MATRIX.slice();
  11366. this.charSpacing = 0;
  11367. this.wordSpacing = 0;
  11368. this.leading = 0;
  11369. this.textHScale = 1;
  11370. this.textRise = 0;
  11371. }
  11372. TextState.prototype = {
  11373. setTextMatrix: function TextState_setTextMatrix(a, b, c, d, e, f) {
  11374. var m = this.textMatrix;
  11375. m[0] = a; m[1] = b; m[2] = c; m[3] = d; m[4] = e; m[5] = f;
  11376. },
  11377. setTextLineMatrix: function TextState_setTextMatrix(a, b, c, d, e, f) {
  11378. var m = this.textLineMatrix;
  11379. m[0] = a; m[1] = b; m[2] = c; m[3] = d; m[4] = e; m[5] = f;
  11380. },
  11381. translateTextMatrix: function TextState_translateTextMatrix(x, y) {
  11382. var m = this.textMatrix;
  11383. m[4] = m[0] * x + m[2] * y + m[4];
  11384. m[5] = m[1] * x + m[3] * y + m[5];
  11385. },
  11386. translateTextLineMatrix: function TextState_translateTextMatrix(x, y) {
  11387. var m = this.textLineMatrix;
  11388. m[4] = m[0] * x + m[2] * y + m[4];
  11389. m[5] = m[1] * x + m[3] * y + m[5];
  11390. },
  11391. calcRenderMatrix: function TextState_calcRendeMatrix(ctm) {
  11392. // 9.4.4 Text Space Details
  11393. var tsm = [this.fontSize * this.textHScale, 0,
  11394. 0, this.fontSize,
  11395. 0, this.textRise];
  11396. return Util.transform(ctm, Util.transform(this.textMatrix, tsm));
  11397. },
  11398. carriageReturn: function TextState_carriageReturn() {
  11399. this.translateTextLineMatrix(0, -this.leading);
  11400. this.textMatrix = this.textLineMatrix.slice();
  11401. },
  11402. clone: function TextState_clone() {
  11403. var clone = Object.create(this);
  11404. clone.textMatrix = this.textMatrix.slice();
  11405. clone.textLineMatrix = this.textLineMatrix.slice();
  11406. clone.fontMatrix = this.fontMatrix.slice();
  11407. return clone;
  11408. }
  11409. };
  11410. return TextState;
  11411. })();
  11412. var EvalState = (function EvalStateClosure() {
  11413. function EvalState() {
  11414. this.ctm = new Float32Array(IDENTITY_MATRIX);
  11415. this.font = null;
  11416. this.textRenderingMode = TextRenderingMode.FILL;
  11417. this.fillColorSpace = ColorSpace.singletons.gray;
  11418. this.strokeColorSpace = ColorSpace.singletons.gray;
  11419. }
  11420. EvalState.prototype = {
  11421. clone: function CanvasExtraState_clone() {
  11422. return Object.create(this);
  11423. },
  11424. };
  11425. return EvalState;
  11426. })();
  11427. var EvaluatorPreprocessor = (function EvaluatorPreprocessorClosure() {
  11428. // Specifies properties for each command
  11429. //
  11430. // If variableArgs === true: [0, `numArgs`] expected
  11431. // If variableArgs === false: exactly `numArgs` expected
  11432. var OP_MAP = {
  11433. // Graphic state
  11434. w: { id: OPS.setLineWidth, numArgs: 1, variableArgs: false },
  11435. J: { id: OPS.setLineCap, numArgs: 1, variableArgs: false },
  11436. j: { id: OPS.setLineJoin, numArgs: 1, variableArgs: false },
  11437. M: { id: OPS.setMiterLimit, numArgs: 1, variableArgs: false },
  11438. d: { id: OPS.setDash, numArgs: 2, variableArgs: false },
  11439. ri: { id: OPS.setRenderingIntent, numArgs: 1, variableArgs: false },
  11440. i: { id: OPS.setFlatness, numArgs: 1, variableArgs: false },
  11441. gs: { id: OPS.setGState, numArgs: 1, variableArgs: false },
  11442. q: { id: OPS.save, numArgs: 0, variableArgs: false },
  11443. Q: { id: OPS.restore, numArgs: 0, variableArgs: false },
  11444. cm: { id: OPS.transform, numArgs: 6, variableArgs: false },
  11445. // Path
  11446. m: { id: OPS.moveTo, numArgs: 2, variableArgs: false },
  11447. l: { id: OPS.lineTo, numArgs: 2, variableArgs: false },
  11448. c: { id: OPS.curveTo, numArgs: 6, variableArgs: false },
  11449. v: { id: OPS.curveTo2, numArgs: 4, variableArgs: false },
  11450. y: { id: OPS.curveTo3, numArgs: 4, variableArgs: false },
  11451. h: { id: OPS.closePath, numArgs: 0, variableArgs: false },
  11452. re: { id: OPS.rectangle, numArgs: 4, variableArgs: false },
  11453. S: { id: OPS.stroke, numArgs: 0, variableArgs: false },
  11454. s: { id: OPS.closeStroke, numArgs: 0, variableArgs: false },
  11455. f: { id: OPS.fill, numArgs: 0, variableArgs: false },
  11456. F: { id: OPS.fill, numArgs: 0, variableArgs: false },
  11457. 'f*': { id: OPS.eoFill, numArgs: 0, variableArgs: false },
  11458. B: { id: OPS.fillStroke, numArgs: 0, variableArgs: false },
  11459. 'B*': { id: OPS.eoFillStroke, numArgs: 0, variableArgs: false },
  11460. b: { id: OPS.closeFillStroke, numArgs: 0, variableArgs: false },
  11461. 'b*': { id: OPS.closeEOFillStroke, numArgs: 0, variableArgs: false },
  11462. n: { id: OPS.endPath, numArgs: 0, variableArgs: false },
  11463. // Clipping
  11464. W: { id: OPS.clip, numArgs: 0, variableArgs: false },
  11465. 'W*': { id: OPS.eoClip, numArgs: 0, variableArgs: false },
  11466. // Text
  11467. BT: { id: OPS.beginText, numArgs: 0, variableArgs: false },
  11468. ET: { id: OPS.endText, numArgs: 0, variableArgs: false },
  11469. Tc: { id: OPS.setCharSpacing, numArgs: 1, variableArgs: false },
  11470. Tw: { id: OPS.setWordSpacing, numArgs: 1, variableArgs: false },
  11471. Tz: { id: OPS.setHScale, numArgs: 1, variableArgs: false },
  11472. TL: { id: OPS.setLeading, numArgs: 1, variableArgs: false },
  11473. Tf: { id: OPS.setFont, numArgs: 2, variableArgs: false },
  11474. Tr: { id: OPS.setTextRenderingMode, numArgs: 1, variableArgs: false },
  11475. Ts: { id: OPS.setTextRise, numArgs: 1, variableArgs: false },
  11476. Td: { id: OPS.moveText, numArgs: 2, variableArgs: false },
  11477. TD: { id: OPS.setLeadingMoveText, numArgs: 2, variableArgs: false },
  11478. Tm: { id: OPS.setTextMatrix, numArgs: 6, variableArgs: false },
  11479. 'T*': { id: OPS.nextLine, numArgs: 0, variableArgs: false },
  11480. Tj: { id: OPS.showText, numArgs: 1, variableArgs: false },
  11481. TJ: { id: OPS.showSpacedText, numArgs: 1, variableArgs: false },
  11482. '\'': { id: OPS.nextLineShowText, numArgs: 1, variableArgs: false },
  11483. '"': { id: OPS.nextLineSetSpacingShowText, numArgs: 3,
  11484. variableArgs: false },
  11485. // Type3 fonts
  11486. d0: { id: OPS.setCharWidth, numArgs: 2, variableArgs: false },
  11487. d1: { id: OPS.setCharWidthAndBounds, numArgs: 6, variableArgs: false },
  11488. // Color
  11489. CS: { id: OPS.setStrokeColorSpace, numArgs: 1, variableArgs: false },
  11490. cs: { id: OPS.setFillColorSpace, numArgs: 1, variableArgs: false },
  11491. SC: { id: OPS.setStrokeColor, numArgs: 4, variableArgs: true },
  11492. SCN: { id: OPS.setStrokeColorN, numArgs: 33, variableArgs: true },
  11493. sc: { id: OPS.setFillColor, numArgs: 4, variableArgs: true },
  11494. scn: { id: OPS.setFillColorN, numArgs: 33, variableArgs: true },
  11495. G: { id: OPS.setStrokeGray, numArgs: 1, variableArgs: false },
  11496. g: { id: OPS.setFillGray, numArgs: 1, variableArgs: false },
  11497. RG: { id: OPS.setStrokeRGBColor, numArgs: 3, variableArgs: false },
  11498. rg: { id: OPS.setFillRGBColor, numArgs: 3, variableArgs: false },
  11499. K: { id: OPS.setStrokeCMYKColor, numArgs: 4, variableArgs: false },
  11500. k: { id: OPS.setFillCMYKColor, numArgs: 4, variableArgs: false },
  11501. // Shading
  11502. sh: { id: OPS.shadingFill, numArgs: 1, variableArgs: false },
  11503. // Images
  11504. BI: { id: OPS.beginInlineImage, numArgs: 0, variableArgs: false },
  11505. ID: { id: OPS.beginImageData, numArgs: 0, variableArgs: false },
  11506. EI: { id: OPS.endInlineImage, numArgs: 1, variableArgs: false },
  11507. // XObjects
  11508. Do: { id: OPS.paintXObject, numArgs: 1, variableArgs: false },
  11509. MP: { id: OPS.markPoint, numArgs: 1, variableArgs: false },
  11510. DP: { id: OPS.markPointProps, numArgs: 2, variableArgs: false },
  11511. BMC: { id: OPS.beginMarkedContent, numArgs: 1, variableArgs: false },
  11512. BDC: { id: OPS.beginMarkedContentProps, numArgs: 2,
  11513. variableArgs: false },
  11514. EMC: { id: OPS.endMarkedContent, numArgs: 0, variableArgs: false },
  11515. // Compatibility
  11516. BX: { id: OPS.beginCompat, numArgs: 0, variableArgs: false },
  11517. EX: { id: OPS.endCompat, numArgs: 0, variableArgs: false },
  11518. // (reserved partial commands for the lexer)
  11519. BM: null,
  11520. BD: null,
  11521. 'true': null,
  11522. fa: null,
  11523. fal: null,
  11524. fals: null,
  11525. 'false': null,
  11526. nu: null,
  11527. nul: null,
  11528. 'null': null
  11529. };
  11530. function EvaluatorPreprocessor(stream, xref, stateManager) {
  11531. // TODO(mduan): pass array of knownCommands rather than OP_MAP
  11532. // dictionary
  11533. this.parser = new Parser(new Lexer(stream, OP_MAP), false, xref);
  11534. this.stateManager = stateManager;
  11535. this.nonProcessedArgs = [];
  11536. }
  11537. EvaluatorPreprocessor.prototype = {
  11538. get savedStatesDepth() {
  11539. return this.stateManager.stateStack.length;
  11540. },
  11541. // |operation| is an object with two fields:
  11542. //
  11543. // - |fn| is an out param.
  11544. //
  11545. // - |args| is an inout param. On entry, it should have one of two values.
  11546. //
  11547. // - An empty array. This indicates that the caller is providing the
  11548. // array in which the args will be stored in. The caller should use
  11549. // this value if it can reuse a single array for each call to read().
  11550. //
  11551. // - |null|. This indicates that the caller needs this function to create
  11552. // the array in which any args are stored in. If there are zero args,
  11553. // this function will leave |operation.args| as |null| (thus avoiding
  11554. // allocations that would occur if we used an empty array to represent
  11555. // zero arguments). Otherwise, it will replace |null| with a new array
  11556. // containing the arguments. The caller should use this value if it
  11557. // cannot reuse an array for each call to read().
  11558. //
  11559. // These two modes are present because this function is very hot and so
  11560. // avoiding allocations where possible is worthwhile.
  11561. //
  11562. read: function EvaluatorPreprocessor_read(operation) {
  11563. var args = operation.args;
  11564. while (true) {
  11565. var obj = this.parser.getObj();
  11566. if (isCmd(obj)) {
  11567. var cmd = obj.cmd;
  11568. // Check that the command is valid
  11569. var opSpec = OP_MAP[cmd];
  11570. if (!opSpec) {
  11571. warn('Unknown command "' + cmd + '"');
  11572. continue;
  11573. }
  11574. var fn = opSpec.id;
  11575. var numArgs = opSpec.numArgs;
  11576. var argsLength = args !== null ? args.length : 0;
  11577. if (!opSpec.variableArgs) {
  11578. // Postscript commands can be nested, e.g. /F2 /GS2 gs 5.711 Tf
  11579. if (argsLength !== numArgs) {
  11580. var nonProcessedArgs = this.nonProcessedArgs;
  11581. while (argsLength > numArgs) {
  11582. nonProcessedArgs.push(args.shift());
  11583. argsLength--;
  11584. }
  11585. while (argsLength < numArgs && nonProcessedArgs.length !== 0) {
  11586. if (!args) {
  11587. args = [];
  11588. }
  11589. args.unshift(nonProcessedArgs.pop());
  11590. argsLength++;
  11591. }
  11592. }
  11593. if (argsLength < numArgs) {
  11594. // If we receive too few args, it's not possible to possible
  11595. // to execute the command, so skip the command
  11596. info('Command ' + fn + ': because expected ' +
  11597. numArgs + ' args, but received ' + argsLength +
  11598. ' args; skipping');
  11599. args = null;
  11600. continue;
  11601. }
  11602. } else if (argsLength > numArgs) {
  11603. info('Command ' + fn + ': expected [0,' + numArgs +
  11604. '] args, but received ' + argsLength + ' args');
  11605. }
  11606. // TODO figure out how to type-check vararg functions
  11607. this.preprocessCommand(fn, args);
  11608. operation.fn = fn;
  11609. operation.args = args;
  11610. return true;
  11611. } else {
  11612. if (isEOF(obj)) {
  11613. return false; // no more commands
  11614. }
  11615. // argument
  11616. if (obj !== null) {
  11617. if (!args) {
  11618. args = [];
  11619. }
  11620. args.push((obj instanceof Dict ? obj.getAll() : obj));
  11621. assert(args.length <= 33, 'Too many arguments');
  11622. }
  11623. }
  11624. }
  11625. },
  11626. preprocessCommand:
  11627. function EvaluatorPreprocessor_preprocessCommand(fn, args) {
  11628. switch (fn | 0) {
  11629. case OPS.save:
  11630. this.stateManager.save();
  11631. break;
  11632. case OPS.restore:
  11633. this.stateManager.restore();
  11634. break;
  11635. case OPS.transform:
  11636. this.stateManager.transform(args);
  11637. break;
  11638. }
  11639. }
  11640. };
  11641. return EvaluatorPreprocessor;
  11642. })();
  11643. var QueueOptimizer = (function QueueOptimizerClosure() {
  11644. function addState(parentState, pattern, fn) {
  11645. var state = parentState;
  11646. for (var i = 0, ii = pattern.length - 1; i < ii; i++) {
  11647. var item = pattern[i];
  11648. state = (state[item] || (state[item] = []));
  11649. }
  11650. state[pattern[pattern.length - 1]] = fn;
  11651. }
  11652. function handlePaintSolidColorImageMask(iFirstSave, count, fnArray,
  11653. argsArray) {
  11654. // Handles special case of mainly LaTeX documents which use image masks to
  11655. // draw lines with the current fill style.
  11656. // 'count' groups of (save, transform, paintImageMaskXObject, restore)+
  11657. // have been found at iFirstSave.
  11658. var iFirstPIMXO = iFirstSave + 2;
  11659. for (var i = 0; i < count; i++) {
  11660. var arg = argsArray[iFirstPIMXO + 4 * i];
  11661. var imageMask = arg.length === 1 && arg[0];
  11662. if (imageMask && imageMask.width === 1 && imageMask.height === 1 &&
  11663. (!imageMask.data.length ||
  11664. (imageMask.data.length === 1 && imageMask.data[0] === 0))) {
  11665. fnArray[iFirstPIMXO + 4 * i] = OPS.paintSolidColorImageMask;
  11666. continue;
  11667. }
  11668. break;
  11669. }
  11670. return count - i;
  11671. }
  11672. var InitialState = [];
  11673. // This replaces (save, transform, paintInlineImageXObject, restore)+
  11674. // sequences with one |paintInlineImageXObjectGroup| operation.
  11675. addState(InitialState,
  11676. [OPS.save, OPS.transform, OPS.paintInlineImageXObject, OPS.restore],
  11677. function foundInlineImageGroup(context) {
  11678. var MIN_IMAGES_IN_INLINE_IMAGES_BLOCK = 10;
  11679. var MAX_IMAGES_IN_INLINE_IMAGES_BLOCK = 200;
  11680. var MAX_WIDTH = 1000;
  11681. var IMAGE_PADDING = 1;
  11682. var fnArray = context.fnArray, argsArray = context.argsArray;
  11683. var curr = context.iCurr;
  11684. var iFirstSave = curr - 3;
  11685. var iFirstTransform = curr - 2;
  11686. var iFirstPIIXO = curr - 1;
  11687. // Look for the quartets.
  11688. var i = iFirstSave + 4;
  11689. var ii = fnArray.length;
  11690. while (i + 3 < ii) {
  11691. if (fnArray[i] !== OPS.save ||
  11692. fnArray[i + 1] !== OPS.transform ||
  11693. fnArray[i + 2] !== OPS.paintInlineImageXObject ||
  11694. fnArray[i + 3] !== OPS.restore) {
  11695. break; // ops don't match
  11696. }
  11697. i += 4;
  11698. }
  11699. // At this point, i is the index of the first op past the last valid
  11700. // quartet.
  11701. var count = Math.min((i - iFirstSave) / 4,
  11702. MAX_IMAGES_IN_INLINE_IMAGES_BLOCK);
  11703. if (count < MIN_IMAGES_IN_INLINE_IMAGES_BLOCK) {
  11704. return i;
  11705. }
  11706. // assuming that heights of those image is too small (~1 pixel)
  11707. // packing as much as possible by lines
  11708. var maxX = 0;
  11709. var map = [], maxLineHeight = 0;
  11710. var currentX = IMAGE_PADDING, currentY = IMAGE_PADDING;
  11711. var q;
  11712. for (q = 0; q < count; q++) {
  11713. var transform = argsArray[iFirstTransform + (q << 2)];
  11714. var img = argsArray[iFirstPIIXO + (q << 2)][0];
  11715. if (currentX + img.width > MAX_WIDTH) {
  11716. // starting new line
  11717. maxX = Math.max(maxX, currentX);
  11718. currentY += maxLineHeight + 2 * IMAGE_PADDING;
  11719. currentX = 0;
  11720. maxLineHeight = 0;
  11721. }
  11722. map.push({
  11723. transform: transform,
  11724. x: currentX, y: currentY,
  11725. w: img.width, h: img.height
  11726. });
  11727. currentX += img.width + 2 * IMAGE_PADDING;
  11728. maxLineHeight = Math.max(maxLineHeight, img.height);
  11729. }
  11730. var imgWidth = Math.max(maxX, currentX) + IMAGE_PADDING;
  11731. var imgHeight = currentY + maxLineHeight + IMAGE_PADDING;
  11732. var imgData = new Uint8Array(imgWidth * imgHeight * 4);
  11733. var imgRowSize = imgWidth << 2;
  11734. for (q = 0; q < count; q++) {
  11735. var data = argsArray[iFirstPIIXO + (q << 2)][0].data;
  11736. // Copy image by lines and extends pixels into padding.
  11737. var rowSize = map[q].w << 2;
  11738. var dataOffset = 0;
  11739. var offset = (map[q].x + map[q].y * imgWidth) << 2;
  11740. imgData.set(data.subarray(0, rowSize), offset - imgRowSize);
  11741. for (var k = 0, kk = map[q].h; k < kk; k++) {
  11742. imgData.set(data.subarray(dataOffset, dataOffset + rowSize), offset);
  11743. dataOffset += rowSize;
  11744. offset += imgRowSize;
  11745. }
  11746. imgData.set(data.subarray(dataOffset - rowSize, dataOffset), offset);
  11747. while (offset >= 0) {
  11748. data[offset - 4] = data[offset];
  11749. data[offset - 3] = data[offset + 1];
  11750. data[offset - 2] = data[offset + 2];
  11751. data[offset - 1] = data[offset + 3];
  11752. data[offset + rowSize] = data[offset + rowSize - 4];
  11753. data[offset + rowSize + 1] = data[offset + rowSize - 3];
  11754. data[offset + rowSize + 2] = data[offset + rowSize - 2];
  11755. data[offset + rowSize + 3] = data[offset + rowSize - 1];
  11756. offset -= imgRowSize;
  11757. }
  11758. }
  11759. // Replace queue items.
  11760. fnArray.splice(iFirstSave, count * 4, OPS.paintInlineImageXObjectGroup);
  11761. argsArray.splice(iFirstSave, count * 4,
  11762. [{ width: imgWidth, height: imgHeight, kind: ImageKind.RGBA_32BPP,
  11763. data: imgData }, map]);
  11764. return iFirstSave + 1;
  11765. });
  11766. // This replaces (save, transform, paintImageMaskXObject, restore)+
  11767. // sequences with one |paintImageMaskXObjectGroup| or one
  11768. // |paintImageMaskXObjectRepeat| operation.
  11769. addState(InitialState,
  11770. [OPS.save, OPS.transform, OPS.paintImageMaskXObject, OPS.restore],
  11771. function foundImageMaskGroup(context) {
  11772. var MIN_IMAGES_IN_MASKS_BLOCK = 10;
  11773. var MAX_IMAGES_IN_MASKS_BLOCK = 100;
  11774. var MAX_SAME_IMAGES_IN_MASKS_BLOCK = 1000;
  11775. var fnArray = context.fnArray, argsArray = context.argsArray;
  11776. var curr = context.iCurr;
  11777. var iFirstSave = curr - 3;
  11778. var iFirstTransform = curr - 2;
  11779. var iFirstPIMXO = curr - 1;
  11780. // Look for the quartets.
  11781. var i = iFirstSave + 4;
  11782. var ii = fnArray.length;
  11783. while (i + 3 < ii) {
  11784. if (fnArray[i] !== OPS.save ||
  11785. fnArray[i + 1] !== OPS.transform ||
  11786. fnArray[i + 2] !== OPS.paintImageMaskXObject ||
  11787. fnArray[i + 3] !== OPS.restore) {
  11788. break; // ops don't match
  11789. }
  11790. i += 4;
  11791. }
  11792. // At this point, i is the index of the first op past the last valid
  11793. // quartet.
  11794. var count = (i - iFirstSave) / 4;
  11795. count = handlePaintSolidColorImageMask(iFirstSave, count, fnArray,
  11796. argsArray);
  11797. if (count < MIN_IMAGES_IN_MASKS_BLOCK) {
  11798. return i;
  11799. }
  11800. var q;
  11801. var isSameImage = false;
  11802. var iTransform, transformArgs;
  11803. var firstPIMXOArg0 = argsArray[iFirstPIMXO][0];
  11804. if (argsArray[iFirstTransform][1] === 0 &&
  11805. argsArray[iFirstTransform][2] === 0) {
  11806. isSameImage = true;
  11807. var firstTransformArg0 = argsArray[iFirstTransform][0];
  11808. var firstTransformArg3 = argsArray[iFirstTransform][3];
  11809. iTransform = iFirstTransform + 4;
  11810. var iPIMXO = iFirstPIMXO + 4;
  11811. for (q = 1; q < count; q++, iTransform += 4, iPIMXO += 4) {
  11812. transformArgs = argsArray[iTransform];
  11813. if (argsArray[iPIMXO][0] !== firstPIMXOArg0 ||
  11814. transformArgs[0] !== firstTransformArg0 ||
  11815. transformArgs[1] !== 0 ||
  11816. transformArgs[2] !== 0 ||
  11817. transformArgs[3] !== firstTransformArg3) {
  11818. if (q < MIN_IMAGES_IN_MASKS_BLOCK) {
  11819. isSameImage = false;
  11820. } else {
  11821. count = q;
  11822. }
  11823. break; // different image or transform
  11824. }
  11825. }
  11826. }
  11827. if (isSameImage) {
  11828. count = Math.min(count, MAX_SAME_IMAGES_IN_MASKS_BLOCK);
  11829. var positions = new Float32Array(count * 2);
  11830. iTransform = iFirstTransform;
  11831. for (q = 0; q < count; q++, iTransform += 4) {
  11832. transformArgs = argsArray[iTransform];
  11833. positions[(q << 1)] = transformArgs[4];
  11834. positions[(q << 1) + 1] = transformArgs[5];
  11835. }
  11836. // Replace queue items.
  11837. fnArray.splice(iFirstSave, count * 4, OPS.paintImageMaskXObjectRepeat);
  11838. argsArray.splice(iFirstSave, count * 4,
  11839. [firstPIMXOArg0, firstTransformArg0, firstTransformArg3, positions]);
  11840. } else {
  11841. count = Math.min(count, MAX_IMAGES_IN_MASKS_BLOCK);
  11842. var images = [];
  11843. for (q = 0; q < count; q++) {
  11844. transformArgs = argsArray[iFirstTransform + (q << 2)];
  11845. var maskParams = argsArray[iFirstPIMXO + (q << 2)][0];
  11846. images.push({ data: maskParams.data, width: maskParams.width,
  11847. height: maskParams.height,
  11848. transform: transformArgs });
  11849. }
  11850. // Replace queue items.
  11851. fnArray.splice(iFirstSave, count * 4, OPS.paintImageMaskXObjectGroup);
  11852. argsArray.splice(iFirstSave, count * 4, [images]);
  11853. }
  11854. return iFirstSave + 1;
  11855. });
  11856. // This replaces (save, transform, paintImageXObject, restore)+ sequences
  11857. // with one paintImageXObjectRepeat operation, if the |transform| and
  11858. // |paintImageXObjectRepeat| ops are appropriate.
  11859. addState(InitialState,
  11860. [OPS.save, OPS.transform, OPS.paintImageXObject, OPS.restore],
  11861. function (context) {
  11862. var MIN_IMAGES_IN_BLOCK = 3;
  11863. var MAX_IMAGES_IN_BLOCK = 1000;
  11864. var fnArray = context.fnArray, argsArray = context.argsArray;
  11865. var curr = context.iCurr;
  11866. var iFirstSave = curr - 3;
  11867. var iFirstTransform = curr - 2;
  11868. var iFirstPIXO = curr - 1;
  11869. var iFirstRestore = curr;
  11870. if (argsArray[iFirstTransform][1] !== 0 ||
  11871. argsArray[iFirstTransform][2] !== 0) {
  11872. return iFirstRestore + 1; // transform has the wrong form
  11873. }
  11874. // Look for the quartets.
  11875. var firstPIXOArg0 = argsArray[iFirstPIXO][0];
  11876. var firstTransformArg0 = argsArray[iFirstTransform][0];
  11877. var firstTransformArg3 = argsArray[iFirstTransform][3];
  11878. var i = iFirstSave + 4;
  11879. var ii = fnArray.length;
  11880. while (i + 3 < ii) {
  11881. if (fnArray[i] !== OPS.save ||
  11882. fnArray[i + 1] !== OPS.transform ||
  11883. fnArray[i + 2] !== OPS.paintImageXObject ||
  11884. fnArray[i + 3] !== OPS.restore) {
  11885. break; // ops don't match
  11886. }
  11887. if (argsArray[i + 1][0] !== firstTransformArg0 ||
  11888. argsArray[i + 1][1] !== 0 ||
  11889. argsArray[i + 1][2] !== 0 ||
  11890. argsArray[i + 1][3] !== firstTransformArg3) {
  11891. break; // transforms don't match
  11892. }
  11893. if (argsArray[i + 2][0] !== firstPIXOArg0) {
  11894. break; // images don't match
  11895. }
  11896. i += 4;
  11897. }
  11898. // At this point, i is the index of the first op past the last valid
  11899. // quartet.
  11900. var count = Math.min((i - iFirstSave) / 4, MAX_IMAGES_IN_BLOCK);
  11901. if (count < MIN_IMAGES_IN_BLOCK) {
  11902. return i;
  11903. }
  11904. // Extract the (x,y) positions from all of the matching transforms.
  11905. var positions = new Float32Array(count * 2);
  11906. var iTransform = iFirstTransform;
  11907. for (var q = 0; q < count; q++, iTransform += 4) {
  11908. var transformArgs = argsArray[iTransform];
  11909. positions[(q << 1)] = transformArgs[4];
  11910. positions[(q << 1) + 1] = transformArgs[5];
  11911. }
  11912. // Replace queue items.
  11913. var args = [firstPIXOArg0, firstTransformArg0, firstTransformArg3,
  11914. positions];
  11915. fnArray.splice(iFirstSave, count * 4, OPS.paintImageXObjectRepeat);
  11916. argsArray.splice(iFirstSave, count * 4, args);
  11917. return iFirstSave + 1;
  11918. });
  11919. // This replaces (beginText, setFont, setTextMatrix, showText, endText)+
  11920. // sequences with (beginText, setFont, (setTextMatrix, showText)+, endText)+
  11921. // sequences, if the font for each one is the same.
  11922. addState(InitialState,
  11923. [OPS.beginText, OPS.setFont, OPS.setTextMatrix, OPS.showText, OPS.endText],
  11924. function (context) {
  11925. var MIN_CHARS_IN_BLOCK = 3;
  11926. var MAX_CHARS_IN_BLOCK = 1000;
  11927. var fnArray = context.fnArray, argsArray = context.argsArray;
  11928. var curr = context.iCurr;
  11929. var iFirstBeginText = curr - 4;
  11930. var iFirstSetFont = curr - 3;
  11931. var iFirstSetTextMatrix = curr - 2;
  11932. var iFirstShowText = curr - 1;
  11933. var iFirstEndText = curr;
  11934. // Look for the quintets.
  11935. var firstSetFontArg0 = argsArray[iFirstSetFont][0];
  11936. var firstSetFontArg1 = argsArray[iFirstSetFont][1];
  11937. var i = iFirstBeginText + 5;
  11938. var ii = fnArray.length;
  11939. while (i + 4 < ii) {
  11940. if (fnArray[i] !== OPS.beginText ||
  11941. fnArray[i + 1] !== OPS.setFont ||
  11942. fnArray[i + 2] !== OPS.setTextMatrix ||
  11943. fnArray[i + 3] !== OPS.showText ||
  11944. fnArray[i + 4] !== OPS.endText) {
  11945. break; // ops don't match
  11946. }
  11947. if (argsArray[i + 1][0] !== firstSetFontArg0 ||
  11948. argsArray[i + 1][1] !== firstSetFontArg1) {
  11949. break; // fonts don't match
  11950. }
  11951. i += 5;
  11952. }
  11953. // At this point, i is the index of the first op past the last valid
  11954. // quintet.
  11955. var count = Math.min(((i - iFirstBeginText) / 5), MAX_CHARS_IN_BLOCK);
  11956. if (count < MIN_CHARS_IN_BLOCK) {
  11957. return i;
  11958. }
  11959. // If the preceding quintet is (<something>, setFont, setTextMatrix,
  11960. // showText, endText), include that as well. (E.g. <something> might be
  11961. // |dependency|.)
  11962. var iFirst = iFirstBeginText;
  11963. if (iFirstBeginText >= 4 &&
  11964. fnArray[iFirstBeginText - 4] === fnArray[iFirstSetFont] &&
  11965. fnArray[iFirstBeginText - 3] === fnArray[iFirstSetTextMatrix] &&
  11966. fnArray[iFirstBeginText - 2] === fnArray[iFirstShowText] &&
  11967. fnArray[iFirstBeginText - 1] === fnArray[iFirstEndText] &&
  11968. argsArray[iFirstBeginText - 4][0] === firstSetFontArg0 &&
  11969. argsArray[iFirstBeginText - 4][1] === firstSetFontArg1) {
  11970. count++;
  11971. iFirst -= 5;
  11972. }
  11973. // Remove (endText, beginText, setFont) trios.
  11974. var iEndText = iFirst + 4;
  11975. for (var q = 1; q < count; q++) {
  11976. fnArray.splice(iEndText, 3);
  11977. argsArray.splice(iEndText, 3);
  11978. iEndText += 2;
  11979. }
  11980. return iEndText + 1;
  11981. });
  11982. function QueueOptimizer() {}
  11983. QueueOptimizer.prototype = {
  11984. optimize: function QueueOptimizer_optimize(queue) {
  11985. var fnArray = queue.fnArray, argsArray = queue.argsArray;
  11986. var context = {
  11987. iCurr: 0,
  11988. fnArray: fnArray,
  11989. argsArray: argsArray
  11990. };
  11991. var state;
  11992. var i = 0, ii = fnArray.length;
  11993. while (i < ii) {
  11994. state = (state || InitialState)[fnArray[i]];
  11995. if (typeof state === 'function') { // we found some handler
  11996. context.iCurr = i;
  11997. // state() returns the index of the first non-matching op (if we
  11998. // didn't match) or the first op past the modified ops (if we did
  11999. // match and replace).
  12000. i = state(context);
  12001. state = undefined; // reset the state machine
  12002. ii = context.fnArray.length;
  12003. } else {
  12004. i++;
  12005. }
  12006. }
  12007. }
  12008. };
  12009. return QueueOptimizer;
  12010. })();
  12011. var BUILT_IN_CMAPS = [
  12012. // << Start unicode maps.
  12013. 'Adobe-GB1-UCS2',
  12014. 'Adobe-CNS1-UCS2',
  12015. 'Adobe-Japan1-UCS2',
  12016. 'Adobe-Korea1-UCS2',
  12017. // >> End unicode maps.
  12018. '78-EUC-H',
  12019. '78-EUC-V',
  12020. '78-H',
  12021. '78-RKSJ-H',
  12022. '78-RKSJ-V',
  12023. '78-V',
  12024. '78ms-RKSJ-H',
  12025. '78ms-RKSJ-V',
  12026. '83pv-RKSJ-H',
  12027. '90ms-RKSJ-H',
  12028. '90ms-RKSJ-V',
  12029. '90msp-RKSJ-H',
  12030. '90msp-RKSJ-V',
  12031. '90pv-RKSJ-H',
  12032. '90pv-RKSJ-V',
  12033. 'Add-H',
  12034. 'Add-RKSJ-H',
  12035. 'Add-RKSJ-V',
  12036. 'Add-V',
  12037. 'Adobe-CNS1-0',
  12038. 'Adobe-CNS1-1',
  12039. 'Adobe-CNS1-2',
  12040. 'Adobe-CNS1-3',
  12041. 'Adobe-CNS1-4',
  12042. 'Adobe-CNS1-5',
  12043. 'Adobe-CNS1-6',
  12044. 'Adobe-GB1-0',
  12045. 'Adobe-GB1-1',
  12046. 'Adobe-GB1-2',
  12047. 'Adobe-GB1-3',
  12048. 'Adobe-GB1-4',
  12049. 'Adobe-GB1-5',
  12050. 'Adobe-Japan1-0',
  12051. 'Adobe-Japan1-1',
  12052. 'Adobe-Japan1-2',
  12053. 'Adobe-Japan1-3',
  12054. 'Adobe-Japan1-4',
  12055. 'Adobe-Japan1-5',
  12056. 'Adobe-Japan1-6',
  12057. 'Adobe-Korea1-0',
  12058. 'Adobe-Korea1-1',
  12059. 'Adobe-Korea1-2',
  12060. 'B5-H',
  12061. 'B5-V',
  12062. 'B5pc-H',
  12063. 'B5pc-V',
  12064. 'CNS-EUC-H',
  12065. 'CNS-EUC-V',
  12066. 'CNS1-H',
  12067. 'CNS1-V',
  12068. 'CNS2-H',
  12069. 'CNS2-V',
  12070. 'ETHK-B5-H',
  12071. 'ETHK-B5-V',
  12072. 'ETen-B5-H',
  12073. 'ETen-B5-V',
  12074. 'ETenms-B5-H',
  12075. 'ETenms-B5-V',
  12076. 'EUC-H',
  12077. 'EUC-V',
  12078. 'Ext-H',
  12079. 'Ext-RKSJ-H',
  12080. 'Ext-RKSJ-V',
  12081. 'Ext-V',
  12082. 'GB-EUC-H',
  12083. 'GB-EUC-V',
  12084. 'GB-H',
  12085. 'GB-V',
  12086. 'GBK-EUC-H',
  12087. 'GBK-EUC-V',
  12088. 'GBK2K-H',
  12089. 'GBK2K-V',
  12090. 'GBKp-EUC-H',
  12091. 'GBKp-EUC-V',
  12092. 'GBT-EUC-H',
  12093. 'GBT-EUC-V',
  12094. 'GBT-H',
  12095. 'GBT-V',
  12096. 'GBTpc-EUC-H',
  12097. 'GBTpc-EUC-V',
  12098. 'GBpc-EUC-H',
  12099. 'GBpc-EUC-V',
  12100. 'H',
  12101. 'HKdla-B5-H',
  12102. 'HKdla-B5-V',
  12103. 'HKdlb-B5-H',
  12104. 'HKdlb-B5-V',
  12105. 'HKgccs-B5-H',
  12106. 'HKgccs-B5-V',
  12107. 'HKm314-B5-H',
  12108. 'HKm314-B5-V',
  12109. 'HKm471-B5-H',
  12110. 'HKm471-B5-V',
  12111. 'HKscs-B5-H',
  12112. 'HKscs-B5-V',
  12113. 'Hankaku',
  12114. 'Hiragana',
  12115. 'KSC-EUC-H',
  12116. 'KSC-EUC-V',
  12117. 'KSC-H',
  12118. 'KSC-Johab-H',
  12119. 'KSC-Johab-V',
  12120. 'KSC-V',
  12121. 'KSCms-UHC-H',
  12122. 'KSCms-UHC-HW-H',
  12123. 'KSCms-UHC-HW-V',
  12124. 'KSCms-UHC-V',
  12125. 'KSCpc-EUC-H',
  12126. 'KSCpc-EUC-V',
  12127. 'Katakana',
  12128. 'NWP-H',
  12129. 'NWP-V',
  12130. 'RKSJ-H',
  12131. 'RKSJ-V',
  12132. 'Roman',
  12133. 'UniCNS-UCS2-H',
  12134. 'UniCNS-UCS2-V',
  12135. 'UniCNS-UTF16-H',
  12136. 'UniCNS-UTF16-V',
  12137. 'UniCNS-UTF32-H',
  12138. 'UniCNS-UTF32-V',
  12139. 'UniCNS-UTF8-H',
  12140. 'UniCNS-UTF8-V',
  12141. 'UniGB-UCS2-H',
  12142. 'UniGB-UCS2-V',
  12143. 'UniGB-UTF16-H',
  12144. 'UniGB-UTF16-V',
  12145. 'UniGB-UTF32-H',
  12146. 'UniGB-UTF32-V',
  12147. 'UniGB-UTF8-H',
  12148. 'UniGB-UTF8-V',
  12149. 'UniJIS-UCS2-H',
  12150. 'UniJIS-UCS2-HW-H',
  12151. 'UniJIS-UCS2-HW-V',
  12152. 'UniJIS-UCS2-V',
  12153. 'UniJIS-UTF16-H',
  12154. 'UniJIS-UTF16-V',
  12155. 'UniJIS-UTF32-H',
  12156. 'UniJIS-UTF32-V',
  12157. 'UniJIS-UTF8-H',
  12158. 'UniJIS-UTF8-V',
  12159. 'UniJIS2004-UTF16-H',
  12160. 'UniJIS2004-UTF16-V',
  12161. 'UniJIS2004-UTF32-H',
  12162. 'UniJIS2004-UTF32-V',
  12163. 'UniJIS2004-UTF8-H',
  12164. 'UniJIS2004-UTF8-V',
  12165. 'UniJISPro-UCS2-HW-V',
  12166. 'UniJISPro-UCS2-V',
  12167. 'UniJISPro-UTF8-V',
  12168. 'UniJISX0213-UTF32-H',
  12169. 'UniJISX0213-UTF32-V',
  12170. 'UniJISX02132004-UTF32-H',
  12171. 'UniJISX02132004-UTF32-V',
  12172. 'UniKS-UCS2-H',
  12173. 'UniKS-UCS2-V',
  12174. 'UniKS-UTF16-H',
  12175. 'UniKS-UTF16-V',
  12176. 'UniKS-UTF32-H',
  12177. 'UniKS-UTF32-V',
  12178. 'UniKS-UTF8-H',
  12179. 'UniKS-UTF8-V',
  12180. 'V',
  12181. 'WP-Symbol'];
  12182. // CMap, not to be confused with TrueType's cmap.
  12183. var CMap = (function CMapClosure() {
  12184. function CMap(builtInCMap) {
  12185. // Codespace ranges are stored as follows:
  12186. // [[1BytePairs], [2BytePairs], [3BytePairs], [4BytePairs]]
  12187. // where nBytePairs are ranges e.g. [low1, high1, low2, high2, ...]
  12188. this.codespaceRanges = [[], [], [], []];
  12189. this.numCodespaceRanges = 0;
  12190. // Map entries have one of two forms.
  12191. // - cid chars are 16-bit unsigned integers, stored as integers.
  12192. // - bf chars are variable-length byte sequences, stored as strings, with
  12193. // one byte per character.
  12194. this._map = [];
  12195. this.name = '';
  12196. this.vertical = false;
  12197. this.useCMap = null;
  12198. this.builtInCMap = builtInCMap;
  12199. }
  12200. CMap.prototype = {
  12201. addCodespaceRange: function(n, low, high) {
  12202. this.codespaceRanges[n - 1].push(low, high);
  12203. this.numCodespaceRanges++;
  12204. },
  12205. mapCidRange: function(low, high, dstLow) {
  12206. while (low <= high) {
  12207. this._map[low++] = dstLow++;
  12208. }
  12209. },
  12210. mapBfRange: function(low, high, dstLow) {
  12211. var lastByte = dstLow.length - 1;
  12212. while (low <= high) {
  12213. this._map[low++] = dstLow;
  12214. // Only the last byte has to be incremented.
  12215. dstLow = dstLow.substr(0, lastByte) +
  12216. String.fromCharCode(dstLow.charCodeAt(lastByte) + 1);
  12217. }
  12218. },
  12219. mapBfRangeToArray: function(low, high, array) {
  12220. var i = 0, ii = array.length;
  12221. while (low <= high && i < ii) {
  12222. this._map[low] = array[i++];
  12223. ++low;
  12224. }
  12225. },
  12226. // This is used for both bf and cid chars.
  12227. mapOne: function(src, dst) {
  12228. this._map[src] = dst;
  12229. },
  12230. lookup: function(code) {
  12231. return this._map[code];
  12232. },
  12233. contains: function(code) {
  12234. return this._map[code] !== undefined;
  12235. },
  12236. forEach: function(callback) {
  12237. // Most maps have fewer than 65536 entries, and for those we use normal
  12238. // array iteration. But really sparse tables are possible -- e.g. with
  12239. // indices in the *billions*. For such tables we use for..in, which isn't
  12240. // ideal because it stringifies the indices for all present elements, but
  12241. // it does avoid iterating over every undefined entry.
  12242. var map = this._map;
  12243. var length = map.length;
  12244. var i;
  12245. if (length <= 0x10000) {
  12246. for (i = 0; i < length; i++) {
  12247. if (map[i] !== undefined) {
  12248. callback(i, map[i]);
  12249. }
  12250. }
  12251. } else {
  12252. for (i in this._map) {
  12253. callback(i, map[i]);
  12254. }
  12255. }
  12256. },
  12257. charCodeOf: function(value) {
  12258. return this._map.indexOf(value);
  12259. },
  12260. getMap: function() {
  12261. return this._map;
  12262. },
  12263. readCharCode: function(str, offset, out) {
  12264. var c = 0;
  12265. var codespaceRanges = this.codespaceRanges;
  12266. var codespaceRangesLen = this.codespaceRanges.length;
  12267. // 9.7.6.2 CMap Mapping
  12268. // The code length is at most 4.
  12269. for (var n = 0; n < codespaceRangesLen; n++) {
  12270. c = ((c << 8) | str.charCodeAt(offset + n)) >>> 0;
  12271. // Check each codespace range to see if it falls within.
  12272. var codespaceRange = codespaceRanges[n];
  12273. for (var k = 0, kk = codespaceRange.length; k < kk;) {
  12274. var low = codespaceRange[k++];
  12275. var high = codespaceRange[k++];
  12276. if (c >= low && c <= high) {
  12277. out.charcode = c;
  12278. out.length = n + 1;
  12279. return;
  12280. }
  12281. }
  12282. }
  12283. out.charcode = 0;
  12284. out.length = 1;
  12285. },
  12286. get isIdentityCMap() {
  12287. if (!(this.name === 'Identity-H' || this.name === 'Identity-V')) {
  12288. return false;
  12289. }
  12290. if (this._map.length !== 0x10000) {
  12291. return false;
  12292. }
  12293. for (var i = 0; i < 0x10000; i++) {
  12294. if (this._map[i] !== i) {
  12295. return false;
  12296. }
  12297. }
  12298. return true;
  12299. }
  12300. };
  12301. return CMap;
  12302. })();
  12303. // A special case of CMap, where the _map array implicitly has a length of
  12304. // 65536 and each element is equal to its index.
  12305. var IdentityCMap = (function IdentityCMapClosure() {
  12306. function IdentityCMap(vertical, n) {
  12307. CMap.call(this);
  12308. this.vertical = vertical;
  12309. this.addCodespaceRange(n, 0, 0xffff);
  12310. }
  12311. Util.inherit(IdentityCMap, CMap, {});
  12312. IdentityCMap.prototype = {
  12313. addCodespaceRange: CMap.prototype.addCodespaceRange,
  12314. mapCidRange: function(low, high, dstLow) {
  12315. error('should not call mapCidRange');
  12316. },
  12317. mapBfRange: function(low, high, dstLow) {
  12318. error('should not call mapBfRange');
  12319. },
  12320. mapBfRangeToArray: function(low, high, array) {
  12321. error('should not call mapBfRangeToArray');
  12322. },
  12323. mapOne: function(src, dst) {
  12324. error('should not call mapCidOne');
  12325. },
  12326. lookup: function(code) {
  12327. return (isInt(code) && code <= 0xffff) ? code : undefined;
  12328. },
  12329. contains: function(code) {
  12330. return isInt(code) && code <= 0xffff;
  12331. },
  12332. forEach: function(callback) {
  12333. for (var i = 0; i <= 0xffff; i++) {
  12334. callback(i, i);
  12335. }
  12336. },
  12337. charCodeOf: function(value) {
  12338. return (isInt(value) && value <= 0xffff) ? value : -1;
  12339. },
  12340. getMap: function() {
  12341. // Sometimes identity maps must be instantiated, but it's rare.
  12342. var map = new Array(0x10000);
  12343. for (var i = 0; i <= 0xffff; i++) {
  12344. map[i] = i;
  12345. }
  12346. return map;
  12347. },
  12348. readCharCode: CMap.prototype.readCharCode,
  12349. get isIdentityCMap() {
  12350. error('should not access .isIdentityCMap');
  12351. }
  12352. };
  12353. return IdentityCMap;
  12354. })();
  12355. var BinaryCMapReader = (function BinaryCMapReaderClosure() {
  12356. function fetchBinaryData(url) {
  12357. var nonBinaryRequest = PDFJS.disableWorker;
  12358. var request = new XMLHttpRequest();
  12359. request.open('GET', url, false);
  12360. if (!nonBinaryRequest) {
  12361. try {
  12362. request.responseType = 'arraybuffer';
  12363. nonBinaryRequest = request.responseType !== 'arraybuffer';
  12364. } catch (e) {
  12365. nonBinaryRequest = true;
  12366. }
  12367. }
  12368. if (nonBinaryRequest && request.overrideMimeType) {
  12369. request.overrideMimeType('text/plain; charset=x-user-defined');
  12370. }
  12371. request.send(null);
  12372. if (nonBinaryRequest ? !request.responseText : !request.response) {
  12373. error('Unable to get binary cMap at: ' + url);
  12374. }
  12375. if (nonBinaryRequest) {
  12376. var data = Array.prototype.map.call(request.responseText, function (ch) {
  12377. return ch.charCodeAt(0) & 255;
  12378. });
  12379. return new Uint8Array(data);
  12380. }
  12381. return new Uint8Array(request.response);
  12382. }
  12383. function hexToInt(a, size) {
  12384. var n = 0;
  12385. for (var i = 0; i <= size; i++) {
  12386. n = (n << 8) | a[i];
  12387. }
  12388. return n >>> 0;
  12389. }
  12390. function hexToStr(a, size) {
  12391. // This code is hot. Special-case some common values to avoid creating an
  12392. // object with subarray().
  12393. if (size === 1) {
  12394. return String.fromCharCode(a[0], a[1]);
  12395. }
  12396. if (size === 3) {
  12397. return String.fromCharCode(a[0], a[1], a[2], a[3]);
  12398. }
  12399. return String.fromCharCode.apply(null, a.subarray(0, size + 1));
  12400. }
  12401. function addHex(a, b, size) {
  12402. var c = 0;
  12403. for (var i = size; i >= 0; i--) {
  12404. c += a[i] + b[i];
  12405. a[i] = c & 255;
  12406. c >>= 8;
  12407. }
  12408. }
  12409. function incHex(a, size) {
  12410. var c = 1;
  12411. for (var i = size; i >= 0 && c > 0; i--) {
  12412. c += a[i];
  12413. a[i] = c & 255;
  12414. c >>= 8;
  12415. }
  12416. }
  12417. var MAX_NUM_SIZE = 16;
  12418. var MAX_ENCODED_NUM_SIZE = 19; // ceil(MAX_NUM_SIZE * 7 / 8)
  12419. function BinaryCMapStream(data) {
  12420. this.buffer = data;
  12421. this.pos = 0;
  12422. this.end = data.length;
  12423. this.tmpBuf = new Uint8Array(MAX_ENCODED_NUM_SIZE);
  12424. }
  12425. BinaryCMapStream.prototype = {
  12426. readByte: function () {
  12427. if (this.pos >= this.end) {
  12428. return -1;
  12429. }
  12430. return this.buffer[this.pos++];
  12431. },
  12432. readNumber: function () {
  12433. var n = 0;
  12434. var last;
  12435. do {
  12436. var b = this.readByte();
  12437. if (b < 0) {
  12438. error('unexpected EOF in bcmap');
  12439. }
  12440. last = !(b & 0x80);
  12441. n = (n << 7) | (b & 0x7F);
  12442. } while (!last);
  12443. return n;
  12444. },
  12445. readSigned: function () {
  12446. var n = this.readNumber();
  12447. return (n & 1) ? ~(n >>> 1) : n >>> 1;
  12448. },
  12449. readHex: function (num, size) {
  12450. num.set(this.buffer.subarray(this.pos,
  12451. this.pos + size + 1));
  12452. this.pos += size + 1;
  12453. },
  12454. readHexNumber: function (num, size) {
  12455. var last;
  12456. var stack = this.tmpBuf, sp = 0;
  12457. do {
  12458. var b = this.readByte();
  12459. if (b < 0) {
  12460. error('unexpected EOF in bcmap');
  12461. }
  12462. last = !(b & 0x80);
  12463. stack[sp++] = b & 0x7F;
  12464. } while (!last);
  12465. var i = size, buffer = 0, bufferSize = 0;
  12466. while (i >= 0) {
  12467. while (bufferSize < 8 && stack.length > 0) {
  12468. buffer = (stack[--sp] << bufferSize) | buffer;
  12469. bufferSize += 7;
  12470. }
  12471. num[i] = buffer & 255;
  12472. i--;
  12473. buffer >>= 8;
  12474. bufferSize -= 8;
  12475. }
  12476. },
  12477. readHexSigned: function (num, size) {
  12478. this.readHexNumber(num, size);
  12479. var sign = num[size] & 1 ? 255 : 0;
  12480. var c = 0;
  12481. for (var i = 0; i <= size; i++) {
  12482. c = ((c & 1) << 8) | num[i];
  12483. num[i] = (c >> 1) ^ sign;
  12484. }
  12485. },
  12486. readString: function () {
  12487. var len = this.readNumber();
  12488. var s = '';
  12489. for (var i = 0; i < len; i++) {
  12490. s += String.fromCharCode(this.readNumber());
  12491. }
  12492. return s;
  12493. }
  12494. };
  12495. function processBinaryCMap(url, cMap, extend) {
  12496. var data = fetchBinaryData(url);
  12497. var stream = new BinaryCMapStream(data);
  12498. var header = stream.readByte();
  12499. cMap.vertical = !!(header & 1);
  12500. var useCMap = null;
  12501. var start = new Uint8Array(MAX_NUM_SIZE);
  12502. var end = new Uint8Array(MAX_NUM_SIZE);
  12503. var char = new Uint8Array(MAX_NUM_SIZE);
  12504. var charCode = new Uint8Array(MAX_NUM_SIZE);
  12505. var tmp = new Uint8Array(MAX_NUM_SIZE);
  12506. var code;
  12507. var b;
  12508. while ((b = stream.readByte()) >= 0) {
  12509. var type = b >> 5;
  12510. if (type === 7) { // metadata, e.g. comment or usecmap
  12511. switch (b & 0x1F) {
  12512. case 0:
  12513. stream.readString(); // skipping comment
  12514. break;
  12515. case 1:
  12516. useCMap = stream.readString();
  12517. break;
  12518. }
  12519. continue;
  12520. }
  12521. var sequence = !!(b & 0x10);
  12522. var dataSize = b & 15;
  12523. assert(dataSize + 1 <= MAX_NUM_SIZE);
  12524. var ucs2DataSize = 1;
  12525. var subitemsCount = stream.readNumber();
  12526. var i;
  12527. switch (type) {
  12528. case 0: // codespacerange
  12529. stream.readHex(start, dataSize);
  12530. stream.readHexNumber(end, dataSize);
  12531. addHex(end, start, dataSize);
  12532. cMap.addCodespaceRange(dataSize + 1, hexToInt(start, dataSize),
  12533. hexToInt(end, dataSize));
  12534. for (i = 1; i < subitemsCount; i++) {
  12535. incHex(end, dataSize);
  12536. stream.readHexNumber(start, dataSize);
  12537. addHex(start, end, dataSize);
  12538. stream.readHexNumber(end, dataSize);
  12539. addHex(end, start, dataSize);
  12540. cMap.addCodespaceRange(dataSize + 1, hexToInt(start, dataSize),
  12541. hexToInt(end, dataSize));
  12542. }
  12543. break;
  12544. case 1: // notdefrange
  12545. stream.readHex(start, dataSize);
  12546. stream.readHexNumber(end, dataSize);
  12547. addHex(end, start, dataSize);
  12548. code = stream.readNumber();
  12549. // undefined range, skipping
  12550. for (i = 1; i < subitemsCount; i++) {
  12551. incHex(end, dataSize);
  12552. stream.readHexNumber(start, dataSize);
  12553. addHex(start, end, dataSize);
  12554. stream.readHexNumber(end, dataSize);
  12555. addHex(end, start, dataSize);
  12556. code = stream.readNumber();
  12557. // nop
  12558. }
  12559. break;
  12560. case 2: // cidchar
  12561. stream.readHex(char, dataSize);
  12562. code = stream.readNumber();
  12563. cMap.mapOne(hexToInt(char, dataSize), code);
  12564. for (i = 1; i < subitemsCount; i++) {
  12565. incHex(char, dataSize);
  12566. if (!sequence) {
  12567. stream.readHexNumber(tmp, dataSize);
  12568. addHex(char, tmp, dataSize);
  12569. }
  12570. code = stream.readSigned() + (code + 1);
  12571. cMap.mapOne(hexToInt(char, dataSize), code);
  12572. }
  12573. break;
  12574. case 3: // cidrange
  12575. stream.readHex(start, dataSize);
  12576. stream.readHexNumber(end, dataSize);
  12577. addHex(end, start, dataSize);
  12578. code = stream.readNumber();
  12579. cMap.mapCidRange(hexToInt(start, dataSize), hexToInt(end, dataSize),
  12580. code);
  12581. for (i = 1; i < subitemsCount; i++) {
  12582. incHex(end, dataSize);
  12583. if (!sequence) {
  12584. stream.readHexNumber(start, dataSize);
  12585. addHex(start, end, dataSize);
  12586. } else {
  12587. start.set(end);
  12588. }
  12589. stream.readHexNumber(end, dataSize);
  12590. addHex(end, start, dataSize);
  12591. code = stream.readNumber();
  12592. cMap.mapCidRange(hexToInt(start, dataSize), hexToInt(end, dataSize),
  12593. code);
  12594. }
  12595. break;
  12596. case 4: // bfchar
  12597. stream.readHex(char, ucs2DataSize);
  12598. stream.readHex(charCode, dataSize);
  12599. cMap.mapOne(hexToInt(char, ucs2DataSize),
  12600. hexToStr(charCode, dataSize));
  12601. for (i = 1; i < subitemsCount; i++) {
  12602. incHex(char, ucs2DataSize);
  12603. if (!sequence) {
  12604. stream.readHexNumber(tmp, ucs2DataSize);
  12605. addHex(char, tmp, ucs2DataSize);
  12606. }
  12607. incHex(charCode, dataSize);
  12608. stream.readHexSigned(tmp, dataSize);
  12609. addHex(charCode, tmp, dataSize);
  12610. cMap.mapOne(hexToInt(char, ucs2DataSize),
  12611. hexToStr(charCode, dataSize));
  12612. }
  12613. break;
  12614. case 5: // bfrange
  12615. stream.readHex(start, ucs2DataSize);
  12616. stream.readHexNumber(end, ucs2DataSize);
  12617. addHex(end, start, ucs2DataSize);
  12618. stream.readHex(charCode, dataSize);
  12619. cMap.mapBfRange(hexToInt(start, ucs2DataSize),
  12620. hexToInt(end, ucs2DataSize),
  12621. hexToStr(charCode, dataSize));
  12622. for (i = 1; i < subitemsCount; i++) {
  12623. incHex(end, ucs2DataSize);
  12624. if (!sequence) {
  12625. stream.readHexNumber(start, ucs2DataSize);
  12626. addHex(start, end, ucs2DataSize);
  12627. } else {
  12628. start.set(end);
  12629. }
  12630. stream.readHexNumber(end, ucs2DataSize);
  12631. addHex(end, start, ucs2DataSize);
  12632. stream.readHex(charCode, dataSize);
  12633. cMap.mapBfRange(hexToInt(start, ucs2DataSize),
  12634. hexToInt(end, ucs2DataSize),
  12635. hexToStr(charCode, dataSize));
  12636. }
  12637. break;
  12638. default:
  12639. error('Unknown type: ' + type);
  12640. break;
  12641. }
  12642. }
  12643. if (useCMap) {
  12644. extend(useCMap);
  12645. }
  12646. return cMap;
  12647. }
  12648. function BinaryCMapReader() {}
  12649. BinaryCMapReader.prototype = {
  12650. read: processBinaryCMap
  12651. };
  12652. return BinaryCMapReader;
  12653. })();
  12654. var CMapFactory = (function CMapFactoryClosure() {
  12655. function strToInt(str) {
  12656. var a = 0;
  12657. for (var i = 0; i < str.length; i++) {
  12658. a = (a << 8) | str.charCodeAt(i);
  12659. }
  12660. return a >>> 0;
  12661. }
  12662. function expectString(obj) {
  12663. if (!isString(obj)) {
  12664. error('Malformed CMap: expected string.');
  12665. }
  12666. }
  12667. function expectInt(obj) {
  12668. if (!isInt(obj)) {
  12669. error('Malformed CMap: expected int.');
  12670. }
  12671. }
  12672. function parseBfChar(cMap, lexer) {
  12673. while (true) {
  12674. var obj = lexer.getObj();
  12675. if (isEOF(obj)) {
  12676. break;
  12677. }
  12678. if (isCmd(obj, 'endbfchar')) {
  12679. return;
  12680. }
  12681. expectString(obj);
  12682. var src = strToInt(obj);
  12683. obj = lexer.getObj();
  12684. // TODO are /dstName used?
  12685. expectString(obj);
  12686. var dst = obj;
  12687. cMap.mapOne(src, dst);
  12688. }
  12689. }
  12690. function parseBfRange(cMap, lexer) {
  12691. while (true) {
  12692. var obj = lexer.getObj();
  12693. if (isEOF(obj)) {
  12694. break;
  12695. }
  12696. if (isCmd(obj, 'endbfrange')) {
  12697. return;
  12698. }
  12699. expectString(obj);
  12700. var low = strToInt(obj);
  12701. obj = lexer.getObj();
  12702. expectString(obj);
  12703. var high = strToInt(obj);
  12704. obj = lexer.getObj();
  12705. if (isInt(obj) || isString(obj)) {
  12706. var dstLow = isInt(obj) ? String.fromCharCode(obj) : obj;
  12707. cMap.mapBfRange(low, high, dstLow);
  12708. } else if (isCmd(obj, '[')) {
  12709. obj = lexer.getObj();
  12710. var array = [];
  12711. while (!isCmd(obj, ']') && !isEOF(obj)) {
  12712. array.push(obj);
  12713. obj = lexer.getObj();
  12714. }
  12715. cMap.mapBfRangeToArray(low, high, array);
  12716. } else {
  12717. break;
  12718. }
  12719. }
  12720. error('Invalid bf range.');
  12721. }
  12722. function parseCidChar(cMap, lexer) {
  12723. while (true) {
  12724. var obj = lexer.getObj();
  12725. if (isEOF(obj)) {
  12726. break;
  12727. }
  12728. if (isCmd(obj, 'endcidchar')) {
  12729. return;
  12730. }
  12731. expectString(obj);
  12732. var src = strToInt(obj);
  12733. obj = lexer.getObj();
  12734. expectInt(obj);
  12735. var dst = obj;
  12736. cMap.mapOne(src, dst);
  12737. }
  12738. }
  12739. function parseCidRange(cMap, lexer) {
  12740. while (true) {
  12741. var obj = lexer.getObj();
  12742. if (isEOF(obj)) {
  12743. break;
  12744. }
  12745. if (isCmd(obj, 'endcidrange')) {
  12746. return;
  12747. }
  12748. expectString(obj);
  12749. var low = strToInt(obj);
  12750. obj = lexer.getObj();
  12751. expectString(obj);
  12752. var high = strToInt(obj);
  12753. obj = lexer.getObj();
  12754. expectInt(obj);
  12755. var dstLow = obj;
  12756. cMap.mapCidRange(low, high, dstLow);
  12757. }
  12758. }
  12759. function parseCodespaceRange(cMap, lexer) {
  12760. while (true) {
  12761. var obj = lexer.getObj();
  12762. if (isEOF(obj)) {
  12763. break;
  12764. }
  12765. if (isCmd(obj, 'endcodespacerange')) {
  12766. return;
  12767. }
  12768. if (!isString(obj)) {
  12769. break;
  12770. }
  12771. var low = strToInt(obj);
  12772. obj = lexer.getObj();
  12773. if (!isString(obj)) {
  12774. break;
  12775. }
  12776. var high = strToInt(obj);
  12777. cMap.addCodespaceRange(obj.length, low, high);
  12778. }
  12779. error('Invalid codespace range.');
  12780. }
  12781. function parseWMode(cMap, lexer) {
  12782. var obj = lexer.getObj();
  12783. if (isInt(obj)) {
  12784. cMap.vertical = !!obj;
  12785. }
  12786. }
  12787. function parseCMapName(cMap, lexer) {
  12788. var obj = lexer.getObj();
  12789. if (isName(obj) && isString(obj.name)) {
  12790. cMap.name = obj.name;
  12791. }
  12792. }
  12793. function parseCMap(cMap, lexer, builtInCMapParams, useCMap) {
  12794. var previous;
  12795. var embededUseCMap;
  12796. objLoop: while (true) {
  12797. var obj = lexer.getObj();
  12798. if (isEOF(obj)) {
  12799. break;
  12800. } else if (isName(obj)) {
  12801. if (obj.name === 'WMode') {
  12802. parseWMode(cMap, lexer);
  12803. } else if (obj.name === 'CMapName') {
  12804. parseCMapName(cMap, lexer);
  12805. }
  12806. previous = obj;
  12807. } else if (isCmd(obj)) {
  12808. switch (obj.cmd) {
  12809. case 'endcmap':
  12810. break objLoop;
  12811. case 'usecmap':
  12812. if (isName(previous)) {
  12813. embededUseCMap = previous.name;
  12814. }
  12815. break;
  12816. case 'begincodespacerange':
  12817. parseCodespaceRange(cMap, lexer);
  12818. break;
  12819. case 'beginbfchar':
  12820. parseBfChar(cMap, lexer);
  12821. break;
  12822. case 'begincidchar':
  12823. parseCidChar(cMap, lexer);
  12824. break;
  12825. case 'beginbfrange':
  12826. parseBfRange(cMap, lexer);
  12827. break;
  12828. case 'begincidrange':
  12829. parseCidRange(cMap, lexer);
  12830. break;
  12831. }
  12832. }
  12833. }
  12834. if (!useCMap && embededUseCMap) {
  12835. // Load the usecmap definition from the file only if there wasn't one
  12836. // specified.
  12837. useCMap = embededUseCMap;
  12838. }
  12839. if (useCMap) {
  12840. extendCMap(cMap, builtInCMapParams, useCMap);
  12841. }
  12842. }
  12843. function extendCMap(cMap, builtInCMapParams, useCMap) {
  12844. cMap.useCMap = createBuiltInCMap(useCMap, builtInCMapParams);
  12845. // If there aren't any code space ranges defined clone all the parent ones
  12846. // into this cMap.
  12847. if (cMap.numCodespaceRanges === 0) {
  12848. var useCodespaceRanges = cMap.useCMap.codespaceRanges;
  12849. for (var i = 0; i < useCodespaceRanges.length; i++) {
  12850. cMap.codespaceRanges[i] = useCodespaceRanges[i].slice();
  12851. }
  12852. cMap.numCodespaceRanges = cMap.useCMap.numCodespaceRanges;
  12853. }
  12854. // Merge the map into the current one, making sure not to override
  12855. // any previously defined entries.
  12856. cMap.useCMap.forEach(function(key, value) {
  12857. if (!cMap.contains(key)) {
  12858. cMap.mapOne(key, cMap.useCMap.lookup(key));
  12859. }
  12860. });
  12861. }
  12862. function parseBinaryCMap(name, builtInCMapParams) {
  12863. var url = builtInCMapParams.url + name + '.bcmap';
  12864. var cMap = new CMap(true);
  12865. new BinaryCMapReader().read(url, cMap, function (useCMap) {
  12866. extendCMap(cMap, builtInCMapParams, useCMap);
  12867. });
  12868. return cMap;
  12869. }
  12870. function createBuiltInCMap(name, builtInCMapParams) {
  12871. if (name === 'Identity-H') {
  12872. return new IdentityCMap(false, 2);
  12873. } else if (name === 'Identity-V') {
  12874. return new IdentityCMap(true, 2);
  12875. }
  12876. if (BUILT_IN_CMAPS.indexOf(name) === -1) {
  12877. error('Unknown cMap name: ' + name);
  12878. }
  12879. assert(builtInCMapParams, 'built-in cMap parameters are not provided');
  12880. if (builtInCMapParams.packed) {
  12881. return parseBinaryCMap(name, builtInCMapParams);
  12882. }
  12883. var request = new XMLHttpRequest();
  12884. var url = builtInCMapParams.url + name;
  12885. request.open('GET', url, false);
  12886. request.send(null);
  12887. if (!request.responseText) {
  12888. error('Unable to get cMap at: ' + url);
  12889. }
  12890. var cMap = new CMap(true);
  12891. var lexer = new Lexer(new StringStream(request.responseText));
  12892. parseCMap(cMap, lexer, builtInCMapParams, null);
  12893. return cMap;
  12894. }
  12895. return {
  12896. create: function (encoding, builtInCMapParams, useCMap) {
  12897. if (isName(encoding)) {
  12898. return createBuiltInCMap(encoding.name, builtInCMapParams);
  12899. } else if (isStream(encoding)) {
  12900. var cMap = new CMap();
  12901. var lexer = new Lexer(encoding);
  12902. try {
  12903. parseCMap(cMap, lexer, builtInCMapParams, useCMap);
  12904. } catch (e) {
  12905. warn('Invalid CMap data. ' + e);
  12906. }
  12907. if (cMap.isIdentityCMap) {
  12908. return createBuiltInCMap(cMap.name, builtInCMapParams);
  12909. }
  12910. return cMap;
  12911. }
  12912. error('Encoding required.');
  12913. }
  12914. };
  12915. })();
  12916. // Unicode Private Use Area
  12917. var PRIVATE_USE_OFFSET_START = 0xE000;
  12918. var PRIVATE_USE_OFFSET_END = 0xF8FF;
  12919. var SKIP_PRIVATE_USE_RANGE_F000_TO_F01F = false;
  12920. // PDF Glyph Space Units are one Thousandth of a TextSpace Unit
  12921. // except for Type 3 fonts
  12922. var PDF_GLYPH_SPACE_UNITS = 1000;
  12923. // Hinting is currently disabled due to unknown problems on windows
  12924. // in tracemonkey and various other pdfs with type1 fonts.
  12925. var HINTING_ENABLED = false;
  12926. // Accented charactars are not displayed properly on windows, using this flag
  12927. // to control analysis of seac charstrings.
  12928. var SEAC_ANALYSIS_ENABLED = false;
  12929. var FontFlags = {
  12930. FixedPitch: 1,
  12931. Serif: 2,
  12932. Symbolic: 4,
  12933. Script: 8,
  12934. Nonsymbolic: 32,
  12935. Italic: 64,
  12936. AllCap: 65536,
  12937. SmallCap: 131072,
  12938. ForceBold: 262144
  12939. };
  12940. var Encodings = {
  12941. ExpertEncoding: ['', '', '', '', '', '', '', '', '', '', '', '', '', '', '',
  12942. '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '',
  12943. 'space', 'exclamsmall', 'Hungarumlautsmall', '', 'dollaroldstyle',
  12944. 'dollarsuperior', 'ampersandsmall', 'Acutesmall', 'parenleftsuperior',
  12945. 'parenrightsuperior', 'twodotenleader', 'onedotenleader', 'comma',
  12946. 'hyphen', 'period', 'fraction', 'zerooldstyle', 'oneoldstyle',
  12947. 'twooldstyle', 'threeoldstyle', 'fouroldstyle', 'fiveoldstyle',
  12948. 'sixoldstyle', 'sevenoldstyle', 'eightoldstyle', 'nineoldstyle', 'colon',
  12949. 'semicolon', 'commasuperior', 'threequartersemdash', 'periodsuperior',
  12950. 'questionsmall', '', 'asuperior', 'bsuperior', 'centsuperior', 'dsuperior',
  12951. 'esuperior', '', '', 'isuperior', '', '', 'lsuperior', 'msuperior',
  12952. 'nsuperior', 'osuperior', '', '', 'rsuperior', 'ssuperior', 'tsuperior',
  12953. '', 'ff', 'fi', 'fl', 'ffi', 'ffl', 'parenleftinferior', '',
  12954. 'parenrightinferior', 'Circumflexsmall', 'hyphensuperior', 'Gravesmall',
  12955. 'Asmall', 'Bsmall', 'Csmall', 'Dsmall', 'Esmall', 'Fsmall', 'Gsmall',
  12956. 'Hsmall', 'Ismall', 'Jsmall', 'Ksmall', 'Lsmall', 'Msmall', 'Nsmall',
  12957. 'Osmall', 'Psmall', 'Qsmall', 'Rsmall', 'Ssmall', 'Tsmall', 'Usmall',
  12958. 'Vsmall', 'Wsmall', 'Xsmall', 'Ysmall', 'Zsmall', 'colonmonetary',
  12959. 'onefitted', 'rupiah', 'Tildesmall', '', '', '', '', '', '', '', '', '',
  12960. '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '',
  12961. '', '', '', '', '', '', 'exclamdownsmall', 'centoldstyle', 'Lslashsmall',
  12962. '', '', 'Scaronsmall', 'Zcaronsmall', 'Dieresissmall', 'Brevesmall',
  12963. 'Caronsmall', '', 'Dotaccentsmall', '', '', 'Macronsmall', '', '',
  12964. 'figuredash', 'hypheninferior', '', '', 'Ogoneksmall', 'Ringsmall',
  12965. 'Cedillasmall', '', '', '', 'onequarter', 'onehalf', 'threequarters',
  12966. 'questiondownsmall', 'oneeighth', 'threeeighths', 'fiveeighths',
  12967. 'seveneighths', 'onethird', 'twothirds', '', '', 'zerosuperior',
  12968. 'onesuperior', 'twosuperior', 'threesuperior', 'foursuperior',
  12969. 'fivesuperior', 'sixsuperior', 'sevensuperior', 'eightsuperior',
  12970. 'ninesuperior', 'zeroinferior', 'oneinferior', 'twoinferior',
  12971. 'threeinferior', 'fourinferior', 'fiveinferior', 'sixinferior',
  12972. 'seveninferior', 'eightinferior', 'nineinferior', 'centinferior',
  12973. 'dollarinferior', 'periodinferior', 'commainferior', 'Agravesmall',
  12974. 'Aacutesmall', 'Acircumflexsmall', 'Atildesmall', 'Adieresissmall',
  12975. 'Aringsmall', 'AEsmall', 'Ccedillasmall', 'Egravesmall', 'Eacutesmall',
  12976. 'Ecircumflexsmall', 'Edieresissmall', 'Igravesmall', 'Iacutesmall',
  12977. 'Icircumflexsmall', 'Idieresissmall', 'Ethsmall', 'Ntildesmall',
  12978. 'Ogravesmall', 'Oacutesmall', 'Ocircumflexsmall', 'Otildesmall',
  12979. 'Odieresissmall', 'OEsmall', 'Oslashsmall', 'Ugravesmall', 'Uacutesmall',
  12980. 'Ucircumflexsmall', 'Udieresissmall', 'Yacutesmall', 'Thornsmall',
  12981. 'Ydieresissmall'],
  12982. MacExpertEncoding: ['', '', '', '', '', '', '', '', '', '', '', '', '', '',
  12983. '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '',
  12984. 'space', 'exclamsmall', 'Hungarumlautsmall', 'centoldstyle',
  12985. 'dollaroldstyle', 'dollarsuperior', 'ampersandsmall', 'Acutesmall',
  12986. 'parenleftsuperior', 'parenrightsuperior', 'twodotenleader',
  12987. 'onedotenleader', 'comma', 'hyphen', 'period', 'fraction', 'zerooldstyle',
  12988. 'oneoldstyle', 'twooldstyle', 'threeoldstyle', 'fouroldstyle',
  12989. 'fiveoldstyle', 'sixoldstyle', 'sevenoldstyle', 'eightoldstyle',
  12990. 'nineoldstyle', 'colon', 'semicolon', '', 'threequartersemdash', '',
  12991. 'questionsmall', '', '', '', '', 'Ethsmall', '', '', 'onequarter',
  12992. 'onehalf', 'threequarters', 'oneeighth', 'threeeighths', 'fiveeighths',
  12993. 'seveneighths', 'onethird', 'twothirds', '', '', '', '', '', '', 'ff',
  12994. 'fi', 'fl', 'ffi', 'ffl', 'parenleftinferior', '', 'parenrightinferior',
  12995. 'Circumflexsmall', 'hypheninferior', 'Gravesmall', 'Asmall', 'Bsmall',
  12996. 'Csmall', 'Dsmall', 'Esmall', 'Fsmall', 'Gsmall', 'Hsmall', 'Ismall',
  12997. 'Jsmall', 'Ksmall', 'Lsmall', 'Msmall', 'Nsmall', 'Osmall', 'Psmall',
  12998. 'Qsmall', 'Rsmall', 'Ssmall', 'Tsmall', 'Usmall', 'Vsmall', 'Wsmall',
  12999. 'Xsmall', 'Ysmall', 'Zsmall', 'colonmonetary', 'onefitted', 'rupiah',
  13000. 'Tildesmall', '', '', 'asuperior', 'centsuperior', '', '', '', '',
  13001. 'Aacutesmall', 'Agravesmall', 'Acircumflexsmall', 'Adieresissmall',
  13002. 'Atildesmall', 'Aringsmall', 'Ccedillasmall', 'Eacutesmall', 'Egravesmall',
  13003. 'Ecircumflexsmall', 'Edieresissmall', 'Iacutesmall', 'Igravesmall',
  13004. 'Icircumflexsmall', 'Idieresissmall', 'Ntildesmall', 'Oacutesmall',
  13005. 'Ogravesmall', 'Ocircumflexsmall', 'Odieresissmall', 'Otildesmall',
  13006. 'Uacutesmall', 'Ugravesmall', 'Ucircumflexsmall', 'Udieresissmall', '',
  13007. 'eightsuperior', 'fourinferior', 'threeinferior', 'sixinferior',
  13008. 'eightinferior', 'seveninferior', 'Scaronsmall', '', 'centinferior',
  13009. 'twoinferior', '', 'Dieresissmall', '', 'Caronsmall', 'osuperior',
  13010. 'fiveinferior', '', 'commainferior', 'periodinferior', 'Yacutesmall', '',
  13011. 'dollarinferior', '', 'Thornsmall', '', 'nineinferior', 'zeroinferior',
  13012. 'Zcaronsmall', 'AEsmall', 'Oslashsmall', 'questiondownsmall',
  13013. 'oneinferior', 'Lslashsmall', '', '', '', '', '', '', 'Cedillasmall', '',
  13014. '', '', '', '', 'OEsmall', 'figuredash', 'hyphensuperior', '', '', '', '',
  13015. 'exclamdownsmall', '', 'Ydieresissmall', '', 'onesuperior', 'twosuperior',
  13016. 'threesuperior', 'foursuperior', 'fivesuperior', 'sixsuperior',
  13017. 'sevensuperior', 'ninesuperior', 'zerosuperior', '', 'esuperior',
  13018. 'rsuperior', 'tsuperior', '', '', 'isuperior', 'ssuperior', 'dsuperior',
  13019. '', '', '', '', '', 'lsuperior', 'Ogoneksmall', 'Brevesmall',
  13020. 'Macronsmall', 'bsuperior', 'nsuperior', 'msuperior', 'commasuperior',
  13021. 'periodsuperior', 'Dotaccentsmall', 'Ringsmall'],
  13022. MacRomanEncoding: ['', '', '', '', '', '', '', '', '', '', '', '', '', '', '',
  13023. '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '',
  13024. 'space', 'exclam', 'quotedbl', 'numbersign', 'dollar', 'percent',
  13025. 'ampersand', 'quotesingle', 'parenleft', 'parenright', 'asterisk', 'plus',
  13026. 'comma', 'hyphen', 'period', 'slash', 'zero', 'one', 'two', 'three',
  13027. 'four', 'five', 'six', 'seven', 'eight', 'nine', 'colon', 'semicolon',
  13028. 'less', 'equal', 'greater', 'question', 'at', 'A', 'B', 'C', 'D', 'E', 'F',
  13029. 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U',
  13030. 'V', 'W', 'X', 'Y', 'Z', 'bracketleft', 'backslash', 'bracketright',
  13031. 'asciicircum', 'underscore', 'grave', 'a', 'b', 'c', 'd', 'e', 'f', 'g',
  13032. 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v',
  13033. 'w', 'x', 'y', 'z', 'braceleft', 'bar', 'braceright', 'asciitilde', '',
  13034. 'Adieresis', 'Aring', 'Ccedilla', 'Eacute', 'Ntilde', 'Odieresis',
  13035. 'Udieresis', 'aacute', 'agrave', 'acircumflex', 'adieresis', 'atilde',
  13036. 'aring', 'ccedilla', 'eacute', 'egrave', 'ecircumflex', 'edieresis',
  13037. 'iacute', 'igrave', 'icircumflex', 'idieresis', 'ntilde', 'oacute',
  13038. 'ograve', 'ocircumflex', 'odieresis', 'otilde', 'uacute', 'ugrave',
  13039. 'ucircumflex', 'udieresis', 'dagger', 'degree', 'cent', 'sterling',
  13040. 'section', 'bullet', 'paragraph', 'germandbls', 'registered', 'copyright',
  13041. 'trademark', 'acute', 'dieresis', 'notequal', 'AE', 'Oslash', 'infinity',
  13042. 'plusminus', 'lessequal', 'greaterequal', 'yen', 'mu', 'partialdiff',
  13043. 'summation', 'product', 'pi', 'integral', 'ordfeminine', 'ordmasculine',
  13044. 'Omega', 'ae', 'oslash', 'questiondown', 'exclamdown', 'logicalnot',
  13045. 'radical', 'florin', 'approxequal', 'Delta', 'guillemotleft',
  13046. 'guillemotright', 'ellipsis', 'space', 'Agrave', 'Atilde', 'Otilde', 'OE',
  13047. 'oe', 'endash', 'emdash', 'quotedblleft', 'quotedblright', 'quoteleft',
  13048. 'quoteright', 'divide', 'lozenge', 'ydieresis', 'Ydieresis', 'fraction',
  13049. 'currency', 'guilsinglleft', 'guilsinglright', 'fi', 'fl', 'daggerdbl',
  13050. 'periodcentered', 'quotesinglbase', 'quotedblbase', 'perthousand',
  13051. 'Acircumflex', 'Ecircumflex', 'Aacute', 'Edieresis', 'Egrave', 'Iacute',
  13052. 'Icircumflex', 'Idieresis', 'Igrave', 'Oacute', 'Ocircumflex', 'apple',
  13053. 'Ograve', 'Uacute', 'Ucircumflex', 'Ugrave', 'dotlessi', 'circumflex',
  13054. 'tilde', 'macron', 'breve', 'dotaccent', 'ring', 'cedilla', 'hungarumlaut',
  13055. 'ogonek', 'caron'],
  13056. StandardEncoding: ['', '', '', '', '', '', '', '', '', '', '', '', '', '', '',
  13057. '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '',
  13058. 'space', 'exclam', 'quotedbl', 'numbersign', 'dollar', 'percent',
  13059. 'ampersand', 'quoteright', 'parenleft', 'parenright', 'asterisk', 'plus',
  13060. 'comma', 'hyphen', 'period', 'slash', 'zero', 'one', 'two', 'three',
  13061. 'four', 'five', 'six', 'seven', 'eight', 'nine', 'colon', 'semicolon',
  13062. 'less', 'equal', 'greater', 'question', 'at', 'A', 'B', 'C', 'D', 'E', 'F',
  13063. 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U',
  13064. 'V', 'W', 'X', 'Y', 'Z', 'bracketleft', 'backslash', 'bracketright',
  13065. 'asciicircum', 'underscore', 'quoteleft', 'a', 'b', 'c', 'd', 'e', 'f',
  13066. 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u',
  13067. 'v', 'w', 'x', 'y', 'z', 'braceleft', 'bar', 'braceright', 'asciitilde',
  13068. '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '',
  13069. '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', 'exclamdown',
  13070. 'cent', 'sterling', 'fraction', 'yen', 'florin', 'section', 'currency',
  13071. 'quotesingle', 'quotedblleft', 'guillemotleft', 'guilsinglleft',
  13072. 'guilsinglright', 'fi', 'fl', '', 'endash', 'dagger', 'daggerdbl',
  13073. 'periodcentered', '', 'paragraph', 'bullet', 'quotesinglbase',
  13074. 'quotedblbase', 'quotedblright', 'guillemotright', 'ellipsis',
  13075. 'perthousand', '', 'questiondown', '', 'grave', 'acute', 'circumflex',
  13076. 'tilde', 'macron', 'breve', 'dotaccent', 'dieresis', '', 'ring', 'cedilla',
  13077. '', 'hungarumlaut', 'ogonek', 'caron', 'emdash', '', '', '', '', '', '',
  13078. '', '', '', '', '', '', '', '', '', '', 'AE', '', 'ordfeminine', '', '',
  13079. '', '', 'Lslash', 'Oslash', 'OE', 'ordmasculine', '', '', '', '', '', 'ae',
  13080. '', '', '', 'dotlessi', '', '', 'lslash', 'oslash', 'oe', 'germandbls'],
  13081. WinAnsiEncoding: ['', '', '', '', '', '', '', '', '', '', '', '', '', '', '',
  13082. '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '',
  13083. 'space', 'exclam', 'quotedbl', 'numbersign', 'dollar', 'percent',
  13084. 'ampersand', 'quotesingle', 'parenleft', 'parenright', 'asterisk', 'plus',
  13085. 'comma', 'hyphen', 'period', 'slash', 'zero', 'one', 'two', 'three',
  13086. 'four', 'five', 'six', 'seven', 'eight', 'nine', 'colon', 'semicolon',
  13087. 'less', 'equal', 'greater', 'question', 'at', 'A', 'B', 'C', 'D', 'E', 'F',
  13088. 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U',
  13089. 'V', 'W', 'X', 'Y', 'Z', 'bracketleft', 'backslash', 'bracketright',
  13090. 'asciicircum', 'underscore', 'grave', 'a', 'b', 'c', 'd', 'e', 'f', 'g',
  13091. 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v',
  13092. 'w', 'x', 'y', 'z', 'braceleft', 'bar', 'braceright', 'asciitilde',
  13093. 'bullet', 'Euro', 'bullet', 'quotesinglbase', 'florin', 'quotedblbase',
  13094. 'ellipsis', 'dagger', 'daggerdbl', 'circumflex', 'perthousand', 'Scaron',
  13095. 'guilsinglleft', 'OE', 'bullet', 'Zcaron', 'bullet', 'bullet', 'quoteleft',
  13096. 'quoteright', 'quotedblleft', 'quotedblright', 'bullet', 'endash',
  13097. 'emdash', 'tilde', 'trademark', 'scaron', 'guilsinglright', 'oe', 'bullet',
  13098. 'zcaron', 'Ydieresis', 'space', 'exclamdown', 'cent', 'sterling',
  13099. 'currency', 'yen', 'brokenbar', 'section', 'dieresis', 'copyright',
  13100. 'ordfeminine', 'guillemotleft', 'logicalnot', 'hyphen', 'registered',
  13101. 'macron', 'degree', 'plusminus', 'twosuperior', 'threesuperior', 'acute',
  13102. 'mu', 'paragraph', 'periodcentered', 'cedilla', 'onesuperior',
  13103. 'ordmasculine', 'guillemotright', 'onequarter', 'onehalf', 'threequarters',
  13104. 'questiondown', 'Agrave', 'Aacute', 'Acircumflex', 'Atilde', 'Adieresis',
  13105. 'Aring', 'AE', 'Ccedilla', 'Egrave', 'Eacute', 'Ecircumflex', 'Edieresis',
  13106. 'Igrave', 'Iacute', 'Icircumflex', 'Idieresis', 'Eth', 'Ntilde', 'Ograve',
  13107. 'Oacute', 'Ocircumflex', 'Otilde', 'Odieresis', 'multiply', 'Oslash',
  13108. 'Ugrave', 'Uacute', 'Ucircumflex', 'Udieresis', 'Yacute', 'Thorn',
  13109. 'germandbls', 'agrave', 'aacute', 'acircumflex', 'atilde', 'adieresis',
  13110. 'aring', 'ae', 'ccedilla', 'egrave', 'eacute', 'ecircumflex', 'edieresis',
  13111. 'igrave', 'iacute', 'icircumflex', 'idieresis', 'eth', 'ntilde', 'ograve',
  13112. 'oacute', 'ocircumflex', 'otilde', 'odieresis', 'divide', 'oslash',
  13113. 'ugrave', 'uacute', 'ucircumflex', 'udieresis', 'yacute', 'thorn',
  13114. 'ydieresis'],
  13115. SymbolSetEncoding: ['', '', '', '', '', '', '', '', '', '', '', '', '', '',
  13116. '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '',
  13117. 'space', 'exclam', 'universal', 'numbersign', 'existential', 'percent',
  13118. 'ampersand', 'suchthat', 'parenleft', 'parenright', 'asteriskmath', 'plus',
  13119. 'comma', 'minus', 'period', 'slash', 'zero', 'one', 'two', 'three', 'four',
  13120. 'five', 'six', 'seven', 'eight', 'nine', 'colon', 'semicolon', 'less',
  13121. 'equal', 'greater', 'question', 'congruent', 'Alpha', 'Beta', 'Chi',
  13122. 'Delta', 'Epsilon', 'Phi', 'Gamma', 'Eta', 'Iota', 'theta1', 'Kappa',
  13123. 'Lambda', 'Mu', 'Nu', 'Omicron', 'Pi', 'Theta', 'Rho', 'Sigma', 'Tau',
  13124. 'Upsilon', 'sigma1', 'Omega', 'Xi', 'Psi', 'Zeta', 'bracketleft',
  13125. 'therefore', 'bracketright', 'perpendicular', 'underscore', 'radicalex',
  13126. 'alpha', 'beta', 'chi', 'delta', 'epsilon', 'phi', 'gamma', 'eta', 'iota',
  13127. 'phi1', 'kappa', 'lambda', 'mu', 'nu', 'omicron', 'pi', 'theta', 'rho',
  13128. 'sigma', 'tau', 'upsilon', 'omega1', 'omega', 'xi', 'psi', 'zeta',
  13129. 'braceleft', 'bar', 'braceright', 'similar', '', '', '', '', '', '', '',
  13130. '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '',
  13131. '', '', '', '', '', '', '', 'Euro', 'Upsilon1', 'minute', 'lessequal',
  13132. 'fraction', 'infinity', 'florin', 'club', 'diamond', 'heart', 'spade',
  13133. 'arrowboth', 'arrowleft', 'arrowup', 'arrowright', 'arrowdown', 'degree',
  13134. 'plusminus', 'second', 'greaterequal', 'multiply', 'proportional',
  13135. 'partialdiff', 'bullet', 'divide', 'notequal', 'equivalence',
  13136. 'approxequal', 'ellipsis', 'arrowvertex', 'arrowhorizex', 'carriagereturn',
  13137. 'aleph', 'Ifraktur', 'Rfraktur', 'weierstrass', 'circlemultiply',
  13138. 'circleplus', 'emptyset', 'intersection', 'union', 'propersuperset',
  13139. 'reflexsuperset', 'notsubset', 'propersubset', 'reflexsubset', 'element',
  13140. 'notelement', 'angle', 'gradient', 'registerserif', 'copyrightserif',
  13141. 'trademarkserif', 'product', 'radical', 'dotmath', 'logicalnot',
  13142. 'logicaland', 'logicalor', 'arrowdblboth', 'arrowdblleft', 'arrowdblup',
  13143. 'arrowdblright', 'arrowdbldown', 'lozenge', 'angleleft', 'registersans',
  13144. 'copyrightsans', 'trademarksans', 'summation', 'parenlefttp',
  13145. 'parenleftex', 'parenleftbt', 'bracketlefttp', 'bracketleftex',
  13146. 'bracketleftbt', 'bracelefttp', 'braceleftmid', 'braceleftbt', 'braceex',
  13147. '', 'angleright', 'integral', 'integraltp', 'integralex', 'integralbt',
  13148. 'parenrighttp', 'parenrightex', 'parenrightbt', 'bracketrighttp',
  13149. 'bracketrightex', 'bracketrightbt', 'bracerighttp', 'bracerightmid',
  13150. 'bracerightbt'],
  13151. ZapfDingbatsEncoding: ['', '', '', '', '', '', '', '', '', '', '', '', '', '',
  13152. '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '',
  13153. 'space', 'a1', 'a2', 'a202', 'a3', 'a4', 'a5', 'a119', 'a118', 'a117',
  13154. 'a11', 'a12', 'a13', 'a14', 'a15', 'a16', 'a105', 'a17', 'a18', 'a19',
  13155. 'a20', 'a21', 'a22', 'a23', 'a24', 'a25', 'a26', 'a27', 'a28', 'a6', 'a7',
  13156. 'a8', 'a9', 'a10', 'a29', 'a30', 'a31', 'a32', 'a33', 'a34', 'a35', 'a36',
  13157. 'a37', 'a38', 'a39', 'a40', 'a41', 'a42', 'a43', 'a44', 'a45', 'a46',
  13158. 'a47', 'a48', 'a49', 'a50', 'a51', 'a52', 'a53', 'a54', 'a55', 'a56',
  13159. 'a57', 'a58', 'a59', 'a60', 'a61', 'a62', 'a63', 'a64', 'a65', 'a66',
  13160. 'a67', 'a68', 'a69', 'a70', 'a71', 'a72', 'a73', 'a74', 'a203', 'a75',
  13161. 'a204', 'a76', 'a77', 'a78', 'a79', 'a81', 'a82', 'a83', 'a84', 'a97',
  13162. 'a98', 'a99', 'a100', '', 'a89', 'a90', 'a93', 'a94', 'a91', 'a92', 'a205',
  13163. 'a85', 'a206', 'a86', 'a87', 'a88', 'a95', 'a96', '', '', '', '', '', '',
  13164. '', '', '', '', '', '', '', '', '', '', '', '', '', 'a101', 'a102', 'a103',
  13165. 'a104', 'a106', 'a107', 'a108', 'a112', 'a111', 'a110', 'a109', 'a120',
  13166. 'a121', 'a122', 'a123', 'a124', 'a125', 'a126', 'a127', 'a128', 'a129',
  13167. 'a130', 'a131', 'a132', 'a133', 'a134', 'a135', 'a136', 'a137', 'a138',
  13168. 'a139', 'a140', 'a141', 'a142', 'a143', 'a144', 'a145', 'a146', 'a147',
  13169. 'a148', 'a149', 'a150', 'a151', 'a152', 'a153', 'a154', 'a155', 'a156',
  13170. 'a157', 'a158', 'a159', 'a160', 'a161', 'a163', 'a164', 'a196', 'a165',
  13171. 'a192', 'a166', 'a167', 'a168', 'a169', 'a170', 'a171', 'a172', 'a173',
  13172. 'a162', 'a174', 'a175', 'a176', 'a177', 'a178', 'a179', 'a193', 'a180',
  13173. 'a199', 'a181', 'a200', 'a182', '', 'a201', 'a183', 'a184', 'a197', 'a185',
  13174. 'a194', 'a198', 'a186', 'a195', 'a187', 'a188', 'a189', 'a190', 'a191']
  13175. };
  13176. /**
  13177. * Hold a map of decoded fonts and of the standard fourteen Type1
  13178. * fonts and their acronyms.
  13179. */
  13180. var stdFontMap = {
  13181. 'ArialNarrow': 'Helvetica',
  13182. 'ArialNarrow-Bold': 'Helvetica-Bold',
  13183. 'ArialNarrow-BoldItalic': 'Helvetica-BoldOblique',
  13184. 'ArialNarrow-Italic': 'Helvetica-Oblique',
  13185. 'ArialBlack': 'Helvetica',
  13186. 'ArialBlack-Bold': 'Helvetica-Bold',
  13187. 'ArialBlack-BoldItalic': 'Helvetica-BoldOblique',
  13188. 'ArialBlack-Italic': 'Helvetica-Oblique',
  13189. 'Arial': 'Helvetica',
  13190. 'Arial-Bold': 'Helvetica-Bold',
  13191. 'Arial-BoldItalic': 'Helvetica-BoldOblique',
  13192. 'Arial-Italic': 'Helvetica-Oblique',
  13193. 'Arial-BoldItalicMT': 'Helvetica-BoldOblique',
  13194. 'Arial-BoldMT': 'Helvetica-Bold',
  13195. 'Arial-ItalicMT': 'Helvetica-Oblique',
  13196. 'ArialMT': 'Helvetica',
  13197. 'Courier-Bold': 'Courier-Bold',
  13198. 'Courier-BoldItalic': 'Courier-BoldOblique',
  13199. 'Courier-Italic': 'Courier-Oblique',
  13200. 'CourierNew': 'Courier',
  13201. 'CourierNew-Bold': 'Courier-Bold',
  13202. 'CourierNew-BoldItalic': 'Courier-BoldOblique',
  13203. 'CourierNew-Italic': 'Courier-Oblique',
  13204. 'CourierNewPS-BoldItalicMT': 'Courier-BoldOblique',
  13205. 'CourierNewPS-BoldMT': 'Courier-Bold',
  13206. 'CourierNewPS-ItalicMT': 'Courier-Oblique',
  13207. 'CourierNewPSMT': 'Courier',
  13208. 'Helvetica': 'Helvetica',
  13209. 'Helvetica-Bold': 'Helvetica-Bold',
  13210. 'Helvetica-BoldItalic': 'Helvetica-BoldOblique',
  13211. 'Helvetica-BoldOblique': 'Helvetica-BoldOblique',
  13212. 'Helvetica-Italic': 'Helvetica-Oblique',
  13213. 'Helvetica-Oblique':'Helvetica-Oblique',
  13214. 'Symbol-Bold': 'Symbol',
  13215. 'Symbol-BoldItalic': 'Symbol',
  13216. 'Symbol-Italic': 'Symbol',
  13217. 'TimesNewRoman': 'Times-Roman',
  13218. 'TimesNewRoman-Bold': 'Times-Bold',
  13219. 'TimesNewRoman-BoldItalic': 'Times-BoldItalic',
  13220. 'TimesNewRoman-Italic': 'Times-Italic',
  13221. 'TimesNewRomanPS': 'Times-Roman',
  13222. 'TimesNewRomanPS-Bold': 'Times-Bold',
  13223. 'TimesNewRomanPS-BoldItalic': 'Times-BoldItalic',
  13224. 'TimesNewRomanPS-BoldItalicMT': 'Times-BoldItalic',
  13225. 'TimesNewRomanPS-BoldMT': 'Times-Bold',
  13226. 'TimesNewRomanPS-Italic': 'Times-Italic',
  13227. 'TimesNewRomanPS-ItalicMT': 'Times-Italic',
  13228. 'TimesNewRomanPSMT': 'Times-Roman',
  13229. 'TimesNewRomanPSMT-Bold': 'Times-Bold',
  13230. 'TimesNewRomanPSMT-BoldItalic': 'Times-BoldItalic',
  13231. 'TimesNewRomanPSMT-Italic': 'Times-Italic'
  13232. };
  13233. /**
  13234. * Holds the map of the non-standard fonts that might be included as a standard
  13235. * fonts without glyph data.
  13236. */
  13237. var nonStdFontMap = {
  13238. 'CenturyGothic': 'Helvetica',
  13239. 'CenturyGothic-Bold': 'Helvetica-Bold',
  13240. 'CenturyGothic-BoldItalic': 'Helvetica-BoldOblique',
  13241. 'CenturyGothic-Italic': 'Helvetica-Oblique',
  13242. 'ComicSansMS': 'Comic Sans MS',
  13243. 'ComicSansMS-Bold': 'Comic Sans MS-Bold',
  13244. 'ComicSansMS-BoldItalic': 'Comic Sans MS-BoldItalic',
  13245. 'ComicSansMS-Italic': 'Comic Sans MS-Italic',
  13246. 'LucidaConsole': 'Courier',
  13247. 'LucidaConsole-Bold': 'Courier-Bold',
  13248. 'LucidaConsole-BoldItalic': 'Courier-BoldOblique',
  13249. 'LucidaConsole-Italic': 'Courier-Oblique',
  13250. 'MS-Gothic': 'MS Gothic',
  13251. 'MS-Gothic-Bold': 'MS Gothic-Bold',
  13252. 'MS-Gothic-BoldItalic': 'MS Gothic-BoldItalic',
  13253. 'MS-Gothic-Italic': 'MS Gothic-Italic',
  13254. 'MS-Mincho': 'MS Mincho',
  13255. 'MS-Mincho-Bold': 'MS Mincho-Bold',
  13256. 'MS-Mincho-BoldItalic': 'MS Mincho-BoldItalic',
  13257. 'MS-Mincho-Italic': 'MS Mincho-Italic',
  13258. 'MS-PGothic': 'MS PGothic',
  13259. 'MS-PGothic-Bold': 'MS PGothic-Bold',
  13260. 'MS-PGothic-BoldItalic': 'MS PGothic-BoldItalic',
  13261. 'MS-PGothic-Italic': 'MS PGothic-Italic',
  13262. 'MS-PMincho': 'MS PMincho',
  13263. 'MS-PMincho-Bold': 'MS PMincho-Bold',
  13264. 'MS-PMincho-BoldItalic': 'MS PMincho-BoldItalic',
  13265. 'MS-PMincho-Italic': 'MS PMincho-Italic',
  13266. 'Wingdings': 'ZapfDingbats'
  13267. };
  13268. var serifFonts = {
  13269. 'Adobe Jenson': true, 'Adobe Text': true, 'Albertus': true,
  13270. 'Aldus': true, 'Alexandria': true, 'Algerian': true,
  13271. 'American Typewriter': true, 'Antiqua': true, 'Apex': true,
  13272. 'Arno': true, 'Aster': true, 'Aurora': true,
  13273. 'Baskerville': true, 'Bell': true, 'Bembo': true,
  13274. 'Bembo Schoolbook': true, 'Benguiat': true, 'Berkeley Old Style': true,
  13275. 'Bernhard Modern': true, 'Berthold City': true, 'Bodoni': true,
  13276. 'Bauer Bodoni': true, 'Book Antiqua': true, 'Bookman': true,
  13277. 'Bordeaux Roman': true, 'Californian FB': true, 'Calisto': true,
  13278. 'Calvert': true, 'Capitals': true, 'Cambria': true,
  13279. 'Cartier': true, 'Caslon': true, 'Catull': true,
  13280. 'Centaur': true, 'Century Old Style': true, 'Century Schoolbook': true,
  13281. 'Chaparral': true, 'Charis SIL': true, 'Cheltenham': true,
  13282. 'Cholla Slab': true, 'Clarendon': true, 'Clearface': true,
  13283. 'Cochin': true, 'Colonna': true, 'Computer Modern': true,
  13284. 'Concrete Roman': true, 'Constantia': true, 'Cooper Black': true,
  13285. 'Corona': true, 'Ecotype': true, 'Egyptienne': true,
  13286. 'Elephant': true, 'Excelsior': true, 'Fairfield': true,
  13287. 'FF Scala': true, 'Folkard': true, 'Footlight': true,
  13288. 'FreeSerif': true, 'Friz Quadrata': true, 'Garamond': true,
  13289. 'Gentium': true, 'Georgia': true, 'Gloucester': true,
  13290. 'Goudy Old Style': true, 'Goudy Schoolbook': true, 'Goudy Pro Font': true,
  13291. 'Granjon': true, 'Guardian Egyptian': true, 'Heather': true,
  13292. 'Hercules': true, 'High Tower Text': true, 'Hiroshige': true,
  13293. 'Hoefler Text': true, 'Humana Serif': true, 'Imprint': true,
  13294. 'Ionic No. 5': true, 'Janson': true, 'Joanna': true,
  13295. 'Korinna': true, 'Lexicon': true, 'Liberation Serif': true,
  13296. 'Linux Libertine': true, 'Literaturnaya': true, 'Lucida': true,
  13297. 'Lucida Bright': true, 'Melior': true, 'Memphis': true,
  13298. 'Miller': true, 'Minion': true, 'Modern': true,
  13299. 'Mona Lisa': true, 'Mrs Eaves': true, 'MS Serif': true,
  13300. 'Museo Slab': true, 'New York': true, 'Nimbus Roman': true,
  13301. 'NPS Rawlinson Roadway': true, 'Palatino': true, 'Perpetua': true,
  13302. 'Plantin': true, 'Plantin Schoolbook': true, 'Playbill': true,
  13303. 'Poor Richard': true, 'Rawlinson Roadway': true, 'Renault': true,
  13304. 'Requiem': true, 'Rockwell': true, 'Roman': true,
  13305. 'Rotis Serif': true, 'Sabon': true, 'Scala': true,
  13306. 'Seagull': true, 'Sistina': true, 'Souvenir': true,
  13307. 'STIX': true, 'Stone Informal': true, 'Stone Serif': true,
  13308. 'Sylfaen': true, 'Times': true, 'Trajan': true,
  13309. 'Trinité': true, 'Trump Mediaeval': true, 'Utopia': true,
  13310. 'Vale Type': true, 'Bitstream Vera': true, 'Vera Serif': true,
  13311. 'Versailles': true, 'Wanted': true, 'Weiss': true,
  13312. 'Wide Latin': true, 'Windsor': true, 'XITS': true
  13313. };
  13314. var symbolsFonts = {
  13315. 'Dingbats': true, 'Symbol': true, 'ZapfDingbats': true
  13316. };
  13317. // Glyph map for well-known standard fonts. Sometimes Ghostscript uses CID fonts
  13318. // but does not embed the CID to GID mapping. The mapping is incomplete for all
  13319. // glyphs, but common for some set of the standard fonts.
  13320. var GlyphMapForStandardFonts = {
  13321. '2': 10, '3': 32, '4': 33, '5': 34, '6': 35, '7': 36, '8': 37, '9': 38,
  13322. '10': 39, '11': 40, '12': 41, '13': 42, '14': 43, '15': 44, '16': 45,
  13323. '17': 46, '18': 47, '19': 48, '20': 49, '21': 50, '22': 51, '23': 52,
  13324. '24': 53, '25': 54, '26': 55, '27': 56, '28': 57, '29': 58, '30': 894,
  13325. '31': 60, '32': 61, '33': 62, '34': 63, '35': 64, '36': 65, '37': 66,
  13326. '38': 67, '39': 68, '40': 69, '41': 70, '42': 71, '43': 72, '44': 73,
  13327. '45': 74, '46': 75, '47': 76, '48': 77, '49': 78, '50': 79, '51': 80,
  13328. '52': 81, '53': 82, '54': 83, '55': 84, '56': 85, '57': 86, '58': 87,
  13329. '59': 88, '60': 89, '61': 90, '62': 91, '63': 92, '64': 93, '65': 94,
  13330. '66': 95, '67': 96, '68': 97, '69': 98, '70': 99, '71': 100, '72': 101,
  13331. '73': 102, '74': 103, '75': 104, '76': 105, '77': 106, '78': 107, '79': 108,
  13332. '80': 109, '81': 110, '82': 111, '83': 112, '84': 113, '85': 114, '86': 115,
  13333. '87': 116, '88': 117, '89': 118, '90': 119, '91': 120, '92': 121, '93': 122,
  13334. '94': 123, '95': 124, '96': 125, '97': 126, '98': 196, '99': 197, '100': 199,
  13335. '101': 201, '102': 209, '103': 214, '104': 220, '105': 225, '106': 224,
  13336. '107': 226, '108': 228, '109': 227, '110': 229, '111': 231, '112': 233,
  13337. '113': 232, '114': 234, '115': 235, '116': 237, '117': 236, '118': 238,
  13338. '119': 239, '120': 241, '121': 243, '122': 242, '123': 244, '124': 246,
  13339. '125': 245, '126': 250, '127': 249, '128': 251, '129': 252, '130': 8224,
  13340. '131': 176, '132': 162, '133': 163, '134': 167, '135': 8226, '136': 182,
  13341. '137': 223, '138': 174, '139': 169, '140': 8482, '141': 180, '142': 168,
  13342. '143': 8800, '144': 198, '145': 216, '146': 8734, '147': 177, '148': 8804,
  13343. '149': 8805, '150': 165, '151': 181, '152': 8706, '153': 8721, '154': 8719,
  13344. '156': 8747, '157': 170, '158': 186, '159': 8486, '160': 230, '161': 248,
  13345. '162': 191, '163': 161, '164': 172, '165': 8730, '166': 402, '167': 8776,
  13346. '168': 8710, '169': 171, '170': 187, '171': 8230, '210': 218, '223': 711,
  13347. '224': 321, '225': 322, '227': 353, '229': 382, '234': 253, '252': 263,
  13348. '253': 268, '254': 269, '258': 258, '260': 260, '261': 261, '265': 280,
  13349. '266': 281, '268': 283, '269': 313, '275': 323, '276': 324, '278': 328,
  13350. '284': 345, '285': 346, '286': 347, '292': 367, '295': 377, '296': 378,
  13351. '298': 380, '305': 963,
  13352. '306': 964, '307': 966, '308': 8215, '309': 8252, '310': 8319, '311': 8359,
  13353. '312': 8592, '313': 8593, '337': 9552, '493': 1039, '494': 1040, '705': 1524,
  13354. '706': 8362, '710': 64288, '711': 64298, '759': 1617, '761': 1776,
  13355. '763': 1778, '775': 1652, '777': 1764, '778': 1780, '779': 1781, '780': 1782,
  13356. '782': 771, '783': 64726, '786': 8363, '788': 8532, '790': 768, '791': 769,
  13357. '792': 768, '795': 803, '797': 64336, '798': 64337, '799': 64342,
  13358. '800': 64343, '801': 64344, '802': 64345, '803': 64362, '804': 64363,
  13359. '805': 64364, '2424': 7821, '2425': 7822, '2426': 7823, '2427': 7824,
  13360. '2428': 7825, '2429': 7826, '2430': 7827, '2433': 7682, '2678': 8045,
  13361. '2679': 8046, '2830': 1552, '2838': 686, '2840': 751, '2842': 753,
  13362. '2843': 754, '2844': 755, '2846': 757, '2856': 767, '2857': 848, '2858': 849,
  13363. '2862': 853, '2863': 854, '2864': 855, '2865': 861, '2866': 862, '2906': 7460,
  13364. '2908': 7462, '2909': 7463, '2910': 7464, '2912': 7466, '2913': 7467,
  13365. '2914': 7468, '2916': 7470, '2917': 7471, '2918': 7472, '2920': 7474,
  13366. '2921': 7475, '2922': 7476, '2924': 7478, '2925': 7479, '2926': 7480,
  13367. '2928': 7482, '2929': 7483, '2930': 7484, '2932': 7486, '2933': 7487,
  13368. '2934': 7488, '2936': 7490, '2937': 7491, '2938': 7492, '2940': 7494,
  13369. '2941': 7495, '2942': 7496, '2944': 7498, '2946': 7500, '2948': 7502,
  13370. '2950': 7504, '2951': 7505, '2952': 7506, '2954': 7508, '2955': 7509,
  13371. '2956': 7510, '2958': 7512, '2959': 7513, '2960': 7514, '2962': 7516,
  13372. '2963': 7517, '2964': 7518, '2966': 7520, '2967': 7521, '2968': 7522,
  13373. '2970': 7524, '2971': 7525, '2972': 7526, '2974': 7528, '2975': 7529,
  13374. '2976': 7530, '2978': 1537, '2979': 1538, '2980': 1539, '2982': 1549,
  13375. '2983': 1551, '2984': 1552, '2986': 1554, '2987': 1555, '2988': 1556,
  13376. '2990': 1623, '2991': 1624, '2995': 1775, '2999': 1791, '3002': 64290,
  13377. '3003': 64291, '3004': 64292, '3006': 64294, '3007': 64295, '3008': 64296,
  13378. '3011': 1900, '3014': 8223, '3015': 8244, '3017': 7532, '3018': 7533,
  13379. '3019': 7534, '3075': 7590, '3076': 7591, '3079': 7594, '3080': 7595,
  13380. '3083': 7598, '3084': 7599, '3087': 7602, '3088': 7603, '3091': 7606,
  13381. '3092': 7607, '3095': 7610, '3096': 7611, '3099': 7614, '3100': 7615,
  13382. '3103': 7618, '3104': 7619, '3107': 8337, '3108': 8338, '3116': 1884,
  13383. '3119': 1885, '3120': 1885, '3123': 1886, '3124': 1886, '3127': 1887,
  13384. '3128': 1887, '3131': 1888, '3132': 1888, '3135': 1889, '3136': 1889,
  13385. '3139': 1890, '3140': 1890, '3143': 1891, '3144': 1891, '3147': 1892,
  13386. '3148': 1892, '3153': 580, '3154': 581, '3157': 584, '3158': 585, '3161': 588,
  13387. '3162': 589, '3165': 891, '3166': 892, '3169': 1274, '3170': 1275,
  13388. '3173': 1278, '3174': 1279, '3181': 7622, '3182': 7623, '3282': 11799,
  13389. '3316': 578, '3379': 42785, '3393': 1159, '3416': 8377
  13390. };
  13391. // Some characters, e.g. copyrightserif, are mapped to the private use area and
  13392. // might not be displayed using standard fonts. Mapping/hacking well-known chars
  13393. // to the similar equivalents in the normal characters range.
  13394. var SpecialPUASymbols = {
  13395. '63721': 0x00A9, // copyrightsans (0xF8E9) => copyright
  13396. '63193': 0x00A9, // copyrightserif (0xF6D9) => copyright
  13397. '63720': 0x00AE, // registersans (0xF8E8) => registered
  13398. '63194': 0x00AE, // registerserif (0xF6DA) => registered
  13399. '63722': 0x2122, // trademarksans (0xF8EA) => trademark
  13400. '63195': 0x2122, // trademarkserif (0xF6DB) => trademark
  13401. '63729': 0x23A7, // bracelefttp (0xF8F1)
  13402. '63730': 0x23A8, // braceleftmid (0xF8F2)
  13403. '63731': 0x23A9, // braceleftbt (0xF8F3)
  13404. '63740': 0x23AB, // bracerighttp (0xF8FC)
  13405. '63741': 0x23AC, // bracerightmid (0xF8FD)
  13406. '63742': 0x23AD, // bracerightbt (0xF8FE)
  13407. '63726': 0x23A1, // bracketlefttp (0xF8EE)
  13408. '63727': 0x23A2, // bracketleftex (0xF8EF)
  13409. '63728': 0x23A3, // bracketleftbt (0xF8F0)
  13410. '63737': 0x23A4, // bracketrighttp (0xF8F9)
  13411. '63738': 0x23A5, // bracketrightex (0xF8FA)
  13412. '63739': 0x23A6, // bracketrightbt (0xF8FB)
  13413. '63723': 0x239B, // parenlefttp (0xF8EB)
  13414. '63724': 0x239C, // parenleftex (0xF8EC)
  13415. '63725': 0x239D, // parenleftbt (0xF8ED)
  13416. '63734': 0x239E, // parenrighttp (0xF8F6)
  13417. '63735': 0x239F, // parenrightex (0xF8F7)
  13418. '63736': 0x23A0, // parenrightbt (0xF8F8)
  13419. };
  13420. function mapSpecialUnicodeValues(code) {
  13421. if (code >= 0xFFF0 && code <= 0xFFFF) { // Specials unicode block.
  13422. return 0;
  13423. } else if (code >= 0xF600 && code <= 0xF8FF) {
  13424. return (SpecialPUASymbols[code] || code);
  13425. }
  13426. return code;
  13427. }
  13428. var UnicodeRanges = [
  13429. { 'begin': 0x0000, 'end': 0x007F }, // Basic Latin
  13430. { 'begin': 0x0080, 'end': 0x00FF }, // Latin-1 Supplement
  13431. { 'begin': 0x0100, 'end': 0x017F }, // Latin Extended-A
  13432. { 'begin': 0x0180, 'end': 0x024F }, // Latin Extended-B
  13433. { 'begin': 0x0250, 'end': 0x02AF }, // IPA Extensions
  13434. { 'begin': 0x02B0, 'end': 0x02FF }, // Spacing Modifier Letters
  13435. { 'begin': 0x0300, 'end': 0x036F }, // Combining Diacritical Marks
  13436. { 'begin': 0x0370, 'end': 0x03FF }, // Greek and Coptic
  13437. { 'begin': 0x2C80, 'end': 0x2CFF }, // Coptic
  13438. { 'begin': 0x0400, 'end': 0x04FF }, // Cyrillic
  13439. { 'begin': 0x0530, 'end': 0x058F }, // Armenian
  13440. { 'begin': 0x0590, 'end': 0x05FF }, // Hebrew
  13441. { 'begin': 0xA500, 'end': 0xA63F }, // Vai
  13442. { 'begin': 0x0600, 'end': 0x06FF }, // Arabic
  13443. { 'begin': 0x07C0, 'end': 0x07FF }, // NKo
  13444. { 'begin': 0x0900, 'end': 0x097F }, // Devanagari
  13445. { 'begin': 0x0980, 'end': 0x09FF }, // Bengali
  13446. { 'begin': 0x0A00, 'end': 0x0A7F }, // Gurmukhi
  13447. { 'begin': 0x0A80, 'end': 0x0AFF }, // Gujarati
  13448. { 'begin': 0x0B00, 'end': 0x0B7F }, // Oriya
  13449. { 'begin': 0x0B80, 'end': 0x0BFF }, // Tamil
  13450. { 'begin': 0x0C00, 'end': 0x0C7F }, // Telugu
  13451. { 'begin': 0x0C80, 'end': 0x0CFF }, // Kannada
  13452. { 'begin': 0x0D00, 'end': 0x0D7F }, // Malayalam
  13453. { 'begin': 0x0E00, 'end': 0x0E7F }, // Thai
  13454. { 'begin': 0x0E80, 'end': 0x0EFF }, // Lao
  13455. { 'begin': 0x10A0, 'end': 0x10FF }, // Georgian
  13456. { 'begin': 0x1B00, 'end': 0x1B7F }, // Balinese
  13457. { 'begin': 0x1100, 'end': 0x11FF }, // Hangul Jamo
  13458. { 'begin': 0x1E00, 'end': 0x1EFF }, // Latin Extended Additional
  13459. { 'begin': 0x1F00, 'end': 0x1FFF }, // Greek Extended
  13460. { 'begin': 0x2000, 'end': 0x206F }, // General Punctuation
  13461. { 'begin': 0x2070, 'end': 0x209F }, // Superscripts And Subscripts
  13462. { 'begin': 0x20A0, 'end': 0x20CF }, // Currency Symbol
  13463. { 'begin': 0x20D0, 'end': 0x20FF }, // Combining Diacritical Marks For Symbols
  13464. { 'begin': 0x2100, 'end': 0x214F }, // Letterlike Symbols
  13465. { 'begin': 0x2150, 'end': 0x218F }, // Number Forms
  13466. { 'begin': 0x2190, 'end': 0x21FF }, // Arrows
  13467. { 'begin': 0x2200, 'end': 0x22FF }, // Mathematical Operators
  13468. { 'begin': 0x2300, 'end': 0x23FF }, // Miscellaneous Technical
  13469. { 'begin': 0x2400, 'end': 0x243F }, // Control Pictures
  13470. { 'begin': 0x2440, 'end': 0x245F }, // Optical Character Recognition
  13471. { 'begin': 0x2460, 'end': 0x24FF }, // Enclosed Alphanumerics
  13472. { 'begin': 0x2500, 'end': 0x257F }, // Box Drawing
  13473. { 'begin': 0x2580, 'end': 0x259F }, // Block Elements
  13474. { 'begin': 0x25A0, 'end': 0x25FF }, // Geometric Shapes
  13475. { 'begin': 0x2600, 'end': 0x26FF }, // Miscellaneous Symbols
  13476. { 'begin': 0x2700, 'end': 0x27BF }, // Dingbats
  13477. { 'begin': 0x3000, 'end': 0x303F }, // CJK Symbols And Punctuation
  13478. { 'begin': 0x3040, 'end': 0x309F }, // Hiragana
  13479. { 'begin': 0x30A0, 'end': 0x30FF }, // Katakana
  13480. { 'begin': 0x3100, 'end': 0x312F }, // Bopomofo
  13481. { 'begin': 0x3130, 'end': 0x318F }, // Hangul Compatibility Jamo
  13482. { 'begin': 0xA840, 'end': 0xA87F }, // Phags-pa
  13483. { 'begin': 0x3200, 'end': 0x32FF }, // Enclosed CJK Letters And Months
  13484. { 'begin': 0x3300, 'end': 0x33FF }, // CJK Compatibility
  13485. { 'begin': 0xAC00, 'end': 0xD7AF }, // Hangul Syllables
  13486. { 'begin': 0xD800, 'end': 0xDFFF }, // Non-Plane 0 *
  13487. { 'begin': 0x10900, 'end': 0x1091F }, // Phoenicia
  13488. { 'begin': 0x4E00, 'end': 0x9FFF }, // CJK Unified Ideographs
  13489. { 'begin': 0xE000, 'end': 0xF8FF }, // Private Use Area (plane 0)
  13490. { 'begin': 0x31C0, 'end': 0x31EF }, // CJK Strokes
  13491. { 'begin': 0xFB00, 'end': 0xFB4F }, // Alphabetic Presentation Forms
  13492. { 'begin': 0xFB50, 'end': 0xFDFF }, // Arabic Presentation Forms-A
  13493. { 'begin': 0xFE20, 'end': 0xFE2F }, // Combining Half Marks
  13494. { 'begin': 0xFE10, 'end': 0xFE1F }, // Vertical Forms
  13495. { 'begin': 0xFE50, 'end': 0xFE6F }, // Small Form Variants
  13496. { 'begin': 0xFE70, 'end': 0xFEFF }, // Arabic Presentation Forms-B
  13497. { 'begin': 0xFF00, 'end': 0xFFEF }, // Halfwidth And Fullwidth Forms
  13498. { 'begin': 0xFFF0, 'end': 0xFFFF }, // Specials
  13499. { 'begin': 0x0F00, 'end': 0x0FFF }, // Tibetan
  13500. { 'begin': 0x0700, 'end': 0x074F }, // Syriac
  13501. { 'begin': 0x0780, 'end': 0x07BF }, // Thaana
  13502. { 'begin': 0x0D80, 'end': 0x0DFF }, // Sinhala
  13503. { 'begin': 0x1000, 'end': 0x109F }, // Myanmar
  13504. { 'begin': 0x1200, 'end': 0x137F }, // Ethiopic
  13505. { 'begin': 0x13A0, 'end': 0x13FF }, // Cherokee
  13506. { 'begin': 0x1400, 'end': 0x167F }, // Unified Canadian Aboriginal Syllabics
  13507. { 'begin': 0x1680, 'end': 0x169F }, // Ogham
  13508. { 'begin': 0x16A0, 'end': 0x16FF }, // Runic
  13509. { 'begin': 0x1780, 'end': 0x17FF }, // Khmer
  13510. { 'begin': 0x1800, 'end': 0x18AF }, // Mongolian
  13511. { 'begin': 0x2800, 'end': 0x28FF }, // Braille Patterns
  13512. { 'begin': 0xA000, 'end': 0xA48F }, // Yi Syllables
  13513. { 'begin': 0x1700, 'end': 0x171F }, // Tagalog
  13514. { 'begin': 0x10300, 'end': 0x1032F }, // Old Italic
  13515. { 'begin': 0x10330, 'end': 0x1034F }, // Gothic
  13516. { 'begin': 0x10400, 'end': 0x1044F }, // Deseret
  13517. { 'begin': 0x1D000, 'end': 0x1D0FF }, // Byzantine Musical Symbols
  13518. { 'begin': 0x1D400, 'end': 0x1D7FF }, // Mathematical Alphanumeric Symbols
  13519. { 'begin': 0xFF000, 'end': 0xFFFFD }, // Private Use (plane 15)
  13520. { 'begin': 0xFE00, 'end': 0xFE0F }, // Variation Selectors
  13521. { 'begin': 0xE0000, 'end': 0xE007F }, // Tags
  13522. { 'begin': 0x1900, 'end': 0x194F }, // Limbu
  13523. { 'begin': 0x1950, 'end': 0x197F }, // Tai Le
  13524. { 'begin': 0x1980, 'end': 0x19DF }, // New Tai Lue
  13525. { 'begin': 0x1A00, 'end': 0x1A1F }, // Buginese
  13526. { 'begin': 0x2C00, 'end': 0x2C5F }, // Glagolitic
  13527. { 'begin': 0x2D30, 'end': 0x2D7F }, // Tifinagh
  13528. { 'begin': 0x4DC0, 'end': 0x4DFF }, // Yijing Hexagram Symbols
  13529. { 'begin': 0xA800, 'end': 0xA82F }, // Syloti Nagri
  13530. { 'begin': 0x10000, 'end': 0x1007F }, // Linear B Syllabary
  13531. { 'begin': 0x10140, 'end': 0x1018F }, // Ancient Greek Numbers
  13532. { 'begin': 0x10380, 'end': 0x1039F }, // Ugaritic
  13533. { 'begin': 0x103A0, 'end': 0x103DF }, // Old Persian
  13534. { 'begin': 0x10450, 'end': 0x1047F }, // Shavian
  13535. { 'begin': 0x10480, 'end': 0x104AF }, // Osmanya
  13536. { 'begin': 0x10800, 'end': 0x1083F }, // Cypriot Syllabary
  13537. { 'begin': 0x10A00, 'end': 0x10A5F }, // Kharoshthi
  13538. { 'begin': 0x1D300, 'end': 0x1D35F }, // Tai Xuan Jing Symbols
  13539. { 'begin': 0x12000, 'end': 0x123FF }, // Cuneiform
  13540. { 'begin': 0x1D360, 'end': 0x1D37F }, // Counting Rod Numerals
  13541. { 'begin': 0x1B80, 'end': 0x1BBF }, // Sundanese
  13542. { 'begin': 0x1C00, 'end': 0x1C4F }, // Lepcha
  13543. { 'begin': 0x1C50, 'end': 0x1C7F }, // Ol Chiki
  13544. { 'begin': 0xA880, 'end': 0xA8DF }, // Saurashtra
  13545. { 'begin': 0xA900, 'end': 0xA92F }, // Kayah Li
  13546. { 'begin': 0xA930, 'end': 0xA95F }, // Rejang
  13547. { 'begin': 0xAA00, 'end': 0xAA5F }, // Cham
  13548. { 'begin': 0x10190, 'end': 0x101CF }, // Ancient Symbols
  13549. { 'begin': 0x101D0, 'end': 0x101FF }, // Phaistos Disc
  13550. { 'begin': 0x102A0, 'end': 0x102DF }, // Carian
  13551. { 'begin': 0x1F030, 'end': 0x1F09F } // Domino Tiles
  13552. ];
  13553. var MacStandardGlyphOrdering = [
  13554. '.notdef', '.null', 'nonmarkingreturn', 'space', 'exclam', 'quotedbl',
  13555. 'numbersign', 'dollar', 'percent', 'ampersand', 'quotesingle', 'parenleft',
  13556. 'parenright', 'asterisk', 'plus', 'comma', 'hyphen', 'period', 'slash',
  13557. 'zero', 'one', 'two', 'three', 'four', 'five', 'six', 'seven', 'eight',
  13558. 'nine', 'colon', 'semicolon', 'less', 'equal', 'greater', 'question', 'at',
  13559. 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O',
  13560. 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z', 'bracketleft',
  13561. 'backslash', 'bracketright', 'asciicircum', 'underscore', 'grave', 'a', 'b',
  13562. 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q',
  13563. 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', 'braceleft', 'bar', 'braceright',
  13564. 'asciitilde', 'Adieresis', 'Aring', 'Ccedilla', 'Eacute', 'Ntilde',
  13565. 'Odieresis', 'Udieresis', 'aacute', 'agrave', 'acircumflex', 'adieresis',
  13566. 'atilde', 'aring', 'ccedilla', 'eacute', 'egrave', 'ecircumflex', 'edieresis',
  13567. 'iacute', 'igrave', 'icircumflex', 'idieresis', 'ntilde', 'oacute', 'ograve',
  13568. 'ocircumflex', 'odieresis', 'otilde', 'uacute', 'ugrave', 'ucircumflex',
  13569. 'udieresis', 'dagger', 'degree', 'cent', 'sterling', 'section', 'bullet',
  13570. 'paragraph', 'germandbls', 'registered', 'copyright', 'trademark', 'acute',
  13571. 'dieresis', 'notequal', 'AE', 'Oslash', 'infinity', 'plusminus', 'lessequal',
  13572. 'greaterequal', 'yen', 'mu', 'partialdiff', 'summation', 'product', 'pi',
  13573. 'integral', 'ordfeminine', 'ordmasculine', 'Omega', 'ae', 'oslash',
  13574. 'questiondown', 'exclamdown', 'logicalnot', 'radical', 'florin',
  13575. 'approxequal', 'Delta', 'guillemotleft', 'guillemotright', 'ellipsis',
  13576. 'nonbreakingspace', 'Agrave', 'Atilde', 'Otilde', 'OE', 'oe', 'endash',
  13577. 'emdash', 'quotedblleft', 'quotedblright', 'quoteleft', 'quoteright',
  13578. 'divide', 'lozenge', 'ydieresis', 'Ydieresis', 'fraction', 'currency',
  13579. 'guilsinglleft', 'guilsinglright', 'fi', 'fl', 'daggerdbl', 'periodcentered',
  13580. 'quotesinglbase', 'quotedblbase', 'perthousand', 'Acircumflex',
  13581. 'Ecircumflex', 'Aacute', 'Edieresis', 'Egrave', 'Iacute', 'Icircumflex',
  13582. 'Idieresis', 'Igrave', 'Oacute', 'Ocircumflex', 'apple', 'Ograve', 'Uacute',
  13583. 'Ucircumflex', 'Ugrave', 'dotlessi', 'circumflex', 'tilde', 'macron',
  13584. 'breve', 'dotaccent', 'ring', 'cedilla', 'hungarumlaut', 'ogonek', 'caron',
  13585. 'Lslash', 'lslash', 'Scaron', 'scaron', 'Zcaron', 'zcaron', 'brokenbar',
  13586. 'Eth', 'eth', 'Yacute', 'yacute', 'Thorn', 'thorn', 'minus', 'multiply',
  13587. 'onesuperior', 'twosuperior', 'threesuperior', 'onehalf', 'onequarter',
  13588. 'threequarters', 'franc', 'Gbreve', 'gbreve', 'Idotaccent', 'Scedilla',
  13589. 'scedilla', 'Cacute', 'cacute', 'Ccaron', 'ccaron', 'dcroat'];
  13590. function getUnicodeRangeFor(value) {
  13591. for (var i = 0, ii = UnicodeRanges.length; i < ii; i++) {
  13592. var range = UnicodeRanges[i];
  13593. if (value >= range.begin && value < range.end) {
  13594. return i;
  13595. }
  13596. }
  13597. return -1;
  13598. }
  13599. function isRTLRangeFor(value) {
  13600. var range = UnicodeRanges[13];
  13601. if (value >= range.begin && value < range.end) {
  13602. return true;
  13603. }
  13604. range = UnicodeRanges[11];
  13605. if (value >= range.begin && value < range.end) {
  13606. return true;
  13607. }
  13608. return false;
  13609. }
  13610. // The normalization table is obtained by filtering the Unicode characters
  13611. // database with <compat> entries.
  13612. var NormalizedUnicodes = {
  13613. '\u00A8': '\u0020\u0308',
  13614. '\u00AF': '\u0020\u0304',
  13615. '\u00B4': '\u0020\u0301',
  13616. '\u00B5': '\u03BC',
  13617. '\u00B8': '\u0020\u0327',
  13618. '\u0132': '\u0049\u004A',
  13619. '\u0133': '\u0069\u006A',
  13620. '\u013F': '\u004C\u00B7',
  13621. '\u0140': '\u006C\u00B7',
  13622. '\u0149': '\u02BC\u006E',
  13623. '\u017F': '\u0073',
  13624. '\u01C4': '\u0044\u017D',
  13625. '\u01C5': '\u0044\u017E',
  13626. '\u01C6': '\u0064\u017E',
  13627. '\u01C7': '\u004C\u004A',
  13628. '\u01C8': '\u004C\u006A',
  13629. '\u01C9': '\u006C\u006A',
  13630. '\u01CA': '\u004E\u004A',
  13631. '\u01CB': '\u004E\u006A',
  13632. '\u01CC': '\u006E\u006A',
  13633. '\u01F1': '\u0044\u005A',
  13634. '\u01F2': '\u0044\u007A',
  13635. '\u01F3': '\u0064\u007A',
  13636. '\u02D8': '\u0020\u0306',
  13637. '\u02D9': '\u0020\u0307',
  13638. '\u02DA': '\u0020\u030A',
  13639. '\u02DB': '\u0020\u0328',
  13640. '\u02DC': '\u0020\u0303',
  13641. '\u02DD': '\u0020\u030B',
  13642. '\u037A': '\u0020\u0345',
  13643. '\u0384': '\u0020\u0301',
  13644. '\u03D0': '\u03B2',
  13645. '\u03D1': '\u03B8',
  13646. '\u03D2': '\u03A5',
  13647. '\u03D5': '\u03C6',
  13648. '\u03D6': '\u03C0',
  13649. '\u03F0': '\u03BA',
  13650. '\u03F1': '\u03C1',
  13651. '\u03F2': '\u03C2',
  13652. '\u03F4': '\u0398',
  13653. '\u03F5': '\u03B5',
  13654. '\u03F9': '\u03A3',
  13655. '\u0587': '\u0565\u0582',
  13656. '\u0675': '\u0627\u0674',
  13657. '\u0676': '\u0648\u0674',
  13658. '\u0677': '\u06C7\u0674',
  13659. '\u0678': '\u064A\u0674',
  13660. '\u0E33': '\u0E4D\u0E32',
  13661. '\u0EB3': '\u0ECD\u0EB2',
  13662. '\u0EDC': '\u0EAB\u0E99',
  13663. '\u0EDD': '\u0EAB\u0EA1',
  13664. '\u0F77': '\u0FB2\u0F81',
  13665. '\u0F79': '\u0FB3\u0F81',
  13666. '\u1E9A': '\u0061\u02BE',
  13667. '\u1FBD': '\u0020\u0313',
  13668. '\u1FBF': '\u0020\u0313',
  13669. '\u1FC0': '\u0020\u0342',
  13670. '\u1FFE': '\u0020\u0314',
  13671. '\u2002': '\u0020',
  13672. '\u2003': '\u0020',
  13673. '\u2004': '\u0020',
  13674. '\u2005': '\u0020',
  13675. '\u2006': '\u0020',
  13676. '\u2008': '\u0020',
  13677. '\u2009': '\u0020',
  13678. '\u200A': '\u0020',
  13679. '\u2017': '\u0020\u0333',
  13680. '\u2024': '\u002E',
  13681. '\u2025': '\u002E\u002E',
  13682. '\u2026': '\u002E\u002E\u002E',
  13683. '\u2033': '\u2032\u2032',
  13684. '\u2034': '\u2032\u2032\u2032',
  13685. '\u2036': '\u2035\u2035',
  13686. '\u2037': '\u2035\u2035\u2035',
  13687. '\u203C': '\u0021\u0021',
  13688. '\u203E': '\u0020\u0305',
  13689. '\u2047': '\u003F\u003F',
  13690. '\u2048': '\u003F\u0021',
  13691. '\u2049': '\u0021\u003F',
  13692. '\u2057': '\u2032\u2032\u2032\u2032',
  13693. '\u205F': '\u0020',
  13694. '\u20A8': '\u0052\u0073',
  13695. '\u2100': '\u0061\u002F\u0063',
  13696. '\u2101': '\u0061\u002F\u0073',
  13697. '\u2103': '\u00B0\u0043',
  13698. '\u2105': '\u0063\u002F\u006F',
  13699. '\u2106': '\u0063\u002F\u0075',
  13700. '\u2107': '\u0190',
  13701. '\u2109': '\u00B0\u0046',
  13702. '\u2116': '\u004E\u006F',
  13703. '\u2121': '\u0054\u0045\u004C',
  13704. '\u2135': '\u05D0',
  13705. '\u2136': '\u05D1',
  13706. '\u2137': '\u05D2',
  13707. '\u2138': '\u05D3',
  13708. '\u213B': '\u0046\u0041\u0058',
  13709. '\u2160': '\u0049',
  13710. '\u2161': '\u0049\u0049',
  13711. '\u2162': '\u0049\u0049\u0049',
  13712. '\u2163': '\u0049\u0056',
  13713. '\u2164': '\u0056',
  13714. '\u2165': '\u0056\u0049',
  13715. '\u2166': '\u0056\u0049\u0049',
  13716. '\u2167': '\u0056\u0049\u0049\u0049',
  13717. '\u2168': '\u0049\u0058',
  13718. '\u2169': '\u0058',
  13719. '\u216A': '\u0058\u0049',
  13720. '\u216B': '\u0058\u0049\u0049',
  13721. '\u216C': '\u004C',
  13722. '\u216D': '\u0043',
  13723. '\u216E': '\u0044',
  13724. '\u216F': '\u004D',
  13725. '\u2170': '\u0069',
  13726. '\u2171': '\u0069\u0069',
  13727. '\u2172': '\u0069\u0069\u0069',
  13728. '\u2173': '\u0069\u0076',
  13729. '\u2174': '\u0076',
  13730. '\u2175': '\u0076\u0069',
  13731. '\u2176': '\u0076\u0069\u0069',
  13732. '\u2177': '\u0076\u0069\u0069\u0069',
  13733. '\u2178': '\u0069\u0078',
  13734. '\u2179': '\u0078',
  13735. '\u217A': '\u0078\u0069',
  13736. '\u217B': '\u0078\u0069\u0069',
  13737. '\u217C': '\u006C',
  13738. '\u217D': '\u0063',
  13739. '\u217E': '\u0064',
  13740. '\u217F': '\u006D',
  13741. '\u222C': '\u222B\u222B',
  13742. '\u222D': '\u222B\u222B\u222B',
  13743. '\u222F': '\u222E\u222E',
  13744. '\u2230': '\u222E\u222E\u222E',
  13745. '\u2474': '\u0028\u0031\u0029',
  13746. '\u2475': '\u0028\u0032\u0029',
  13747. '\u2476': '\u0028\u0033\u0029',
  13748. '\u2477': '\u0028\u0034\u0029',
  13749. '\u2478': '\u0028\u0035\u0029',
  13750. '\u2479': '\u0028\u0036\u0029',
  13751. '\u247A': '\u0028\u0037\u0029',
  13752. '\u247B': '\u0028\u0038\u0029',
  13753. '\u247C': '\u0028\u0039\u0029',
  13754. '\u247D': '\u0028\u0031\u0030\u0029',
  13755. '\u247E': '\u0028\u0031\u0031\u0029',
  13756. '\u247F': '\u0028\u0031\u0032\u0029',
  13757. '\u2480': '\u0028\u0031\u0033\u0029',
  13758. '\u2481': '\u0028\u0031\u0034\u0029',
  13759. '\u2482': '\u0028\u0031\u0035\u0029',
  13760. '\u2483': '\u0028\u0031\u0036\u0029',
  13761. '\u2484': '\u0028\u0031\u0037\u0029',
  13762. '\u2485': '\u0028\u0031\u0038\u0029',
  13763. '\u2486': '\u0028\u0031\u0039\u0029',
  13764. '\u2487': '\u0028\u0032\u0030\u0029',
  13765. '\u2488': '\u0031\u002E',
  13766. '\u2489': '\u0032\u002E',
  13767. '\u248A': '\u0033\u002E',
  13768. '\u248B': '\u0034\u002E',
  13769. '\u248C': '\u0035\u002E',
  13770. '\u248D': '\u0036\u002E',
  13771. '\u248E': '\u0037\u002E',
  13772. '\u248F': '\u0038\u002E',
  13773. '\u2490': '\u0039\u002E',
  13774. '\u2491': '\u0031\u0030\u002E',
  13775. '\u2492': '\u0031\u0031\u002E',
  13776. '\u2493': '\u0031\u0032\u002E',
  13777. '\u2494': '\u0031\u0033\u002E',
  13778. '\u2495': '\u0031\u0034\u002E',
  13779. '\u2496': '\u0031\u0035\u002E',
  13780. '\u2497': '\u0031\u0036\u002E',
  13781. '\u2498': '\u0031\u0037\u002E',
  13782. '\u2499': '\u0031\u0038\u002E',
  13783. '\u249A': '\u0031\u0039\u002E',
  13784. '\u249B': '\u0032\u0030\u002E',
  13785. '\u249C': '\u0028\u0061\u0029',
  13786. '\u249D': '\u0028\u0062\u0029',
  13787. '\u249E': '\u0028\u0063\u0029',
  13788. '\u249F': '\u0028\u0064\u0029',
  13789. '\u24A0': '\u0028\u0065\u0029',
  13790. '\u24A1': '\u0028\u0066\u0029',
  13791. '\u24A2': '\u0028\u0067\u0029',
  13792. '\u24A3': '\u0028\u0068\u0029',
  13793. '\u24A4': '\u0028\u0069\u0029',
  13794. '\u24A5': '\u0028\u006A\u0029',
  13795. '\u24A6': '\u0028\u006B\u0029',
  13796. '\u24A7': '\u0028\u006C\u0029',
  13797. '\u24A8': '\u0028\u006D\u0029',
  13798. '\u24A9': '\u0028\u006E\u0029',
  13799. '\u24AA': '\u0028\u006F\u0029',
  13800. '\u24AB': '\u0028\u0070\u0029',
  13801. '\u24AC': '\u0028\u0071\u0029',
  13802. '\u24AD': '\u0028\u0072\u0029',
  13803. '\u24AE': '\u0028\u0073\u0029',
  13804. '\u24AF': '\u0028\u0074\u0029',
  13805. '\u24B0': '\u0028\u0075\u0029',
  13806. '\u24B1': '\u0028\u0076\u0029',
  13807. '\u24B2': '\u0028\u0077\u0029',
  13808. '\u24B3': '\u0028\u0078\u0029',
  13809. '\u24B4': '\u0028\u0079\u0029',
  13810. '\u24B5': '\u0028\u007A\u0029',
  13811. '\u2A0C': '\u222B\u222B\u222B\u222B',
  13812. '\u2A74': '\u003A\u003A\u003D',
  13813. '\u2A75': '\u003D\u003D',
  13814. '\u2A76': '\u003D\u003D\u003D',
  13815. '\u2E9F': '\u6BCD',
  13816. '\u2EF3': '\u9F9F',
  13817. '\u2F00': '\u4E00',
  13818. '\u2F01': '\u4E28',
  13819. '\u2F02': '\u4E36',
  13820. '\u2F03': '\u4E3F',
  13821. '\u2F04': '\u4E59',
  13822. '\u2F05': '\u4E85',
  13823. '\u2F06': '\u4E8C',
  13824. '\u2F07': '\u4EA0',
  13825. '\u2F08': '\u4EBA',
  13826. '\u2F09': '\u513F',
  13827. '\u2F0A': '\u5165',
  13828. '\u2F0B': '\u516B',
  13829. '\u2F0C': '\u5182',
  13830. '\u2F0D': '\u5196',
  13831. '\u2F0E': '\u51AB',
  13832. '\u2F0F': '\u51E0',
  13833. '\u2F10': '\u51F5',
  13834. '\u2F11': '\u5200',
  13835. '\u2F12': '\u529B',
  13836. '\u2F13': '\u52F9',
  13837. '\u2F14': '\u5315',
  13838. '\u2F15': '\u531A',
  13839. '\u2F16': '\u5338',
  13840. '\u2F17': '\u5341',
  13841. '\u2F18': '\u535C',
  13842. '\u2F19': '\u5369',
  13843. '\u2F1A': '\u5382',
  13844. '\u2F1B': '\u53B6',
  13845. '\u2F1C': '\u53C8',
  13846. '\u2F1D': '\u53E3',
  13847. '\u2F1E': '\u56D7',
  13848. '\u2F1F': '\u571F',
  13849. '\u2F20': '\u58EB',
  13850. '\u2F21': '\u5902',
  13851. '\u2F22': '\u590A',
  13852. '\u2F23': '\u5915',
  13853. '\u2F24': '\u5927',
  13854. '\u2F25': '\u5973',
  13855. '\u2F26': '\u5B50',
  13856. '\u2F27': '\u5B80',
  13857. '\u2F28': '\u5BF8',
  13858. '\u2F29': '\u5C0F',
  13859. '\u2F2A': '\u5C22',
  13860. '\u2F2B': '\u5C38',
  13861. '\u2F2C': '\u5C6E',
  13862. '\u2F2D': '\u5C71',
  13863. '\u2F2E': '\u5DDB',
  13864. '\u2F2F': '\u5DE5',
  13865. '\u2F30': '\u5DF1',
  13866. '\u2F31': '\u5DFE',
  13867. '\u2F32': '\u5E72',
  13868. '\u2F33': '\u5E7A',
  13869. '\u2F34': '\u5E7F',
  13870. '\u2F35': '\u5EF4',
  13871. '\u2F36': '\u5EFE',
  13872. '\u2F37': '\u5F0B',
  13873. '\u2F38': '\u5F13',
  13874. '\u2F39': '\u5F50',
  13875. '\u2F3A': '\u5F61',
  13876. '\u2F3B': '\u5F73',
  13877. '\u2F3C': '\u5FC3',
  13878. '\u2F3D': '\u6208',
  13879. '\u2F3E': '\u6236',
  13880. '\u2F3F': '\u624B',
  13881. '\u2F40': '\u652F',
  13882. '\u2F41': '\u6534',
  13883. '\u2F42': '\u6587',
  13884. '\u2F43': '\u6597',
  13885. '\u2F44': '\u65A4',
  13886. '\u2F45': '\u65B9',
  13887. '\u2F46': '\u65E0',
  13888. '\u2F47': '\u65E5',
  13889. '\u2F48': '\u66F0',
  13890. '\u2F49': '\u6708',
  13891. '\u2F4A': '\u6728',
  13892. '\u2F4B': '\u6B20',
  13893. '\u2F4C': '\u6B62',
  13894. '\u2F4D': '\u6B79',
  13895. '\u2F4E': '\u6BB3',
  13896. '\u2F4F': '\u6BCB',
  13897. '\u2F50': '\u6BD4',
  13898. '\u2F51': '\u6BDB',
  13899. '\u2F52': '\u6C0F',
  13900. '\u2F53': '\u6C14',
  13901. '\u2F54': '\u6C34',
  13902. '\u2F55': '\u706B',
  13903. '\u2F56': '\u722A',
  13904. '\u2F57': '\u7236',
  13905. '\u2F58': '\u723B',
  13906. '\u2F59': '\u723F',
  13907. '\u2F5A': '\u7247',
  13908. '\u2F5B': '\u7259',
  13909. '\u2F5C': '\u725B',
  13910. '\u2F5D': '\u72AC',
  13911. '\u2F5E': '\u7384',
  13912. '\u2F5F': '\u7389',
  13913. '\u2F60': '\u74DC',
  13914. '\u2F61': '\u74E6',
  13915. '\u2F62': '\u7518',
  13916. '\u2F63': '\u751F',
  13917. '\u2F64': '\u7528',
  13918. '\u2F65': '\u7530',
  13919. '\u2F66': '\u758B',
  13920. '\u2F67': '\u7592',
  13921. '\u2F68': '\u7676',
  13922. '\u2F69': '\u767D',
  13923. '\u2F6A': '\u76AE',
  13924. '\u2F6B': '\u76BF',
  13925. '\u2F6C': '\u76EE',
  13926. '\u2F6D': '\u77DB',
  13927. '\u2F6E': '\u77E2',
  13928. '\u2F6F': '\u77F3',
  13929. '\u2F70': '\u793A',
  13930. '\u2F71': '\u79B8',
  13931. '\u2F72': '\u79BE',
  13932. '\u2F73': '\u7A74',
  13933. '\u2F74': '\u7ACB',
  13934. '\u2F75': '\u7AF9',
  13935. '\u2F76': '\u7C73',
  13936. '\u2F77': '\u7CF8',
  13937. '\u2F78': '\u7F36',
  13938. '\u2F79': '\u7F51',
  13939. '\u2F7A': '\u7F8A',
  13940. '\u2F7B': '\u7FBD',
  13941. '\u2F7C': '\u8001',
  13942. '\u2F7D': '\u800C',
  13943. '\u2F7E': '\u8012',
  13944. '\u2F7F': '\u8033',
  13945. '\u2F80': '\u807F',
  13946. '\u2F81': '\u8089',
  13947. '\u2F82': '\u81E3',
  13948. '\u2F83': '\u81EA',
  13949. '\u2F84': '\u81F3',
  13950. '\u2F85': '\u81FC',
  13951. '\u2F86': '\u820C',
  13952. '\u2F87': '\u821B',
  13953. '\u2F88': '\u821F',
  13954. '\u2F89': '\u826E',
  13955. '\u2F8A': '\u8272',
  13956. '\u2F8B': '\u8278',
  13957. '\u2F8C': '\u864D',
  13958. '\u2F8D': '\u866B',
  13959. '\u2F8E': '\u8840',
  13960. '\u2F8F': '\u884C',
  13961. '\u2F90': '\u8863',
  13962. '\u2F91': '\u897E',
  13963. '\u2F92': '\u898B',
  13964. '\u2F93': '\u89D2',
  13965. '\u2F94': '\u8A00',
  13966. '\u2F95': '\u8C37',
  13967. '\u2F96': '\u8C46',
  13968. '\u2F97': '\u8C55',
  13969. '\u2F98': '\u8C78',
  13970. '\u2F99': '\u8C9D',
  13971. '\u2F9A': '\u8D64',
  13972. '\u2F9B': '\u8D70',
  13973. '\u2F9C': '\u8DB3',
  13974. '\u2F9D': '\u8EAB',
  13975. '\u2F9E': '\u8ECA',
  13976. '\u2F9F': '\u8F9B',
  13977. '\u2FA0': '\u8FB0',
  13978. '\u2FA1': '\u8FB5',
  13979. '\u2FA2': '\u9091',
  13980. '\u2FA3': '\u9149',
  13981. '\u2FA4': '\u91C6',
  13982. '\u2FA5': '\u91CC',
  13983. '\u2FA6': '\u91D1',
  13984. '\u2FA7': '\u9577',
  13985. '\u2FA8': '\u9580',
  13986. '\u2FA9': '\u961C',
  13987. '\u2FAA': '\u96B6',
  13988. '\u2FAB': '\u96B9',
  13989. '\u2FAC': '\u96E8',
  13990. '\u2FAD': '\u9751',
  13991. '\u2FAE': '\u975E',
  13992. '\u2FAF': '\u9762',
  13993. '\u2FB0': '\u9769',
  13994. '\u2FB1': '\u97CB',
  13995. '\u2FB2': '\u97ED',
  13996. '\u2FB3': '\u97F3',
  13997. '\u2FB4': '\u9801',
  13998. '\u2FB5': '\u98A8',
  13999. '\u2FB6': '\u98DB',
  14000. '\u2FB7': '\u98DF',
  14001. '\u2FB8': '\u9996',
  14002. '\u2FB9': '\u9999',
  14003. '\u2FBA': '\u99AC',
  14004. '\u2FBB': '\u9AA8',
  14005. '\u2FBC': '\u9AD8',
  14006. '\u2FBD': '\u9ADF',
  14007. '\u2FBE': '\u9B25',
  14008. '\u2FBF': '\u9B2F',
  14009. '\u2FC0': '\u9B32',
  14010. '\u2FC1': '\u9B3C',
  14011. '\u2FC2': '\u9B5A',
  14012. '\u2FC3': '\u9CE5',
  14013. '\u2FC4': '\u9E75',
  14014. '\u2FC5': '\u9E7F',
  14015. '\u2FC6': '\u9EA5',
  14016. '\u2FC7': '\u9EBB',
  14017. '\u2FC8': '\u9EC3',
  14018. '\u2FC9': '\u9ECD',
  14019. '\u2FCA': '\u9ED1',
  14020. '\u2FCB': '\u9EF9',
  14021. '\u2FCC': '\u9EFD',
  14022. '\u2FCD': '\u9F0E',
  14023. '\u2FCE': '\u9F13',
  14024. '\u2FCF': '\u9F20',
  14025. '\u2FD0': '\u9F3B',
  14026. '\u2FD1': '\u9F4A',
  14027. '\u2FD2': '\u9F52',
  14028. '\u2FD3': '\u9F8D',
  14029. '\u2FD4': '\u9F9C',
  14030. '\u2FD5': '\u9FA0',
  14031. '\u3036': '\u3012',
  14032. '\u3038': '\u5341',
  14033. '\u3039': '\u5344',
  14034. '\u303A': '\u5345',
  14035. '\u309B': '\u0020\u3099',
  14036. '\u309C': '\u0020\u309A',
  14037. '\u3131': '\u1100',
  14038. '\u3132': '\u1101',
  14039. '\u3133': '\u11AA',
  14040. '\u3134': '\u1102',
  14041. '\u3135': '\u11AC',
  14042. '\u3136': '\u11AD',
  14043. '\u3137': '\u1103',
  14044. '\u3138': '\u1104',
  14045. '\u3139': '\u1105',
  14046. '\u313A': '\u11B0',
  14047. '\u313B': '\u11B1',
  14048. '\u313C': '\u11B2',
  14049. '\u313D': '\u11B3',
  14050. '\u313E': '\u11B4',
  14051. '\u313F': '\u11B5',
  14052. '\u3140': '\u111A',
  14053. '\u3141': '\u1106',
  14054. '\u3142': '\u1107',
  14055. '\u3143': '\u1108',
  14056. '\u3144': '\u1121',
  14057. '\u3145': '\u1109',
  14058. '\u3146': '\u110A',
  14059. '\u3147': '\u110B',
  14060. '\u3148': '\u110C',
  14061. '\u3149': '\u110D',
  14062. '\u314A': '\u110E',
  14063. '\u314B': '\u110F',
  14064. '\u314C': '\u1110',
  14065. '\u314D': '\u1111',
  14066. '\u314E': '\u1112',
  14067. '\u314F': '\u1161',
  14068. '\u3150': '\u1162',
  14069. '\u3151': '\u1163',
  14070. '\u3152': '\u1164',
  14071. '\u3153': '\u1165',
  14072. '\u3154': '\u1166',
  14073. '\u3155': '\u1167',
  14074. '\u3156': '\u1168',
  14075. '\u3157': '\u1169',
  14076. '\u3158': '\u116A',
  14077. '\u3159': '\u116B',
  14078. '\u315A': '\u116C',
  14079. '\u315B': '\u116D',
  14080. '\u315C': '\u116E',
  14081. '\u315D': '\u116F',
  14082. '\u315E': '\u1170',
  14083. '\u315F': '\u1171',
  14084. '\u3160': '\u1172',
  14085. '\u3161': '\u1173',
  14086. '\u3162': '\u1174',
  14087. '\u3163': '\u1175',
  14088. '\u3164': '\u1160',
  14089. '\u3165': '\u1114',
  14090. '\u3166': '\u1115',
  14091. '\u3167': '\u11C7',
  14092. '\u3168': '\u11C8',
  14093. '\u3169': '\u11CC',
  14094. '\u316A': '\u11CE',
  14095. '\u316B': '\u11D3',
  14096. '\u316C': '\u11D7',
  14097. '\u316D': '\u11D9',
  14098. '\u316E': '\u111C',
  14099. '\u316F': '\u11DD',
  14100. '\u3170': '\u11DF',
  14101. '\u3171': '\u111D',
  14102. '\u3172': '\u111E',
  14103. '\u3173': '\u1120',
  14104. '\u3174': '\u1122',
  14105. '\u3175': '\u1123',
  14106. '\u3176': '\u1127',
  14107. '\u3177': '\u1129',
  14108. '\u3178': '\u112B',
  14109. '\u3179': '\u112C',
  14110. '\u317A': '\u112D',
  14111. '\u317B': '\u112E',
  14112. '\u317C': '\u112F',
  14113. '\u317D': '\u1132',
  14114. '\u317E': '\u1136',
  14115. '\u317F': '\u1140',
  14116. '\u3180': '\u1147',
  14117. '\u3181': '\u114C',
  14118. '\u3182': '\u11F1',
  14119. '\u3183': '\u11F2',
  14120. '\u3184': '\u1157',
  14121. '\u3185': '\u1158',
  14122. '\u3186': '\u1159',
  14123. '\u3187': '\u1184',
  14124. '\u3188': '\u1185',
  14125. '\u3189': '\u1188',
  14126. '\u318A': '\u1191',
  14127. '\u318B': '\u1192',
  14128. '\u318C': '\u1194',
  14129. '\u318D': '\u119E',
  14130. '\u318E': '\u11A1',
  14131. '\u3200': '\u0028\u1100\u0029',
  14132. '\u3201': '\u0028\u1102\u0029',
  14133. '\u3202': '\u0028\u1103\u0029',
  14134. '\u3203': '\u0028\u1105\u0029',
  14135. '\u3204': '\u0028\u1106\u0029',
  14136. '\u3205': '\u0028\u1107\u0029',
  14137. '\u3206': '\u0028\u1109\u0029',
  14138. '\u3207': '\u0028\u110B\u0029',
  14139. '\u3208': '\u0028\u110C\u0029',
  14140. '\u3209': '\u0028\u110E\u0029',
  14141. '\u320A': '\u0028\u110F\u0029',
  14142. '\u320B': '\u0028\u1110\u0029',
  14143. '\u320C': '\u0028\u1111\u0029',
  14144. '\u320D': '\u0028\u1112\u0029',
  14145. '\u320E': '\u0028\u1100\u1161\u0029',
  14146. '\u320F': '\u0028\u1102\u1161\u0029',
  14147. '\u3210': '\u0028\u1103\u1161\u0029',
  14148. '\u3211': '\u0028\u1105\u1161\u0029',
  14149. '\u3212': '\u0028\u1106\u1161\u0029',
  14150. '\u3213': '\u0028\u1107\u1161\u0029',
  14151. '\u3214': '\u0028\u1109\u1161\u0029',
  14152. '\u3215': '\u0028\u110B\u1161\u0029',
  14153. '\u3216': '\u0028\u110C\u1161\u0029',
  14154. '\u3217': '\u0028\u110E\u1161\u0029',
  14155. '\u3218': '\u0028\u110F\u1161\u0029',
  14156. '\u3219': '\u0028\u1110\u1161\u0029',
  14157. '\u321A': '\u0028\u1111\u1161\u0029',
  14158. '\u321B': '\u0028\u1112\u1161\u0029',
  14159. '\u321C': '\u0028\u110C\u116E\u0029',
  14160. '\u321D': '\u0028\u110B\u1169\u110C\u1165\u11AB\u0029',
  14161. '\u321E': '\u0028\u110B\u1169\u1112\u116E\u0029',
  14162. '\u3220': '\u0028\u4E00\u0029',
  14163. '\u3221': '\u0028\u4E8C\u0029',
  14164. '\u3222': '\u0028\u4E09\u0029',
  14165. '\u3223': '\u0028\u56DB\u0029',
  14166. '\u3224': '\u0028\u4E94\u0029',
  14167. '\u3225': '\u0028\u516D\u0029',
  14168. '\u3226': '\u0028\u4E03\u0029',
  14169. '\u3227': '\u0028\u516B\u0029',
  14170. '\u3228': '\u0028\u4E5D\u0029',
  14171. '\u3229': '\u0028\u5341\u0029',
  14172. '\u322A': '\u0028\u6708\u0029',
  14173. '\u322B': '\u0028\u706B\u0029',
  14174. '\u322C': '\u0028\u6C34\u0029',
  14175. '\u322D': '\u0028\u6728\u0029',
  14176. '\u322E': '\u0028\u91D1\u0029',
  14177. '\u322F': '\u0028\u571F\u0029',
  14178. '\u3230': '\u0028\u65E5\u0029',
  14179. '\u3231': '\u0028\u682A\u0029',
  14180. '\u3232': '\u0028\u6709\u0029',
  14181. '\u3233': '\u0028\u793E\u0029',
  14182. '\u3234': '\u0028\u540D\u0029',
  14183. '\u3235': '\u0028\u7279\u0029',
  14184. '\u3236': '\u0028\u8CA1\u0029',
  14185. '\u3237': '\u0028\u795D\u0029',
  14186. '\u3238': '\u0028\u52B4\u0029',
  14187. '\u3239': '\u0028\u4EE3\u0029',
  14188. '\u323A': '\u0028\u547C\u0029',
  14189. '\u323B': '\u0028\u5B66\u0029',
  14190. '\u323C': '\u0028\u76E3\u0029',
  14191. '\u323D': '\u0028\u4F01\u0029',
  14192. '\u323E': '\u0028\u8CC7\u0029',
  14193. '\u323F': '\u0028\u5354\u0029',
  14194. '\u3240': '\u0028\u796D\u0029',
  14195. '\u3241': '\u0028\u4F11\u0029',
  14196. '\u3242': '\u0028\u81EA\u0029',
  14197. '\u3243': '\u0028\u81F3\u0029',
  14198. '\u32C0': '\u0031\u6708',
  14199. '\u32C1': '\u0032\u6708',
  14200. '\u32C2': '\u0033\u6708',
  14201. '\u32C3': '\u0034\u6708',
  14202. '\u32C4': '\u0035\u6708',
  14203. '\u32C5': '\u0036\u6708',
  14204. '\u32C6': '\u0037\u6708',
  14205. '\u32C7': '\u0038\u6708',
  14206. '\u32C8': '\u0039\u6708',
  14207. '\u32C9': '\u0031\u0030\u6708',
  14208. '\u32CA': '\u0031\u0031\u6708',
  14209. '\u32CB': '\u0031\u0032\u6708',
  14210. '\u3358': '\u0030\u70B9',
  14211. '\u3359': '\u0031\u70B9',
  14212. '\u335A': '\u0032\u70B9',
  14213. '\u335B': '\u0033\u70B9',
  14214. '\u335C': '\u0034\u70B9',
  14215. '\u335D': '\u0035\u70B9',
  14216. '\u335E': '\u0036\u70B9',
  14217. '\u335F': '\u0037\u70B9',
  14218. '\u3360': '\u0038\u70B9',
  14219. '\u3361': '\u0039\u70B9',
  14220. '\u3362': '\u0031\u0030\u70B9',
  14221. '\u3363': '\u0031\u0031\u70B9',
  14222. '\u3364': '\u0031\u0032\u70B9',
  14223. '\u3365': '\u0031\u0033\u70B9',
  14224. '\u3366': '\u0031\u0034\u70B9',
  14225. '\u3367': '\u0031\u0035\u70B9',
  14226. '\u3368': '\u0031\u0036\u70B9',
  14227. '\u3369': '\u0031\u0037\u70B9',
  14228. '\u336A': '\u0031\u0038\u70B9',
  14229. '\u336B': '\u0031\u0039\u70B9',
  14230. '\u336C': '\u0032\u0030\u70B9',
  14231. '\u336D': '\u0032\u0031\u70B9',
  14232. '\u336E': '\u0032\u0032\u70B9',
  14233. '\u336F': '\u0032\u0033\u70B9',
  14234. '\u3370': '\u0032\u0034\u70B9',
  14235. '\u33E0': '\u0031\u65E5',
  14236. '\u33E1': '\u0032\u65E5',
  14237. '\u33E2': '\u0033\u65E5',
  14238. '\u33E3': '\u0034\u65E5',
  14239. '\u33E4': '\u0035\u65E5',
  14240. '\u33E5': '\u0036\u65E5',
  14241. '\u33E6': '\u0037\u65E5',
  14242. '\u33E7': '\u0038\u65E5',
  14243. '\u33E8': '\u0039\u65E5',
  14244. '\u33E9': '\u0031\u0030\u65E5',
  14245. '\u33EA': '\u0031\u0031\u65E5',
  14246. '\u33EB': '\u0031\u0032\u65E5',
  14247. '\u33EC': '\u0031\u0033\u65E5',
  14248. '\u33ED': '\u0031\u0034\u65E5',
  14249. '\u33EE': '\u0031\u0035\u65E5',
  14250. '\u33EF': '\u0031\u0036\u65E5',
  14251. '\u33F0': '\u0031\u0037\u65E5',
  14252. '\u33F1': '\u0031\u0038\u65E5',
  14253. '\u33F2': '\u0031\u0039\u65E5',
  14254. '\u33F3': '\u0032\u0030\u65E5',
  14255. '\u33F4': '\u0032\u0031\u65E5',
  14256. '\u33F5': '\u0032\u0032\u65E5',
  14257. '\u33F6': '\u0032\u0033\u65E5',
  14258. '\u33F7': '\u0032\u0034\u65E5',
  14259. '\u33F8': '\u0032\u0035\u65E5',
  14260. '\u33F9': '\u0032\u0036\u65E5',
  14261. '\u33FA': '\u0032\u0037\u65E5',
  14262. '\u33FB': '\u0032\u0038\u65E5',
  14263. '\u33FC': '\u0032\u0039\u65E5',
  14264. '\u33FD': '\u0033\u0030\u65E5',
  14265. '\u33FE': '\u0033\u0031\u65E5',
  14266. '\uFB00': '\u0066\u0066',
  14267. '\uFB01': '\u0066\u0069',
  14268. '\uFB02': '\u0066\u006C',
  14269. '\uFB03': '\u0066\u0066\u0069',
  14270. '\uFB04': '\u0066\u0066\u006C',
  14271. '\uFB05': '\u017F\u0074',
  14272. '\uFB06': '\u0073\u0074',
  14273. '\uFB13': '\u0574\u0576',
  14274. '\uFB14': '\u0574\u0565',
  14275. '\uFB15': '\u0574\u056B',
  14276. '\uFB16': '\u057E\u0576',
  14277. '\uFB17': '\u0574\u056D',
  14278. '\uFB4F': '\u05D0\u05DC',
  14279. '\uFB50': '\u0671',
  14280. '\uFB51': '\u0671',
  14281. '\uFB52': '\u067B',
  14282. '\uFB53': '\u067B',
  14283. '\uFB54': '\u067B',
  14284. '\uFB55': '\u067B',
  14285. '\uFB56': '\u067E',
  14286. '\uFB57': '\u067E',
  14287. '\uFB58': '\u067E',
  14288. '\uFB59': '\u067E',
  14289. '\uFB5A': '\u0680',
  14290. '\uFB5B': '\u0680',
  14291. '\uFB5C': '\u0680',
  14292. '\uFB5D': '\u0680',
  14293. '\uFB5E': '\u067A',
  14294. '\uFB5F': '\u067A',
  14295. '\uFB60': '\u067A',
  14296. '\uFB61': '\u067A',
  14297. '\uFB62': '\u067F',
  14298. '\uFB63': '\u067F',
  14299. '\uFB64': '\u067F',
  14300. '\uFB65': '\u067F',
  14301. '\uFB66': '\u0679',
  14302. '\uFB67': '\u0679',
  14303. '\uFB68': '\u0679',
  14304. '\uFB69': '\u0679',
  14305. '\uFB6A': '\u06A4',
  14306. '\uFB6B': '\u06A4',
  14307. '\uFB6C': '\u06A4',
  14308. '\uFB6D': '\u06A4',
  14309. '\uFB6E': '\u06A6',
  14310. '\uFB6F': '\u06A6',
  14311. '\uFB70': '\u06A6',
  14312. '\uFB71': '\u06A6',
  14313. '\uFB72': '\u0684',
  14314. '\uFB73': '\u0684',
  14315. '\uFB74': '\u0684',
  14316. '\uFB75': '\u0684',
  14317. '\uFB76': '\u0683',
  14318. '\uFB77': '\u0683',
  14319. '\uFB78': '\u0683',
  14320. '\uFB79': '\u0683',
  14321. '\uFB7A': '\u0686',
  14322. '\uFB7B': '\u0686',
  14323. '\uFB7C': '\u0686',
  14324. '\uFB7D': '\u0686',
  14325. '\uFB7E': '\u0687',
  14326. '\uFB7F': '\u0687',
  14327. '\uFB80': '\u0687',
  14328. '\uFB81': '\u0687',
  14329. '\uFB82': '\u068D',
  14330. '\uFB83': '\u068D',
  14331. '\uFB84': '\u068C',
  14332. '\uFB85': '\u068C',
  14333. '\uFB86': '\u068E',
  14334. '\uFB87': '\u068E',
  14335. '\uFB88': '\u0688',
  14336. '\uFB89': '\u0688',
  14337. '\uFB8A': '\u0698',
  14338. '\uFB8B': '\u0698',
  14339. '\uFB8C': '\u0691',
  14340. '\uFB8D': '\u0691',
  14341. '\uFB8E': '\u06A9',
  14342. '\uFB8F': '\u06A9',
  14343. '\uFB90': '\u06A9',
  14344. '\uFB91': '\u06A9',
  14345. '\uFB92': '\u06AF',
  14346. '\uFB93': '\u06AF',
  14347. '\uFB94': '\u06AF',
  14348. '\uFB95': '\u06AF',
  14349. '\uFB96': '\u06B3',
  14350. '\uFB97': '\u06B3',
  14351. '\uFB98': '\u06B3',
  14352. '\uFB99': '\u06B3',
  14353. '\uFB9A': '\u06B1',
  14354. '\uFB9B': '\u06B1',
  14355. '\uFB9C': '\u06B1',
  14356. '\uFB9D': '\u06B1',
  14357. '\uFB9E': '\u06BA',
  14358. '\uFB9F': '\u06BA',
  14359. '\uFBA0': '\u06BB',
  14360. '\uFBA1': '\u06BB',
  14361. '\uFBA2': '\u06BB',
  14362. '\uFBA3': '\u06BB',
  14363. '\uFBA4': '\u06C0',
  14364. '\uFBA5': '\u06C0',
  14365. '\uFBA6': '\u06C1',
  14366. '\uFBA7': '\u06C1',
  14367. '\uFBA8': '\u06C1',
  14368. '\uFBA9': '\u06C1',
  14369. '\uFBAA': '\u06BE',
  14370. '\uFBAB': '\u06BE',
  14371. '\uFBAC': '\u06BE',
  14372. '\uFBAD': '\u06BE',
  14373. '\uFBAE': '\u06D2',
  14374. '\uFBAF': '\u06D2',
  14375. '\uFBB0': '\u06D3',
  14376. '\uFBB1': '\u06D3',
  14377. '\uFBD3': '\u06AD',
  14378. '\uFBD4': '\u06AD',
  14379. '\uFBD5': '\u06AD',
  14380. '\uFBD6': '\u06AD',
  14381. '\uFBD7': '\u06C7',
  14382. '\uFBD8': '\u06C7',
  14383. '\uFBD9': '\u06C6',
  14384. '\uFBDA': '\u06C6',
  14385. '\uFBDB': '\u06C8',
  14386. '\uFBDC': '\u06C8',
  14387. '\uFBDD': '\u0677',
  14388. '\uFBDE': '\u06CB',
  14389. '\uFBDF': '\u06CB',
  14390. '\uFBE0': '\u06C5',
  14391. '\uFBE1': '\u06C5',
  14392. '\uFBE2': '\u06C9',
  14393. '\uFBE3': '\u06C9',
  14394. '\uFBE4': '\u06D0',
  14395. '\uFBE5': '\u06D0',
  14396. '\uFBE6': '\u06D0',
  14397. '\uFBE7': '\u06D0',
  14398. '\uFBE8': '\u0649',
  14399. '\uFBE9': '\u0649',
  14400. '\uFBEA': '\u0626\u0627',
  14401. '\uFBEB': '\u0626\u0627',
  14402. '\uFBEC': '\u0626\u06D5',
  14403. '\uFBED': '\u0626\u06D5',
  14404. '\uFBEE': '\u0626\u0648',
  14405. '\uFBEF': '\u0626\u0648',
  14406. '\uFBF0': '\u0626\u06C7',
  14407. '\uFBF1': '\u0626\u06C7',
  14408. '\uFBF2': '\u0626\u06C6',
  14409. '\uFBF3': '\u0626\u06C6',
  14410. '\uFBF4': '\u0626\u06C8',
  14411. '\uFBF5': '\u0626\u06C8',
  14412. '\uFBF6': '\u0626\u06D0',
  14413. '\uFBF7': '\u0626\u06D0',
  14414. '\uFBF8': '\u0626\u06D0',
  14415. '\uFBF9': '\u0626\u0649',
  14416. '\uFBFA': '\u0626\u0649',
  14417. '\uFBFB': '\u0626\u0649',
  14418. '\uFBFC': '\u06CC',
  14419. '\uFBFD': '\u06CC',
  14420. '\uFBFE': '\u06CC',
  14421. '\uFBFF': '\u06CC',
  14422. '\uFC00': '\u0626\u062C',
  14423. '\uFC01': '\u0626\u062D',
  14424. '\uFC02': '\u0626\u0645',
  14425. '\uFC03': '\u0626\u0649',
  14426. '\uFC04': '\u0626\u064A',
  14427. '\uFC05': '\u0628\u062C',
  14428. '\uFC06': '\u0628\u062D',
  14429. '\uFC07': '\u0628\u062E',
  14430. '\uFC08': '\u0628\u0645',
  14431. '\uFC09': '\u0628\u0649',
  14432. '\uFC0A': '\u0628\u064A',
  14433. '\uFC0B': '\u062A\u062C',
  14434. '\uFC0C': '\u062A\u062D',
  14435. '\uFC0D': '\u062A\u062E',
  14436. '\uFC0E': '\u062A\u0645',
  14437. '\uFC0F': '\u062A\u0649',
  14438. '\uFC10': '\u062A\u064A',
  14439. '\uFC11': '\u062B\u062C',
  14440. '\uFC12': '\u062B\u0645',
  14441. '\uFC13': '\u062B\u0649',
  14442. '\uFC14': '\u062B\u064A',
  14443. '\uFC15': '\u062C\u062D',
  14444. '\uFC16': '\u062C\u0645',
  14445. '\uFC17': '\u062D\u062C',
  14446. '\uFC18': '\u062D\u0645',
  14447. '\uFC19': '\u062E\u062C',
  14448. '\uFC1A': '\u062E\u062D',
  14449. '\uFC1B': '\u062E\u0645',
  14450. '\uFC1C': '\u0633\u062C',
  14451. '\uFC1D': '\u0633\u062D',
  14452. '\uFC1E': '\u0633\u062E',
  14453. '\uFC1F': '\u0633\u0645',
  14454. '\uFC20': '\u0635\u062D',
  14455. '\uFC21': '\u0635\u0645',
  14456. '\uFC22': '\u0636\u062C',
  14457. '\uFC23': '\u0636\u062D',
  14458. '\uFC24': '\u0636\u062E',
  14459. '\uFC25': '\u0636\u0645',
  14460. '\uFC26': '\u0637\u062D',
  14461. '\uFC27': '\u0637\u0645',
  14462. '\uFC28': '\u0638\u0645',
  14463. '\uFC29': '\u0639\u062C',
  14464. '\uFC2A': '\u0639\u0645',
  14465. '\uFC2B': '\u063A\u062C',
  14466. '\uFC2C': '\u063A\u0645',
  14467. '\uFC2D': '\u0641\u062C',
  14468. '\uFC2E': '\u0641\u062D',
  14469. '\uFC2F': '\u0641\u062E',
  14470. '\uFC30': '\u0641\u0645',
  14471. '\uFC31': '\u0641\u0649',
  14472. '\uFC32': '\u0641\u064A',
  14473. '\uFC33': '\u0642\u062D',
  14474. '\uFC34': '\u0642\u0645',
  14475. '\uFC35': '\u0642\u0649',
  14476. '\uFC36': '\u0642\u064A',
  14477. '\uFC37': '\u0643\u0627',
  14478. '\uFC38': '\u0643\u062C',
  14479. '\uFC39': '\u0643\u062D',
  14480. '\uFC3A': '\u0643\u062E',
  14481. '\uFC3B': '\u0643\u0644',
  14482. '\uFC3C': '\u0643\u0645',
  14483. '\uFC3D': '\u0643\u0649',
  14484. '\uFC3E': '\u0643\u064A',
  14485. '\uFC3F': '\u0644\u062C',
  14486. '\uFC40': '\u0644\u062D',
  14487. '\uFC41': '\u0644\u062E',
  14488. '\uFC42': '\u0644\u0645',
  14489. '\uFC43': '\u0644\u0649',
  14490. '\uFC44': '\u0644\u064A',
  14491. '\uFC45': '\u0645\u062C',
  14492. '\uFC46': '\u0645\u062D',
  14493. '\uFC47': '\u0645\u062E',
  14494. '\uFC48': '\u0645\u0645',
  14495. '\uFC49': '\u0645\u0649',
  14496. '\uFC4A': '\u0645\u064A',
  14497. '\uFC4B': '\u0646\u062C',
  14498. '\uFC4C': '\u0646\u062D',
  14499. '\uFC4D': '\u0646\u062E',
  14500. '\uFC4E': '\u0646\u0645',
  14501. '\uFC4F': '\u0646\u0649',
  14502. '\uFC50': '\u0646\u064A',
  14503. '\uFC51': '\u0647\u062C',
  14504. '\uFC52': '\u0647\u0645',
  14505. '\uFC53': '\u0647\u0649',
  14506. '\uFC54': '\u0647\u064A',
  14507. '\uFC55': '\u064A\u062C',
  14508. '\uFC56': '\u064A\u062D',
  14509. '\uFC57': '\u064A\u062E',
  14510. '\uFC58': '\u064A\u0645',
  14511. '\uFC59': '\u064A\u0649',
  14512. '\uFC5A': '\u064A\u064A',
  14513. '\uFC5B': '\u0630\u0670',
  14514. '\uFC5C': '\u0631\u0670',
  14515. '\uFC5D': '\u0649\u0670',
  14516. '\uFC5E': '\u0020\u064C\u0651',
  14517. '\uFC5F': '\u0020\u064D\u0651',
  14518. '\uFC60': '\u0020\u064E\u0651',
  14519. '\uFC61': '\u0020\u064F\u0651',
  14520. '\uFC62': '\u0020\u0650\u0651',
  14521. '\uFC63': '\u0020\u0651\u0670',
  14522. '\uFC64': '\u0626\u0631',
  14523. '\uFC65': '\u0626\u0632',
  14524. '\uFC66': '\u0626\u0645',
  14525. '\uFC67': '\u0626\u0646',
  14526. '\uFC68': '\u0626\u0649',
  14527. '\uFC69': '\u0626\u064A',
  14528. '\uFC6A': '\u0628\u0631',
  14529. '\uFC6B': '\u0628\u0632',
  14530. '\uFC6C': '\u0628\u0645',
  14531. '\uFC6D': '\u0628\u0646',
  14532. '\uFC6E': '\u0628\u0649',
  14533. '\uFC6F': '\u0628\u064A',
  14534. '\uFC70': '\u062A\u0631',
  14535. '\uFC71': '\u062A\u0632',
  14536. '\uFC72': '\u062A\u0645',
  14537. '\uFC73': '\u062A\u0646',
  14538. '\uFC74': '\u062A\u0649',
  14539. '\uFC75': '\u062A\u064A',
  14540. '\uFC76': '\u062B\u0631',
  14541. '\uFC77': '\u062B\u0632',
  14542. '\uFC78': '\u062B\u0645',
  14543. '\uFC79': '\u062B\u0646',
  14544. '\uFC7A': '\u062B\u0649',
  14545. '\uFC7B': '\u062B\u064A',
  14546. '\uFC7C': '\u0641\u0649',
  14547. '\uFC7D': '\u0641\u064A',
  14548. '\uFC7E': '\u0642\u0649',
  14549. '\uFC7F': '\u0642\u064A',
  14550. '\uFC80': '\u0643\u0627',
  14551. '\uFC81': '\u0643\u0644',
  14552. '\uFC82': '\u0643\u0645',
  14553. '\uFC83': '\u0643\u0649',
  14554. '\uFC84': '\u0643\u064A',
  14555. '\uFC85': '\u0644\u0645',
  14556. '\uFC86': '\u0644\u0649',
  14557. '\uFC87': '\u0644\u064A',
  14558. '\uFC88': '\u0645\u0627',
  14559. '\uFC89': '\u0645\u0645',
  14560. '\uFC8A': '\u0646\u0631',
  14561. '\uFC8B': '\u0646\u0632',
  14562. '\uFC8C': '\u0646\u0645',
  14563. '\uFC8D': '\u0646\u0646',
  14564. '\uFC8E': '\u0646\u0649',
  14565. '\uFC8F': '\u0646\u064A',
  14566. '\uFC90': '\u0649\u0670',
  14567. '\uFC91': '\u064A\u0631',
  14568. '\uFC92': '\u064A\u0632',
  14569. '\uFC93': '\u064A\u0645',
  14570. '\uFC94': '\u064A\u0646',
  14571. '\uFC95': '\u064A\u0649',
  14572. '\uFC96': '\u064A\u064A',
  14573. '\uFC97': '\u0626\u062C',
  14574. '\uFC98': '\u0626\u062D',
  14575. '\uFC99': '\u0626\u062E',
  14576. '\uFC9A': '\u0626\u0645',
  14577. '\uFC9B': '\u0626\u0647',
  14578. '\uFC9C': '\u0628\u062C',
  14579. '\uFC9D': '\u0628\u062D',
  14580. '\uFC9E': '\u0628\u062E',
  14581. '\uFC9F': '\u0628\u0645',
  14582. '\uFCA0': '\u0628\u0647',
  14583. '\uFCA1': '\u062A\u062C',
  14584. '\uFCA2': '\u062A\u062D',
  14585. '\uFCA3': '\u062A\u062E',
  14586. '\uFCA4': '\u062A\u0645',
  14587. '\uFCA5': '\u062A\u0647',
  14588. '\uFCA6': '\u062B\u0645',
  14589. '\uFCA7': '\u062C\u062D',
  14590. '\uFCA8': '\u062C\u0645',
  14591. '\uFCA9': '\u062D\u062C',
  14592. '\uFCAA': '\u062D\u0645',
  14593. '\uFCAB': '\u062E\u062C',
  14594. '\uFCAC': '\u062E\u0645',
  14595. '\uFCAD': '\u0633\u062C',
  14596. '\uFCAE': '\u0633\u062D',
  14597. '\uFCAF': '\u0633\u062E',
  14598. '\uFCB0': '\u0633\u0645',
  14599. '\uFCB1': '\u0635\u062D',
  14600. '\uFCB2': '\u0635\u062E',
  14601. '\uFCB3': '\u0635\u0645',
  14602. '\uFCB4': '\u0636\u062C',
  14603. '\uFCB5': '\u0636\u062D',
  14604. '\uFCB6': '\u0636\u062E',
  14605. '\uFCB7': '\u0636\u0645',
  14606. '\uFCB8': '\u0637\u062D',
  14607. '\uFCB9': '\u0638\u0645',
  14608. '\uFCBA': '\u0639\u062C',
  14609. '\uFCBB': '\u0639\u0645',
  14610. '\uFCBC': '\u063A\u062C',
  14611. '\uFCBD': '\u063A\u0645',
  14612. '\uFCBE': '\u0641\u062C',
  14613. '\uFCBF': '\u0641\u062D',
  14614. '\uFCC0': '\u0641\u062E',
  14615. '\uFCC1': '\u0641\u0645',
  14616. '\uFCC2': '\u0642\u062D',
  14617. '\uFCC3': '\u0642\u0645',
  14618. '\uFCC4': '\u0643\u062C',
  14619. '\uFCC5': '\u0643\u062D',
  14620. '\uFCC6': '\u0643\u062E',
  14621. '\uFCC7': '\u0643\u0644',
  14622. '\uFCC8': '\u0643\u0645',
  14623. '\uFCC9': '\u0644\u062C',
  14624. '\uFCCA': '\u0644\u062D',
  14625. '\uFCCB': '\u0644\u062E',
  14626. '\uFCCC': '\u0644\u0645',
  14627. '\uFCCD': '\u0644\u0647',
  14628. '\uFCCE': '\u0645\u062C',
  14629. '\uFCCF': '\u0645\u062D',
  14630. '\uFCD0': '\u0645\u062E',
  14631. '\uFCD1': '\u0645\u0645',
  14632. '\uFCD2': '\u0646\u062C',
  14633. '\uFCD3': '\u0646\u062D',
  14634. '\uFCD4': '\u0646\u062E',
  14635. '\uFCD5': '\u0646\u0645',
  14636. '\uFCD6': '\u0646\u0647',
  14637. '\uFCD7': '\u0647\u062C',
  14638. '\uFCD8': '\u0647\u0645',
  14639. '\uFCD9': '\u0647\u0670',
  14640. '\uFCDA': '\u064A\u062C',
  14641. '\uFCDB': '\u064A\u062D',
  14642. '\uFCDC': '\u064A\u062E',
  14643. '\uFCDD': '\u064A\u0645',
  14644. '\uFCDE': '\u064A\u0647',
  14645. '\uFCDF': '\u0626\u0645',
  14646. '\uFCE0': '\u0626\u0647',
  14647. '\uFCE1': '\u0628\u0645',
  14648. '\uFCE2': '\u0628\u0647',
  14649. '\uFCE3': '\u062A\u0645',
  14650. '\uFCE4': '\u062A\u0647',
  14651. '\uFCE5': '\u062B\u0645',
  14652. '\uFCE6': '\u062B\u0647',
  14653. '\uFCE7': '\u0633\u0645',
  14654. '\uFCE8': '\u0633\u0647',
  14655. '\uFCE9': '\u0634\u0645',
  14656. '\uFCEA': '\u0634\u0647',
  14657. '\uFCEB': '\u0643\u0644',
  14658. '\uFCEC': '\u0643\u0645',
  14659. '\uFCED': '\u0644\u0645',
  14660. '\uFCEE': '\u0646\u0645',
  14661. '\uFCEF': '\u0646\u0647',
  14662. '\uFCF0': '\u064A\u0645',
  14663. '\uFCF1': '\u064A\u0647',
  14664. '\uFCF2': '\u0640\u064E\u0651',
  14665. '\uFCF3': '\u0640\u064F\u0651',
  14666. '\uFCF4': '\u0640\u0650\u0651',
  14667. '\uFCF5': '\u0637\u0649',
  14668. '\uFCF6': '\u0637\u064A',
  14669. '\uFCF7': '\u0639\u0649',
  14670. '\uFCF8': '\u0639\u064A',
  14671. '\uFCF9': '\u063A\u0649',
  14672. '\uFCFA': '\u063A\u064A',
  14673. '\uFCFB': '\u0633\u0649',
  14674. '\uFCFC': '\u0633\u064A',
  14675. '\uFCFD': '\u0634\u0649',
  14676. '\uFCFE': '\u0634\u064A',
  14677. '\uFCFF': '\u062D\u0649',
  14678. '\uFD00': '\u062D\u064A',
  14679. '\uFD01': '\u062C\u0649',
  14680. '\uFD02': '\u062C\u064A',
  14681. '\uFD03': '\u062E\u0649',
  14682. '\uFD04': '\u062E\u064A',
  14683. '\uFD05': '\u0635\u0649',
  14684. '\uFD06': '\u0635\u064A',
  14685. '\uFD07': '\u0636\u0649',
  14686. '\uFD08': '\u0636\u064A',
  14687. '\uFD09': '\u0634\u062C',
  14688. '\uFD0A': '\u0634\u062D',
  14689. '\uFD0B': '\u0634\u062E',
  14690. '\uFD0C': '\u0634\u0645',
  14691. '\uFD0D': '\u0634\u0631',
  14692. '\uFD0E': '\u0633\u0631',
  14693. '\uFD0F': '\u0635\u0631',
  14694. '\uFD10': '\u0636\u0631',
  14695. '\uFD11': '\u0637\u0649',
  14696. '\uFD12': '\u0637\u064A',
  14697. '\uFD13': '\u0639\u0649',
  14698. '\uFD14': '\u0639\u064A',
  14699. '\uFD15': '\u063A\u0649',
  14700. '\uFD16': '\u063A\u064A',
  14701. '\uFD17': '\u0633\u0649',
  14702. '\uFD18': '\u0633\u064A',
  14703. '\uFD19': '\u0634\u0649',
  14704. '\uFD1A': '\u0634\u064A',
  14705. '\uFD1B': '\u062D\u0649',
  14706. '\uFD1C': '\u062D\u064A',
  14707. '\uFD1D': '\u062C\u0649',
  14708. '\uFD1E': '\u062C\u064A',
  14709. '\uFD1F': '\u062E\u0649',
  14710. '\uFD20': '\u062E\u064A',
  14711. '\uFD21': '\u0635\u0649',
  14712. '\uFD22': '\u0635\u064A',
  14713. '\uFD23': '\u0636\u0649',
  14714. '\uFD24': '\u0636\u064A',
  14715. '\uFD25': '\u0634\u062C',
  14716. '\uFD26': '\u0634\u062D',
  14717. '\uFD27': '\u0634\u062E',
  14718. '\uFD28': '\u0634\u0645',
  14719. '\uFD29': '\u0634\u0631',
  14720. '\uFD2A': '\u0633\u0631',
  14721. '\uFD2B': '\u0635\u0631',
  14722. '\uFD2C': '\u0636\u0631',
  14723. '\uFD2D': '\u0634\u062C',
  14724. '\uFD2E': '\u0634\u062D',
  14725. '\uFD2F': '\u0634\u062E',
  14726. '\uFD30': '\u0634\u0645',
  14727. '\uFD31': '\u0633\u0647',
  14728. '\uFD32': '\u0634\u0647',
  14729. '\uFD33': '\u0637\u0645',
  14730. '\uFD34': '\u0633\u062C',
  14731. '\uFD35': '\u0633\u062D',
  14732. '\uFD36': '\u0633\u062E',
  14733. '\uFD37': '\u0634\u062C',
  14734. '\uFD38': '\u0634\u062D',
  14735. '\uFD39': '\u0634\u062E',
  14736. '\uFD3A': '\u0637\u0645',
  14737. '\uFD3B': '\u0638\u0645',
  14738. '\uFD3C': '\u0627\u064B',
  14739. '\uFD3D': '\u0627\u064B',
  14740. '\uFD50': '\u062A\u062C\u0645',
  14741. '\uFD51': '\u062A\u062D\u062C',
  14742. '\uFD52': '\u062A\u062D\u062C',
  14743. '\uFD53': '\u062A\u062D\u0645',
  14744. '\uFD54': '\u062A\u062E\u0645',
  14745. '\uFD55': '\u062A\u0645\u062C',
  14746. '\uFD56': '\u062A\u0645\u062D',
  14747. '\uFD57': '\u062A\u0645\u062E',
  14748. '\uFD58': '\u062C\u0645\u062D',
  14749. '\uFD59': '\u062C\u0645\u062D',
  14750. '\uFD5A': '\u062D\u0645\u064A',
  14751. '\uFD5B': '\u062D\u0645\u0649',
  14752. '\uFD5C': '\u0633\u062D\u062C',
  14753. '\uFD5D': '\u0633\u062C\u062D',
  14754. '\uFD5E': '\u0633\u062C\u0649',
  14755. '\uFD5F': '\u0633\u0645\u062D',
  14756. '\uFD60': '\u0633\u0645\u062D',
  14757. '\uFD61': '\u0633\u0645\u062C',
  14758. '\uFD62': '\u0633\u0645\u0645',
  14759. '\uFD63': '\u0633\u0645\u0645',
  14760. '\uFD64': '\u0635\u062D\u062D',
  14761. '\uFD65': '\u0635\u062D\u062D',
  14762. '\uFD66': '\u0635\u0645\u0645',
  14763. '\uFD67': '\u0634\u062D\u0645',
  14764. '\uFD68': '\u0634\u062D\u0645',
  14765. '\uFD69': '\u0634\u062C\u064A',
  14766. '\uFD6A': '\u0634\u0645\u062E',
  14767. '\uFD6B': '\u0634\u0645\u062E',
  14768. '\uFD6C': '\u0634\u0645\u0645',
  14769. '\uFD6D': '\u0634\u0645\u0645',
  14770. '\uFD6E': '\u0636\u062D\u0649',
  14771. '\uFD6F': '\u0636\u062E\u0645',
  14772. '\uFD70': '\u0636\u062E\u0645',
  14773. '\uFD71': '\u0637\u0645\u062D',
  14774. '\uFD72': '\u0637\u0645\u062D',
  14775. '\uFD73': '\u0637\u0645\u0645',
  14776. '\uFD74': '\u0637\u0645\u064A',
  14777. '\uFD75': '\u0639\u062C\u0645',
  14778. '\uFD76': '\u0639\u0645\u0645',
  14779. '\uFD77': '\u0639\u0645\u0645',
  14780. '\uFD78': '\u0639\u0645\u0649',
  14781. '\uFD79': '\u063A\u0645\u0645',
  14782. '\uFD7A': '\u063A\u0645\u064A',
  14783. '\uFD7B': '\u063A\u0645\u0649',
  14784. '\uFD7C': '\u0641\u062E\u0645',
  14785. '\uFD7D': '\u0641\u062E\u0645',
  14786. '\uFD7E': '\u0642\u0645\u062D',
  14787. '\uFD7F': '\u0642\u0645\u0645',
  14788. '\uFD80': '\u0644\u062D\u0645',
  14789. '\uFD81': '\u0644\u062D\u064A',
  14790. '\uFD82': '\u0644\u062D\u0649',
  14791. '\uFD83': '\u0644\u062C\u062C',
  14792. '\uFD84': '\u0644\u062C\u062C',
  14793. '\uFD85': '\u0644\u062E\u0645',
  14794. '\uFD86': '\u0644\u062E\u0645',
  14795. '\uFD87': '\u0644\u0645\u062D',
  14796. '\uFD88': '\u0644\u0645\u062D',
  14797. '\uFD89': '\u0645\u062D\u062C',
  14798. '\uFD8A': '\u0645\u062D\u0645',
  14799. '\uFD8B': '\u0645\u062D\u064A',
  14800. '\uFD8C': '\u0645\u062C\u062D',
  14801. '\uFD8D': '\u0645\u062C\u0645',
  14802. '\uFD8E': '\u0645\u062E\u062C',
  14803. '\uFD8F': '\u0645\u062E\u0645',
  14804. '\uFD92': '\u0645\u062C\u062E',
  14805. '\uFD93': '\u0647\u0645\u062C',
  14806. '\uFD94': '\u0647\u0645\u0645',
  14807. '\uFD95': '\u0646\u062D\u0645',
  14808. '\uFD96': '\u0646\u062D\u0649',
  14809. '\uFD97': '\u0646\u062C\u0645',
  14810. '\uFD98': '\u0646\u062C\u0645',
  14811. '\uFD99': '\u0646\u062C\u0649',
  14812. '\uFD9A': '\u0646\u0645\u064A',
  14813. '\uFD9B': '\u0646\u0645\u0649',
  14814. '\uFD9C': '\u064A\u0645\u0645',
  14815. '\uFD9D': '\u064A\u0645\u0645',
  14816. '\uFD9E': '\u0628\u062E\u064A',
  14817. '\uFD9F': '\u062A\u062C\u064A',
  14818. '\uFDA0': '\u062A\u062C\u0649',
  14819. '\uFDA1': '\u062A\u062E\u064A',
  14820. '\uFDA2': '\u062A\u062E\u0649',
  14821. '\uFDA3': '\u062A\u0645\u064A',
  14822. '\uFDA4': '\u062A\u0645\u0649',
  14823. '\uFDA5': '\u062C\u0645\u064A',
  14824. '\uFDA6': '\u062C\u062D\u0649',
  14825. '\uFDA7': '\u062C\u0645\u0649',
  14826. '\uFDA8': '\u0633\u062E\u0649',
  14827. '\uFDA9': '\u0635\u062D\u064A',
  14828. '\uFDAA': '\u0634\u062D\u064A',
  14829. '\uFDAB': '\u0636\u062D\u064A',
  14830. '\uFDAC': '\u0644\u062C\u064A',
  14831. '\uFDAD': '\u0644\u0645\u064A',
  14832. '\uFDAE': '\u064A\u062D\u064A',
  14833. '\uFDAF': '\u064A\u062C\u064A',
  14834. '\uFDB0': '\u064A\u0645\u064A',
  14835. '\uFDB1': '\u0645\u0645\u064A',
  14836. '\uFDB2': '\u0642\u0645\u064A',
  14837. '\uFDB3': '\u0646\u062D\u064A',
  14838. '\uFDB4': '\u0642\u0645\u062D',
  14839. '\uFDB5': '\u0644\u062D\u0645',
  14840. '\uFDB6': '\u0639\u0645\u064A',
  14841. '\uFDB7': '\u0643\u0645\u064A',
  14842. '\uFDB8': '\u0646\u062C\u062D',
  14843. '\uFDB9': '\u0645\u062E\u064A',
  14844. '\uFDBA': '\u0644\u062C\u0645',
  14845. '\uFDBB': '\u0643\u0645\u0645',
  14846. '\uFDBC': '\u0644\u062C\u0645',
  14847. '\uFDBD': '\u0646\u062C\u062D',
  14848. '\uFDBE': '\u062C\u062D\u064A',
  14849. '\uFDBF': '\u062D\u062C\u064A',
  14850. '\uFDC0': '\u0645\u062C\u064A',
  14851. '\uFDC1': '\u0641\u0645\u064A',
  14852. '\uFDC2': '\u0628\u062D\u064A',
  14853. '\uFDC3': '\u0643\u0645\u0645',
  14854. '\uFDC4': '\u0639\u062C\u0645',
  14855. '\uFDC5': '\u0635\u0645\u0645',
  14856. '\uFDC6': '\u0633\u062E\u064A',
  14857. '\uFDC7': '\u0646\u062C\u064A',
  14858. '\uFE49': '\u203E',
  14859. '\uFE4A': '\u203E',
  14860. '\uFE4B': '\u203E',
  14861. '\uFE4C': '\u203E',
  14862. '\uFE4D': '\u005F',
  14863. '\uFE4E': '\u005F',
  14864. '\uFE4F': '\u005F',
  14865. '\uFE80': '\u0621',
  14866. '\uFE81': '\u0622',
  14867. '\uFE82': '\u0622',
  14868. '\uFE83': '\u0623',
  14869. '\uFE84': '\u0623',
  14870. '\uFE85': '\u0624',
  14871. '\uFE86': '\u0624',
  14872. '\uFE87': '\u0625',
  14873. '\uFE88': '\u0625',
  14874. '\uFE89': '\u0626',
  14875. '\uFE8A': '\u0626',
  14876. '\uFE8B': '\u0626',
  14877. '\uFE8C': '\u0626',
  14878. '\uFE8D': '\u0627',
  14879. '\uFE8E': '\u0627',
  14880. '\uFE8F': '\u0628',
  14881. '\uFE90': '\u0628',
  14882. '\uFE91': '\u0628',
  14883. '\uFE92': '\u0628',
  14884. '\uFE93': '\u0629',
  14885. '\uFE94': '\u0629',
  14886. '\uFE95': '\u062A',
  14887. '\uFE96': '\u062A',
  14888. '\uFE97': '\u062A',
  14889. '\uFE98': '\u062A',
  14890. '\uFE99': '\u062B',
  14891. '\uFE9A': '\u062B',
  14892. '\uFE9B': '\u062B',
  14893. '\uFE9C': '\u062B',
  14894. '\uFE9D': '\u062C',
  14895. '\uFE9E': '\u062C',
  14896. '\uFE9F': '\u062C',
  14897. '\uFEA0': '\u062C',
  14898. '\uFEA1': '\u062D',
  14899. '\uFEA2': '\u062D',
  14900. '\uFEA3': '\u062D',
  14901. '\uFEA4': '\u062D',
  14902. '\uFEA5': '\u062E',
  14903. '\uFEA6': '\u062E',
  14904. '\uFEA7': '\u062E',
  14905. '\uFEA8': '\u062E',
  14906. '\uFEA9': '\u062F',
  14907. '\uFEAA': '\u062F',
  14908. '\uFEAB': '\u0630',
  14909. '\uFEAC': '\u0630',
  14910. '\uFEAD': '\u0631',
  14911. '\uFEAE': '\u0631',
  14912. '\uFEAF': '\u0632',
  14913. '\uFEB0': '\u0632',
  14914. '\uFEB1': '\u0633',
  14915. '\uFEB2': '\u0633',
  14916. '\uFEB3': '\u0633',
  14917. '\uFEB4': '\u0633',
  14918. '\uFEB5': '\u0634',
  14919. '\uFEB6': '\u0634',
  14920. '\uFEB7': '\u0634',
  14921. '\uFEB8': '\u0634',
  14922. '\uFEB9': '\u0635',
  14923. '\uFEBA': '\u0635',
  14924. '\uFEBB': '\u0635',
  14925. '\uFEBC': '\u0635',
  14926. '\uFEBD': '\u0636',
  14927. '\uFEBE': '\u0636',
  14928. '\uFEBF': '\u0636',
  14929. '\uFEC0': '\u0636',
  14930. '\uFEC1': '\u0637',
  14931. '\uFEC2': '\u0637',
  14932. '\uFEC3': '\u0637',
  14933. '\uFEC4': '\u0637',
  14934. '\uFEC5': '\u0638',
  14935. '\uFEC6': '\u0638',
  14936. '\uFEC7': '\u0638',
  14937. '\uFEC8': '\u0638',
  14938. '\uFEC9': '\u0639',
  14939. '\uFECA': '\u0639',
  14940. '\uFECB': '\u0639',
  14941. '\uFECC': '\u0639',
  14942. '\uFECD': '\u063A',
  14943. '\uFECE': '\u063A',
  14944. '\uFECF': '\u063A',
  14945. '\uFED0': '\u063A',
  14946. '\uFED1': '\u0641',
  14947. '\uFED2': '\u0641',
  14948. '\uFED3': '\u0641',
  14949. '\uFED4': '\u0641',
  14950. '\uFED5': '\u0642',
  14951. '\uFED6': '\u0642',
  14952. '\uFED7': '\u0642',
  14953. '\uFED8': '\u0642',
  14954. '\uFED9': '\u0643',
  14955. '\uFEDA': '\u0643',
  14956. '\uFEDB': '\u0643',
  14957. '\uFEDC': '\u0643',
  14958. '\uFEDD': '\u0644',
  14959. '\uFEDE': '\u0644',
  14960. '\uFEDF': '\u0644',
  14961. '\uFEE0': '\u0644',
  14962. '\uFEE1': '\u0645',
  14963. '\uFEE2': '\u0645',
  14964. '\uFEE3': '\u0645',
  14965. '\uFEE4': '\u0645',
  14966. '\uFEE5': '\u0646',
  14967. '\uFEE6': '\u0646',
  14968. '\uFEE7': '\u0646',
  14969. '\uFEE8': '\u0646',
  14970. '\uFEE9': '\u0647',
  14971. '\uFEEA': '\u0647',
  14972. '\uFEEB': '\u0647',
  14973. '\uFEEC': '\u0647',
  14974. '\uFEED': '\u0648',
  14975. '\uFEEE': '\u0648',
  14976. '\uFEEF': '\u0649',
  14977. '\uFEF0': '\u0649',
  14978. '\uFEF1': '\u064A',
  14979. '\uFEF2': '\u064A',
  14980. '\uFEF3': '\u064A',
  14981. '\uFEF4': '\u064A',
  14982. '\uFEF5': '\u0644\u0622',
  14983. '\uFEF6': '\u0644\u0622',
  14984. '\uFEF7': '\u0644\u0623',
  14985. '\uFEF8': '\u0644\u0623',
  14986. '\uFEF9': '\u0644\u0625',
  14987. '\uFEFA': '\u0644\u0625',
  14988. '\uFEFB': '\u0644\u0627',
  14989. '\uFEFC': '\u0644\u0627'
  14990. };
  14991. function reverseIfRtl(chars) {
  14992. var charsLength = chars.length;
  14993. //reverse an arabic ligature
  14994. if (charsLength <= 1 || !isRTLRangeFor(chars.charCodeAt(0))) {
  14995. return chars;
  14996. }
  14997. var s = '';
  14998. for (var ii = charsLength - 1; ii >= 0; ii--) {
  14999. s += chars[ii];
  15000. }
  15001. return s;
  15002. }
  15003. function adjustWidths(properties) {
  15004. if (properties.fontMatrix[0] === FONT_IDENTITY_MATRIX[0]) {
  15005. return;
  15006. }
  15007. // adjusting width to fontMatrix scale
  15008. var scale = 0.001 / properties.fontMatrix[0];
  15009. var glyphsWidths = properties.widths;
  15010. for (var glyph in glyphsWidths) {
  15011. glyphsWidths[glyph] *= scale;
  15012. }
  15013. properties.defaultWidth *= scale;
  15014. }
  15015. function getFontType(type, subtype) {
  15016. switch (type) {
  15017. case 'Type1':
  15018. return subtype === 'Type1C' ? FontType.TYPE1C : FontType.TYPE1;
  15019. case 'CIDFontType0':
  15020. return subtype === 'CIDFontType0C' ? FontType.CIDFONTTYPE0C :
  15021. FontType.CIDFONTTYPE0;
  15022. case 'OpenType':
  15023. return FontType.OPENTYPE;
  15024. case 'TrueType':
  15025. return FontType.TRUETYPE;
  15026. case 'CIDFontType2':
  15027. return FontType.CIDFONTTYPE2;
  15028. case 'MMType1':
  15029. return FontType.MMTYPE1;
  15030. case 'Type0':
  15031. return FontType.TYPE0;
  15032. default:
  15033. return FontType.UNKNOWN;
  15034. }
  15035. }
  15036. var Glyph = (function GlyphClosure() {
  15037. function Glyph(fontChar, unicode, accent, width, vmetric, operatorListId) {
  15038. this.fontChar = fontChar;
  15039. this.unicode = unicode;
  15040. this.accent = accent;
  15041. this.width = width;
  15042. this.vmetric = vmetric;
  15043. this.operatorListId = operatorListId;
  15044. }
  15045. Glyph.prototype.matchesForCache =
  15046. function(fontChar, unicode, accent, width, vmetric, operatorListId) {
  15047. return this.fontChar === fontChar &&
  15048. this.unicode === unicode &&
  15049. this.accent === accent &&
  15050. this.width === width &&
  15051. this.vmetric === vmetric &&
  15052. this.operatorListId === operatorListId;
  15053. };
  15054. return Glyph;
  15055. })();
  15056. var ToUnicodeMap = (function ToUnicodeMapClosure() {
  15057. function ToUnicodeMap(cmap) {
  15058. // The elements of this._map can be integers or strings, depending on how
  15059. // |cmap| was created.
  15060. this._map = cmap;
  15061. }
  15062. ToUnicodeMap.prototype = {
  15063. get length() {
  15064. return this._map.length;
  15065. },
  15066. forEach: function(callback) {
  15067. for (var charCode in this._map) {
  15068. callback(charCode, this._map[charCode].charCodeAt(0));
  15069. }
  15070. },
  15071. has: function(i) {
  15072. return this._map[i] !== undefined;
  15073. },
  15074. get: function(i) {
  15075. return this._map[i];
  15076. },
  15077. charCodeOf: function(v) {
  15078. return this._map.indexOf(v);
  15079. }
  15080. };
  15081. return ToUnicodeMap;
  15082. })();
  15083. var IdentityToUnicodeMap = (function IdentityToUnicodeMapClosure() {
  15084. function IdentityToUnicodeMap(firstChar, lastChar) {
  15085. this.firstChar = firstChar;
  15086. this.lastChar = lastChar;
  15087. }
  15088. IdentityToUnicodeMap.prototype = {
  15089. get length() {
  15090. return (this.lastChar + 1) - this.firstChar;
  15091. },
  15092. forEach: function (callback) {
  15093. for (var i = this.firstChar, ii = this.lastChar; i <= ii; i++) {
  15094. callback(i, i);
  15095. }
  15096. },
  15097. has: function (i) {
  15098. return this.firstChar <= i && i <= this.lastChar;
  15099. },
  15100. get: function (i) {
  15101. if (this.firstChar <= i && i <= this.lastChar) {
  15102. return String.fromCharCode(i);
  15103. }
  15104. return undefined;
  15105. },
  15106. charCodeOf: function (v) {
  15107. error('should not call .charCodeOf');
  15108. }
  15109. };
  15110. return IdentityToUnicodeMap;
  15111. })();
  15112. var OpenTypeFileBuilder = (function OpenTypeFileBuilderClosure() {
  15113. function writeInt16(dest, offset, num) {
  15114. dest[offset] = (num >> 8) & 0xFF;
  15115. dest[offset + 1] = num & 0xFF;
  15116. }
  15117. function writeInt32(dest, offset, num) {
  15118. dest[offset] = (num >> 24) & 0xFF;
  15119. dest[offset + 1] = (num >> 16) & 0xFF;
  15120. dest[offset + 2] = (num >> 8) & 0xFF;
  15121. dest[offset + 3] = num & 0xFF;
  15122. }
  15123. function writeData(dest, offset, data) {
  15124. var i, ii;
  15125. if (data instanceof Uint8Array) {
  15126. dest.set(data, offset);
  15127. } else if (typeof data === 'string') {
  15128. for (i = 0, ii = data.length; i < ii; i++) {
  15129. dest[offset++] = data.charCodeAt(i) & 0xFF;
  15130. }
  15131. } else {
  15132. // treating everything else as array
  15133. for (i = 0, ii = data.length; i < ii; i++) {
  15134. dest[offset++] = data[i] & 0xFF;
  15135. }
  15136. }
  15137. }
  15138. function OpenTypeFileBuilder(sfnt) {
  15139. this.sfnt = sfnt;
  15140. this.tables = Object.create(null);
  15141. }
  15142. OpenTypeFileBuilder.getSearchParams =
  15143. function OpenTypeFileBuilder_getSearchParams(entriesCount, entrySize) {
  15144. var maxPower2 = 1, log2 = 0;
  15145. while ((maxPower2 ^ entriesCount) > maxPower2) {
  15146. maxPower2 <<= 1;
  15147. log2++;
  15148. }
  15149. var searchRange = maxPower2 * entrySize;
  15150. return {
  15151. range: searchRange,
  15152. entry: log2,
  15153. rangeShift: entrySize * entriesCount - searchRange
  15154. };
  15155. };
  15156. var OTF_HEADER_SIZE = 12;
  15157. var OTF_TABLE_ENTRY_SIZE = 16;
  15158. OpenTypeFileBuilder.prototype = {
  15159. toArray: function OpenTypeFileBuilder_toArray() {
  15160. var sfnt = this.sfnt;
  15161. // Tables needs to be written by ascendant alphabetic order
  15162. var tables = this.tables;
  15163. var tablesNames = Object.keys(tables);
  15164. tablesNames.sort();
  15165. var numTables = tablesNames.length;
  15166. var i, j, jj, table, tableName;
  15167. // layout the tables data
  15168. var offset = OTF_HEADER_SIZE + numTables * OTF_TABLE_ENTRY_SIZE;
  15169. var tableOffsets = [offset];
  15170. for (i = 0; i < numTables; i++) {
  15171. table = tables[tablesNames[i]];
  15172. var paddedLength = ((table.length + 3) & ~3) >>> 0;
  15173. offset += paddedLength;
  15174. tableOffsets.push(offset);
  15175. }
  15176. var file = new Uint8Array(offset);
  15177. // write the table data first (mostly for checksum)
  15178. for (i = 0; i < numTables; i++) {
  15179. table = tables[tablesNames[i]];
  15180. writeData(file, tableOffsets[i], table);
  15181. }
  15182. // sfnt version (4 bytes)
  15183. if (sfnt === 'true') {
  15184. // Windows hates the Mac TrueType sfnt version number
  15185. sfnt = string32(0x00010000);
  15186. }
  15187. file[0] = sfnt.charCodeAt(0) & 0xFF;
  15188. file[1] = sfnt.charCodeAt(1) & 0xFF;
  15189. file[2] = sfnt.charCodeAt(2) & 0xFF;
  15190. file[3] = sfnt.charCodeAt(3) & 0xFF;
  15191. // numTables (2 bytes)
  15192. writeInt16(file, 4, numTables);
  15193. var searchParams = OpenTypeFileBuilder.getSearchParams(numTables, 16);
  15194. // searchRange (2 bytes)
  15195. writeInt16(file, 6, searchParams.range);
  15196. // entrySelector (2 bytes)
  15197. writeInt16(file, 8, searchParams.entry);
  15198. // rangeShift (2 bytes)
  15199. writeInt16(file, 10, searchParams.rangeShift);
  15200. offset = OTF_HEADER_SIZE;
  15201. // writing table entries
  15202. for (i = 0; i < numTables; i++) {
  15203. tableName = tablesNames[i];
  15204. file[offset] = tableName.charCodeAt(0) & 0xFF;
  15205. file[offset + 1] = tableName.charCodeAt(1) & 0xFF;
  15206. file[offset + 2] = tableName.charCodeAt(2) & 0xFF;
  15207. file[offset + 3] = tableName.charCodeAt(3) & 0xFF;
  15208. // checksum
  15209. var checksum = 0;
  15210. for (j = tableOffsets[i], jj = tableOffsets[i + 1]; j < jj; j += 4) {
  15211. var quad = (file[j] << 24) + (file[j + 1] << 16) +
  15212. (file[j + 2] << 8) + file[j + 3];
  15213. checksum = (checksum + quad) | 0;
  15214. }
  15215. writeInt32(file, offset + 4, checksum);
  15216. // offset
  15217. writeInt32(file, offset + 8, tableOffsets[i]);
  15218. // length
  15219. writeInt32(file, offset + 12, tables[tableName].length);
  15220. offset += OTF_TABLE_ENTRY_SIZE;
  15221. }
  15222. return file;
  15223. },
  15224. addTable: function OpenTypeFileBuilder_addTable(tag, data) {
  15225. if (tag in this.tables) {
  15226. throw new Error('Table ' + tag + ' already exists');
  15227. }
  15228. this.tables[tag] = data;
  15229. }
  15230. };
  15231. return OpenTypeFileBuilder;
  15232. })();
  15233. /**
  15234. * 'Font' is the class the outside world should use, it encapsulate all the font
  15235. * decoding logics whatever type it is (assuming the font type is supported).
  15236. *
  15237. * For example to read a Type1 font and to attach it to the document:
  15238. * var type1Font = new Font("MyFontName", binaryFile, propertiesObject);
  15239. * type1Font.bind();
  15240. */
  15241. var Font = (function FontClosure() {
  15242. function Font(name, file, properties) {
  15243. var charCode, glyphName, fontChar;
  15244. this.name = name;
  15245. this.loadedName = properties.loadedName;
  15246. this.isType3Font = properties.isType3Font;
  15247. this.sizes = [];
  15248. this.glyphCache = {};
  15249. var names = name.split('+');
  15250. names = names.length > 1 ? names[1] : names[0];
  15251. names = names.split(/[-,_]/g)[0];
  15252. this.isSerifFont = !!(properties.flags & FontFlags.Serif);
  15253. this.isSymbolicFont = !!(properties.flags & FontFlags.Symbolic);
  15254. this.isMonospace = !!(properties.flags & FontFlags.FixedPitch);
  15255. var type = properties.type;
  15256. var subtype = properties.subtype;
  15257. this.type = type;
  15258. this.fallbackName = (this.isMonospace ? 'monospace' :
  15259. (this.isSerifFont ? 'serif' : 'sans-serif'));
  15260. this.differences = properties.differences;
  15261. this.widths = properties.widths;
  15262. this.defaultWidth = properties.defaultWidth;
  15263. this.composite = properties.composite;
  15264. this.wideChars = properties.wideChars;
  15265. this.cMap = properties.cMap;
  15266. this.ascent = properties.ascent / PDF_GLYPH_SPACE_UNITS;
  15267. this.descent = properties.descent / PDF_GLYPH_SPACE_UNITS;
  15268. this.fontMatrix = properties.fontMatrix;
  15269. this.toUnicode = properties.toUnicode = this.buildToUnicode(properties);
  15270. this.toFontChar = [];
  15271. if (properties.type === 'Type3') {
  15272. for (charCode = 0; charCode < 256; charCode++) {
  15273. this.toFontChar[charCode] = (this.differences[charCode] ||
  15274. properties.defaultEncoding[charCode]);
  15275. }
  15276. this.fontType = FontType.TYPE3;
  15277. return;
  15278. }
  15279. this.cidEncoding = properties.cidEncoding;
  15280. this.vertical = properties.vertical;
  15281. if (this.vertical) {
  15282. this.vmetrics = properties.vmetrics;
  15283. this.defaultVMetrics = properties.defaultVMetrics;
  15284. }
  15285. if (!file || file.isEmpty) {
  15286. if (file) {
  15287. // Some bad PDF generators will include empty font files,
  15288. // attempting to recover by assuming that no file exists.
  15289. warn('Font file is empty in "' + name + '" (' + this.loadedName + ')');
  15290. }
  15291. this.missingFile = true;
  15292. // The file data is not specified. Trying to fix the font name
  15293. // to be used with the canvas.font.
  15294. var fontName = name.replace(/[,_]/g, '-');
  15295. var isStandardFont = !!stdFontMap[fontName] ||
  15296. !!(nonStdFontMap[fontName] && stdFontMap[nonStdFontMap[fontName]]);
  15297. fontName = stdFontMap[fontName] || nonStdFontMap[fontName] || fontName;
  15298. this.bold = (fontName.search(/bold/gi) !== -1);
  15299. this.italic = ((fontName.search(/oblique/gi) !== -1) ||
  15300. (fontName.search(/italic/gi) !== -1));
  15301. // Use 'name' instead of 'fontName' here because the original
  15302. // name ArialBlack for example will be replaced by Helvetica.
  15303. this.black = (name.search(/Black/g) !== -1);
  15304. // if at least one width is present, remeasure all chars when exists
  15305. this.remeasure = Object.keys(this.widths).length > 0;
  15306. if (isStandardFont && type === 'CIDFontType2' &&
  15307. properties.cidEncoding.indexOf('Identity-') === 0) {
  15308. // Standard fonts might be embedded as CID font without glyph mapping.
  15309. // Building one based on GlyphMapForStandardFonts.
  15310. var map = [];
  15311. for (var code in GlyphMapForStandardFonts) {
  15312. map[+code] = GlyphMapForStandardFonts[code];
  15313. }
  15314. var isIdentityUnicode = this.toUnicode instanceof IdentityToUnicodeMap;
  15315. if (!isIdentityUnicode) {
  15316. this.toUnicode.forEach(function(charCode, unicodeCharCode) {
  15317. map[+charCode] = unicodeCharCode;
  15318. });
  15319. }
  15320. this.toFontChar = map;
  15321. this.toUnicode = new ToUnicodeMap(map);
  15322. } else if (/Symbol/i.test(fontName)) {
  15323. var symbols = Encodings.SymbolSetEncoding;
  15324. for (charCode in symbols) {
  15325. fontChar = GlyphsUnicode[symbols[charCode]];
  15326. if (!fontChar) {
  15327. continue;
  15328. }
  15329. this.toFontChar[charCode] = fontChar;
  15330. }
  15331. for (charCode in properties.differences) {
  15332. fontChar = GlyphsUnicode[properties.differences[charCode]];
  15333. if (!fontChar) {
  15334. continue;
  15335. }
  15336. this.toFontChar[charCode] = fontChar;
  15337. }
  15338. } else if (/Dingbats/i.test(fontName)) {
  15339. if (/Wingdings/i.test(name)) {
  15340. warn('Wingdings font without embedded font file, ' +
  15341. 'falling back to the ZapfDingbats encoding.');
  15342. }
  15343. var dingbats = Encodings.ZapfDingbatsEncoding;
  15344. for (charCode in dingbats) {
  15345. fontChar = DingbatsGlyphsUnicode[dingbats[charCode]];
  15346. if (!fontChar) {
  15347. continue;
  15348. }
  15349. this.toFontChar[charCode] = fontChar;
  15350. }
  15351. for (charCode in properties.differences) {
  15352. fontChar = DingbatsGlyphsUnicode[properties.differences[charCode]];
  15353. if (!fontChar) {
  15354. continue;
  15355. }
  15356. this.toFontChar[charCode] = fontChar;
  15357. }
  15358. } else if (isStandardFont) {
  15359. this.toFontChar = [];
  15360. for (charCode in properties.defaultEncoding) {
  15361. glyphName = (properties.differences[charCode] ||
  15362. properties.defaultEncoding[charCode]);
  15363. this.toFontChar[charCode] = GlyphsUnicode[glyphName];
  15364. }
  15365. } else {
  15366. var unicodeCharCode, notCidFont = (type.indexOf('CIDFontType') === -1);
  15367. this.toUnicode.forEach(function(charCode, unicodeCharCode) {
  15368. if (notCidFont) {
  15369. glyphName = (properties.differences[charCode] ||
  15370. properties.defaultEncoding[charCode]);
  15371. unicodeCharCode = (GlyphsUnicode[glyphName] || unicodeCharCode);
  15372. }
  15373. this.toFontChar[charCode] = unicodeCharCode;
  15374. }.bind(this));
  15375. }
  15376. this.loadedName = fontName.split('-')[0];
  15377. this.loading = false;
  15378. this.fontType = getFontType(type, subtype);
  15379. return;
  15380. }
  15381. // Some fonts might use wrong font types for Type1C or CIDFontType0C
  15382. if (subtype === 'Type1C' && (type !== 'Type1' && type !== 'MMType1')) {
  15383. // Some TrueType fonts by mistake claim Type1C
  15384. if (isTrueTypeFile(file)) {
  15385. subtype = 'TrueType';
  15386. } else {
  15387. type = 'Type1';
  15388. }
  15389. }
  15390. if (subtype === 'CIDFontType0C' && type !== 'CIDFontType0') {
  15391. type = 'CIDFontType0';
  15392. }
  15393. if (subtype === 'OpenType') {
  15394. type = 'OpenType';
  15395. }
  15396. // Some CIDFontType0C fonts by mistake claim CIDFontType0.
  15397. if (type === 'CIDFontType0') {
  15398. subtype = isType1File(file) ? 'CIDFontType0' : 'CIDFontType0C';
  15399. }
  15400. var data;
  15401. switch (type) {
  15402. case 'MMType1':
  15403. info('MMType1 font (' + name + '), falling back to Type1.');
  15404. /* falls through */
  15405. case 'Type1':
  15406. case 'CIDFontType0':
  15407. this.mimetype = 'font/opentype';
  15408. var cff = (subtype === 'Type1C' || subtype === 'CIDFontType0C') ?
  15409. new CFFFont(file, properties) : new Type1Font(name, file, properties);
  15410. adjustWidths(properties);
  15411. // Wrap the CFF data inside an OTF font file
  15412. data = this.convert(name, cff, properties);
  15413. break;
  15414. case 'OpenType':
  15415. case 'TrueType':
  15416. case 'CIDFontType2':
  15417. this.mimetype = 'font/opentype';
  15418. // Repair the TrueType file. It is can be damaged in the point of
  15419. // view of the sanitizer
  15420. data = this.checkAndRepair(name, file, properties);
  15421. if (this.isOpenType) {
  15422. type = 'OpenType';
  15423. }
  15424. break;
  15425. default:
  15426. error('Font ' + type + ' is not supported');
  15427. break;
  15428. }
  15429. this.data = data;
  15430. this.fontType = getFontType(type, subtype);
  15431. // Transfer some properties again that could change during font conversion
  15432. this.fontMatrix = properties.fontMatrix;
  15433. this.widths = properties.widths;
  15434. this.defaultWidth = properties.defaultWidth;
  15435. this.encoding = properties.baseEncoding;
  15436. this.seacMap = properties.seacMap;
  15437. this.loading = true;
  15438. }
  15439. Font.getFontID = (function () {
  15440. var ID = 1;
  15441. return function Font_getFontID() {
  15442. return String(ID++);
  15443. };
  15444. })();
  15445. function int16(b0, b1) {
  15446. return (b0 << 8) + b1;
  15447. }
  15448. function int32(b0, b1, b2, b3) {
  15449. return (b0 << 24) + (b1 << 16) + (b2 << 8) + b3;
  15450. }
  15451. function string16(value) {
  15452. return String.fromCharCode((value >> 8) & 0xff, value & 0xff);
  15453. }
  15454. function safeString16(value) {
  15455. // clamp value to the 16-bit int range
  15456. value = (value > 0x7FFF ? 0x7FFF : (value < -0x8000 ? -0x8000 : value));
  15457. return String.fromCharCode((value >> 8) & 0xff, value & 0xff);
  15458. }
  15459. function isTrueTypeFile(file) {
  15460. var header = file.peekBytes(4);
  15461. return readUint32(header, 0) === 0x00010000;
  15462. }
  15463. function isType1File(file) {
  15464. var header = file.peekBytes(2);
  15465. // All Type1 font programs must begin with the comment '%!' (0x25 + 0x21).
  15466. if (header[0] === 0x25 && header[1] === 0x21) {
  15467. return true;
  15468. }
  15469. // ... obviously some fonts violate that part of the specification,
  15470. // please refer to the comment in |Type1Font| below.
  15471. if (header[0] === 0x80 && header[1] === 0x01) { // pfb file header.
  15472. return true;
  15473. }
  15474. return false;
  15475. }
  15476. /**
  15477. * Helper function for |adjustMapping|.
  15478. * @return {boolean}
  15479. */
  15480. function isProblematicUnicodeLocation(code) {
  15481. if (code <= 0x1F) { // Control chars
  15482. return true;
  15483. }
  15484. if (code >= 0x80 && code <= 0x9F) { // Control chars
  15485. return true;
  15486. }
  15487. if ((code >= 0x2000 && code <= 0x200F) || // General punctuation chars
  15488. (code >= 0x2028 && code <= 0x202F) ||
  15489. (code >= 0x2060 && code <= 0x206F)) {
  15490. return true;
  15491. }
  15492. if (code >= 0xFFF0 && code <= 0xFFFF) { // Specials Unicode block
  15493. return true;
  15494. }
  15495. switch (code) {
  15496. case 0x7F: // Control char
  15497. case 0xA0: // Non breaking space
  15498. case 0xAD: // Soft hyphen
  15499. case 0x0E33: // Thai character SARA AM
  15500. case 0x2011: // Non breaking hyphen
  15501. case 0x205F: // Medium mathematical space
  15502. case 0x25CC: // Dotted circle (combining mark)
  15503. return true;
  15504. }
  15505. return false;
  15506. }
  15507. /**
  15508. * Rebuilds the char code to glyph ID map by trying to replace the char codes
  15509. * with their unicode value. It also moves char codes that are in known
  15510. * problematic locations.
  15511. * @return {Object} Two properties:
  15512. * 'toFontChar' - maps original char codes(the value that will be read
  15513. * from commands such as show text) to the char codes that will be used in the
  15514. * font that we build
  15515. * 'charCodeToGlyphId' - maps the new font char codes to glyph ids
  15516. */
  15517. function adjustMapping(charCodeToGlyphId, properties) {
  15518. var toUnicode = properties.toUnicode;
  15519. var isSymbolic = !!(properties.flags & FontFlags.Symbolic);
  15520. var isIdentityUnicode =
  15521. properties.toUnicode instanceof IdentityToUnicodeMap;
  15522. var newMap = Object.create(null);
  15523. var toFontChar = [];
  15524. var usedFontCharCodes = [];
  15525. var nextAvailableFontCharCode = PRIVATE_USE_OFFSET_START;
  15526. for (var originalCharCode in charCodeToGlyphId) {
  15527. originalCharCode |= 0;
  15528. var glyphId = charCodeToGlyphId[originalCharCode];
  15529. var fontCharCode = originalCharCode;
  15530. // First try to map the value to a unicode position if a non identity map
  15531. // was created.
  15532. if (!isIdentityUnicode && toUnicode.has(originalCharCode)) {
  15533. var unicode = toUnicode.get(fontCharCode);
  15534. // TODO: Try to map ligatures to the correct spot.
  15535. if (unicode.length === 1) {
  15536. fontCharCode = unicode.charCodeAt(0);
  15537. }
  15538. }
  15539. // Try to move control characters, special characters and already mapped
  15540. // characters to the private use area since they will not be drawn by
  15541. // canvas if left in their current position. Also, move characters if the
  15542. // font was symbolic and there is only an identity unicode map since the
  15543. // characters probably aren't in the correct position (fixes an issue
  15544. // with firefox and thuluthfont).
  15545. if ((usedFontCharCodes[fontCharCode] !== undefined ||
  15546. isProblematicUnicodeLocation(fontCharCode) ||
  15547. (isSymbolic && isIdentityUnicode)) &&
  15548. nextAvailableFontCharCode <= PRIVATE_USE_OFFSET_END) { // Room left.
  15549. // Loop to try and find a free spot in the private use area.
  15550. do {
  15551. fontCharCode = nextAvailableFontCharCode++;
  15552. if (SKIP_PRIVATE_USE_RANGE_F000_TO_F01F && fontCharCode === 0xF000) {
  15553. fontCharCode = 0xF020;
  15554. nextAvailableFontCharCode = fontCharCode + 1;
  15555. }
  15556. } while (usedFontCharCodes[fontCharCode] !== undefined &&
  15557. nextAvailableFontCharCode <= PRIVATE_USE_OFFSET_END);
  15558. }
  15559. newMap[fontCharCode] = glyphId;
  15560. toFontChar[originalCharCode] = fontCharCode;
  15561. usedFontCharCodes[fontCharCode] = true;
  15562. }
  15563. return {
  15564. toFontChar: toFontChar,
  15565. charCodeToGlyphId: newMap,
  15566. nextAvailableFontCharCode: nextAvailableFontCharCode
  15567. };
  15568. }
  15569. function getRanges(glyphs) {
  15570. // Array.sort() sorts by characters, not numerically, so convert to an
  15571. // array of characters.
  15572. var codes = [];
  15573. for (var charCode in glyphs) {
  15574. codes.push({ fontCharCode: charCode | 0, glyphId: glyphs[charCode] });
  15575. }
  15576. codes.sort(function fontGetRangesSort(a, b) {
  15577. return a.fontCharCode - b.fontCharCode;
  15578. });
  15579. // Split the sorted codes into ranges.
  15580. var ranges = [];
  15581. var length = codes.length;
  15582. for (var n = 0; n < length; ) {
  15583. var start = codes[n].fontCharCode;
  15584. var codeIndices = [codes[n].glyphId];
  15585. ++n;
  15586. var end = start;
  15587. while (n < length && end + 1 === codes[n].fontCharCode) {
  15588. codeIndices.push(codes[n].glyphId);
  15589. ++end;
  15590. ++n;
  15591. if (end === 0xFFFF) {
  15592. break;
  15593. }
  15594. }
  15595. ranges.push([start, end, codeIndices]);
  15596. }
  15597. return ranges;
  15598. }
  15599. function createCmapTable(glyphs) {
  15600. var ranges = getRanges(glyphs);
  15601. var numTables = ranges[ranges.length - 1][1] > 0xFFFF ? 2 : 1;
  15602. var cmap = '\x00\x00' + // version
  15603. string16(numTables) + // numTables
  15604. '\x00\x03' + // platformID
  15605. '\x00\x01' + // encodingID
  15606. string32(4 + numTables * 8); // start of the table record
  15607. var i, ii, j, jj;
  15608. for (i = ranges.length - 1; i >= 0; --i) {
  15609. if (ranges[i][0] <= 0xFFFF) { break; }
  15610. }
  15611. var bmpLength = i + 1;
  15612. if (ranges[i][0] < 0xFFFF && ranges[i][1] === 0xFFFF) {
  15613. ranges[i][1] = 0xFFFE;
  15614. }
  15615. var trailingRangesCount = ranges[i][1] < 0xFFFF ? 1 : 0;
  15616. var segCount = bmpLength + trailingRangesCount;
  15617. var searchParams = OpenTypeFileBuilder.getSearchParams(segCount, 2);
  15618. // Fill up the 4 parallel arrays describing the segments.
  15619. var startCount = '';
  15620. var endCount = '';
  15621. var idDeltas = '';
  15622. var idRangeOffsets = '';
  15623. var glyphsIds = '';
  15624. var bias = 0;
  15625. var range, start, end, codes;
  15626. for (i = 0, ii = bmpLength; i < ii; i++) {
  15627. range = ranges[i];
  15628. start = range[0];
  15629. end = range[1];
  15630. startCount += string16(start);
  15631. endCount += string16(end);
  15632. codes = range[2];
  15633. var contiguous = true;
  15634. for (j = 1, jj = codes.length; j < jj; ++j) {
  15635. if (codes[j] !== codes[j - 1] + 1) {
  15636. contiguous = false;
  15637. break;
  15638. }
  15639. }
  15640. if (!contiguous) {
  15641. var offset = (segCount - i) * 2 + bias * 2;
  15642. bias += (end - start + 1);
  15643. idDeltas += string16(0);
  15644. idRangeOffsets += string16(offset);
  15645. for (j = 0, jj = codes.length; j < jj; ++j) {
  15646. glyphsIds += string16(codes[j]);
  15647. }
  15648. } else {
  15649. var startCode = codes[0];
  15650. idDeltas += string16((startCode - start) & 0xFFFF);
  15651. idRangeOffsets += string16(0);
  15652. }
  15653. }
  15654. if (trailingRangesCount > 0) {
  15655. endCount += '\xFF\xFF';
  15656. startCount += '\xFF\xFF';
  15657. idDeltas += '\x00\x01';
  15658. idRangeOffsets += '\x00\x00';
  15659. }
  15660. var format314 = '\x00\x00' + // language
  15661. string16(2 * segCount) +
  15662. string16(searchParams.range) +
  15663. string16(searchParams.entry) +
  15664. string16(searchParams.rangeShift) +
  15665. endCount + '\x00\x00' + startCount +
  15666. idDeltas + idRangeOffsets + glyphsIds;
  15667. var format31012 = '';
  15668. var header31012 = '';
  15669. if (numTables > 1) {
  15670. cmap += '\x00\x03' + // platformID
  15671. '\x00\x0A' + // encodingID
  15672. string32(4 + numTables * 8 +
  15673. 4 + format314.length); // start of the table record
  15674. format31012 = '';
  15675. for (i = 0, ii = ranges.length; i < ii; i++) {
  15676. range = ranges[i];
  15677. start = range[0];
  15678. codes = range[2];
  15679. var code = codes[0];
  15680. for (j = 1, jj = codes.length; j < jj; ++j) {
  15681. if (codes[j] !== codes[j - 1] + 1) {
  15682. end = range[0] + j - 1;
  15683. format31012 += string32(start) + // startCharCode
  15684. string32(end) + // endCharCode
  15685. string32(code); // startGlyphID
  15686. start = end + 1;
  15687. code = codes[j];
  15688. }
  15689. }
  15690. format31012 += string32(start) + // startCharCode
  15691. string32(range[1]) + // endCharCode
  15692. string32(code); // startGlyphID
  15693. }
  15694. header31012 = '\x00\x0C' + // format
  15695. '\x00\x00' + // reserved
  15696. string32(format31012.length + 16) + // length
  15697. '\x00\x00\x00\x00' + // language
  15698. string32(format31012.length / 12); // nGroups
  15699. }
  15700. return cmap + '\x00\x04' + // format
  15701. string16(format314.length + 4) + // length
  15702. format314 + header31012 + format31012;
  15703. }
  15704. function validateOS2Table(os2) {
  15705. var stream = new Stream(os2.data);
  15706. var version = stream.getUint16();
  15707. // TODO verify all OS/2 tables fields, but currently we validate only those
  15708. // that give us issues
  15709. stream.getBytes(60); // skipping type, misc sizes, panose, unicode ranges
  15710. var selection = stream.getUint16();
  15711. if (version < 4 && (selection & 0x0300)) {
  15712. return false;
  15713. }
  15714. var firstChar = stream.getUint16();
  15715. var lastChar = stream.getUint16();
  15716. if (firstChar > lastChar) {
  15717. return false;
  15718. }
  15719. stream.getBytes(6); // skipping sTypoAscender/Descender/LineGap
  15720. var usWinAscent = stream.getUint16();
  15721. if (usWinAscent === 0) { // makes font unreadable by windows
  15722. return false;
  15723. }
  15724. // OS/2 appears to be valid, resetting some fields
  15725. os2.data[8] = os2.data[9] = 0; // IE rejects fonts if fsType != 0
  15726. return true;
  15727. }
  15728. function createOS2Table(properties, charstrings, override) {
  15729. override = override || {
  15730. unitsPerEm: 0,
  15731. yMax: 0,
  15732. yMin: 0,
  15733. ascent: 0,
  15734. descent: 0
  15735. };
  15736. var ulUnicodeRange1 = 0;
  15737. var ulUnicodeRange2 = 0;
  15738. var ulUnicodeRange3 = 0;
  15739. var ulUnicodeRange4 = 0;
  15740. var firstCharIndex = null;
  15741. var lastCharIndex = 0;
  15742. if (charstrings) {
  15743. for (var code in charstrings) {
  15744. code |= 0;
  15745. if (firstCharIndex > code || !firstCharIndex) {
  15746. firstCharIndex = code;
  15747. }
  15748. if (lastCharIndex < code) {
  15749. lastCharIndex = code;
  15750. }
  15751. var position = getUnicodeRangeFor(code);
  15752. if (position < 32) {
  15753. ulUnicodeRange1 |= 1 << position;
  15754. } else if (position < 64) {
  15755. ulUnicodeRange2 |= 1 << position - 32;
  15756. } else if (position < 96) {
  15757. ulUnicodeRange3 |= 1 << position - 64;
  15758. } else if (position < 123) {
  15759. ulUnicodeRange4 |= 1 << position - 96;
  15760. } else {
  15761. error('Unicode ranges Bits > 123 are reserved for internal usage');
  15762. }
  15763. }
  15764. } else {
  15765. // TODO
  15766. firstCharIndex = 0;
  15767. lastCharIndex = 255;
  15768. }
  15769. var bbox = properties.bbox || [0, 0, 0, 0];
  15770. var unitsPerEm = (override.unitsPerEm ||
  15771. 1 / (properties.fontMatrix || FONT_IDENTITY_MATRIX)[0]);
  15772. // if the font units differ to the PDF glyph space units
  15773. // then scale up the values
  15774. var scale = (properties.ascentScaled ? 1.0 :
  15775. unitsPerEm / PDF_GLYPH_SPACE_UNITS);
  15776. var typoAscent = (override.ascent ||
  15777. Math.round(scale * (properties.ascent || bbox[3])));
  15778. var typoDescent = (override.descent ||
  15779. Math.round(scale * (properties.descent || bbox[1])));
  15780. if (typoDescent > 0 && properties.descent > 0 && bbox[1] < 0) {
  15781. typoDescent = -typoDescent; // fixing incorrect descent
  15782. }
  15783. var winAscent = override.yMax || typoAscent;
  15784. var winDescent = -override.yMin || -typoDescent;
  15785. return '\x00\x03' + // version
  15786. '\x02\x24' + // xAvgCharWidth
  15787. '\x01\xF4' + // usWeightClass
  15788. '\x00\x05' + // usWidthClass
  15789. '\x00\x00' + // fstype (0 to let the font loads via font-face on IE)
  15790. '\x02\x8A' + // ySubscriptXSize
  15791. '\x02\xBB' + // ySubscriptYSize
  15792. '\x00\x00' + // ySubscriptXOffset
  15793. '\x00\x8C' + // ySubscriptYOffset
  15794. '\x02\x8A' + // ySuperScriptXSize
  15795. '\x02\xBB' + // ySuperScriptYSize
  15796. '\x00\x00' + // ySuperScriptXOffset
  15797. '\x01\xDF' + // ySuperScriptYOffset
  15798. '\x00\x31' + // yStrikeOutSize
  15799. '\x01\x02' + // yStrikeOutPosition
  15800. '\x00\x00' + // sFamilyClass
  15801. '\x00\x00\x06' +
  15802. String.fromCharCode(properties.fixedPitch ? 0x09 : 0x00) +
  15803. '\x00\x00\x00\x00\x00\x00' + // Panose
  15804. string32(ulUnicodeRange1) + // ulUnicodeRange1 (Bits 0-31)
  15805. string32(ulUnicodeRange2) + // ulUnicodeRange2 (Bits 32-63)
  15806. string32(ulUnicodeRange3) + // ulUnicodeRange3 (Bits 64-95)
  15807. string32(ulUnicodeRange4) + // ulUnicodeRange4 (Bits 96-127)
  15808. '\x2A\x32\x31\x2A' + // achVendID
  15809. string16(properties.italicAngle ? 1 : 0) + // fsSelection
  15810. string16(firstCharIndex ||
  15811. properties.firstChar) + // usFirstCharIndex
  15812. string16(lastCharIndex || properties.lastChar) + // usLastCharIndex
  15813. string16(typoAscent) + // sTypoAscender
  15814. string16(typoDescent) + // sTypoDescender
  15815. '\x00\x64' + // sTypoLineGap (7%-10% of the unitsPerEM value)
  15816. string16(winAscent) + // usWinAscent
  15817. string16(winDescent) + // usWinDescent
  15818. '\x00\x00\x00\x00' + // ulCodePageRange1 (Bits 0-31)
  15819. '\x00\x00\x00\x00' + // ulCodePageRange2 (Bits 32-63)
  15820. string16(properties.xHeight) + // sxHeight
  15821. string16(properties.capHeight) + // sCapHeight
  15822. string16(0) + // usDefaultChar
  15823. string16(firstCharIndex || properties.firstChar) + // usBreakChar
  15824. '\x00\x03'; // usMaxContext
  15825. }
  15826. function createPostTable(properties) {
  15827. var angle = Math.floor(properties.italicAngle * (Math.pow(2, 16)));
  15828. return ('\x00\x03\x00\x00' + // Version number
  15829. string32(angle) + // italicAngle
  15830. '\x00\x00' + // underlinePosition
  15831. '\x00\x00' + // underlineThickness
  15832. string32(properties.fixedPitch) + // isFixedPitch
  15833. '\x00\x00\x00\x00' + // minMemType42
  15834. '\x00\x00\x00\x00' + // maxMemType42
  15835. '\x00\x00\x00\x00' + // minMemType1
  15836. '\x00\x00\x00\x00'); // maxMemType1
  15837. }
  15838. function createNameTable(name, proto) {
  15839. if (!proto) {
  15840. proto = [[], []]; // no strings and unicode strings
  15841. }
  15842. var strings = [
  15843. proto[0][0] || 'Original licence', // 0.Copyright
  15844. proto[0][1] || name, // 1.Font family
  15845. proto[0][2] || 'Unknown', // 2.Font subfamily (font weight)
  15846. proto[0][3] || 'uniqueID', // 3.Unique ID
  15847. proto[0][4] || name, // 4.Full font name
  15848. proto[0][5] || 'Version 0.11', // 5.Version
  15849. proto[0][6] || '', // 6.Postscript name
  15850. proto[0][7] || 'Unknown', // 7.Trademark
  15851. proto[0][8] || 'Unknown', // 8.Manufacturer
  15852. proto[0][9] || 'Unknown' // 9.Designer
  15853. ];
  15854. // Mac want 1-byte per character strings while Windows want
  15855. // 2-bytes per character, so duplicate the names table
  15856. var stringsUnicode = [];
  15857. var i, ii, j, jj, str;
  15858. for (i = 0, ii = strings.length; i < ii; i++) {
  15859. str = proto[1][i] || strings[i];
  15860. var strBufUnicode = [];
  15861. for (j = 0, jj = str.length; j < jj; j++) {
  15862. strBufUnicode.push(string16(str.charCodeAt(j)));
  15863. }
  15864. stringsUnicode.push(strBufUnicode.join(''));
  15865. }
  15866. var names = [strings, stringsUnicode];
  15867. var platforms = ['\x00\x01', '\x00\x03'];
  15868. var encodings = ['\x00\x00', '\x00\x01'];
  15869. var languages = ['\x00\x00', '\x04\x09'];
  15870. var namesRecordCount = strings.length * platforms.length;
  15871. var nameTable =
  15872. '\x00\x00' + // format
  15873. string16(namesRecordCount) + // Number of names Record
  15874. string16(namesRecordCount * 12 + 6); // Storage
  15875. // Build the name records field
  15876. var strOffset = 0;
  15877. for (i = 0, ii = platforms.length; i < ii; i++) {
  15878. var strs = names[i];
  15879. for (j = 0, jj = strs.length; j < jj; j++) {
  15880. str = strs[j];
  15881. var nameRecord =
  15882. platforms[i] + // platform ID
  15883. encodings[i] + // encoding ID
  15884. languages[i] + // language ID
  15885. string16(j) + // name ID
  15886. string16(str.length) +
  15887. string16(strOffset);
  15888. nameTable += nameRecord;
  15889. strOffset += str.length;
  15890. }
  15891. }
  15892. nameTable += strings.join('') + stringsUnicode.join('');
  15893. return nameTable;
  15894. }
  15895. Font.prototype = {
  15896. name: null,
  15897. font: null,
  15898. mimetype: null,
  15899. encoding: null,
  15900. get renderer() {
  15901. var renderer = FontRendererFactory.create(this);
  15902. return shadow(this, 'renderer', renderer);
  15903. },
  15904. exportData: function Font_exportData() {
  15905. var data = {};
  15906. for (var i in this) {
  15907. if (this.hasOwnProperty(i)) {
  15908. data[i] = this[i];
  15909. }
  15910. }
  15911. return data;
  15912. },
  15913. checkAndRepair: function Font_checkAndRepair(name, font, properties) {
  15914. function readTableEntry(file) {
  15915. var tag = bytesToString(file.getBytes(4));
  15916. var checksum = file.getInt32();
  15917. var offset = file.getInt32() >>> 0;
  15918. var length = file.getInt32() >>> 0;
  15919. // Read the table associated data
  15920. var previousPosition = file.pos;
  15921. file.pos = file.start ? file.start : 0;
  15922. file.skip(offset);
  15923. var data = file.getBytes(length);
  15924. file.pos = previousPosition;
  15925. if (tag === 'head') {
  15926. // clearing checksum adjustment
  15927. data[8] = data[9] = data[10] = data[11] = 0;
  15928. data[17] |= 0x20; //Set font optimized for cleartype flag
  15929. }
  15930. return {
  15931. tag: tag,
  15932. checksum: checksum,
  15933. length: length,
  15934. offset: offset,
  15935. data: data
  15936. };
  15937. }
  15938. function readOpenTypeHeader(ttf) {
  15939. return {
  15940. version: bytesToString(ttf.getBytes(4)),
  15941. numTables: ttf.getUint16(),
  15942. searchRange: ttf.getUint16(),
  15943. entrySelector: ttf.getUint16(),
  15944. rangeShift: ttf.getUint16()
  15945. };
  15946. }
  15947. /**
  15948. * Read the appropriate subtable from the cmap according to 9.6.6.4 from
  15949. * PDF spec
  15950. */
  15951. function readCmapTable(cmap, font, isSymbolicFont) {
  15952. var segment;
  15953. var start = (font.start ? font.start : 0) + cmap.offset;
  15954. font.pos = start;
  15955. var version = font.getUint16();
  15956. var numTables = font.getUint16();
  15957. var potentialTable;
  15958. var canBreak = false;
  15959. // There's an order of preference in terms of which cmap subtable to
  15960. // use:
  15961. // - non-symbolic fonts the preference is a 3,1 table then a 1,0 table
  15962. // - symbolic fonts the preference is a 3,0 table then a 1,0 table
  15963. // The following takes advantage of the fact that the tables are sorted
  15964. // to work.
  15965. for (var i = 0; i < numTables; i++) {
  15966. var platformId = font.getUint16();
  15967. var encodingId = font.getUint16();
  15968. var offset = font.getInt32() >>> 0;
  15969. var useTable = false;
  15970. if (platformId === 0 && encodingId === 0) {
  15971. useTable = true;
  15972. // Continue the loop since there still may be a higher priority
  15973. // table.
  15974. } else if (platformId === 1 && encodingId === 0) {
  15975. useTable = true;
  15976. // Continue the loop since there still may be a higher priority
  15977. // table.
  15978. } else if (platformId === 3 && encodingId === 1 &&
  15979. (!isSymbolicFont || !potentialTable)) {
  15980. useTable = true;
  15981. if (!isSymbolicFont) {
  15982. canBreak = true;
  15983. }
  15984. } else if (isSymbolicFont && platformId === 3 && encodingId === 0) {
  15985. useTable = true;
  15986. canBreak = true;
  15987. }
  15988. if (useTable) {
  15989. potentialTable = {
  15990. platformId: platformId,
  15991. encodingId: encodingId,
  15992. offset: offset
  15993. };
  15994. }
  15995. if (canBreak) {
  15996. break;
  15997. }
  15998. }
  15999. if (!potentialTable) {
  16000. warn('Could not find a preferred cmap table.');
  16001. return {
  16002. platformId: -1,
  16003. encodingId: -1,
  16004. mappings: [],
  16005. hasShortCmap: false
  16006. };
  16007. }
  16008. font.pos = start + potentialTable.offset;
  16009. var format = font.getUint16();
  16010. var length = font.getUint16();
  16011. var language = font.getUint16();
  16012. var hasShortCmap = false;
  16013. var mappings = [];
  16014. var j, glyphId;
  16015. // TODO(mack): refactor this cmap subtable reading logic out
  16016. if (format === 0) {
  16017. for (j = 0; j < 256; j++) {
  16018. var index = font.getByte();
  16019. if (!index) {
  16020. continue;
  16021. }
  16022. mappings.push({
  16023. charCode: j,
  16024. glyphId: index
  16025. });
  16026. }
  16027. hasShortCmap = true;
  16028. } else if (format === 4) {
  16029. // re-creating the table in format 4 since the encoding
  16030. // might be changed
  16031. var segCount = (font.getUint16() >> 1);
  16032. font.getBytes(6); // skipping range fields
  16033. var segIndex, segments = [];
  16034. for (segIndex = 0; segIndex < segCount; segIndex++) {
  16035. segments.push({ end: font.getUint16() });
  16036. }
  16037. font.getUint16();
  16038. for (segIndex = 0; segIndex < segCount; segIndex++) {
  16039. segments[segIndex].start = font.getUint16();
  16040. }
  16041. for (segIndex = 0; segIndex < segCount; segIndex++) {
  16042. segments[segIndex].delta = font.getUint16();
  16043. }
  16044. var offsetsCount = 0;
  16045. for (segIndex = 0; segIndex < segCount; segIndex++) {
  16046. segment = segments[segIndex];
  16047. var rangeOffset = font.getUint16();
  16048. if (!rangeOffset) {
  16049. segment.offsetIndex = -1;
  16050. continue;
  16051. }
  16052. var offsetIndex = (rangeOffset >> 1) - (segCount - segIndex);
  16053. segment.offsetIndex = offsetIndex;
  16054. offsetsCount = Math.max(offsetsCount, offsetIndex +
  16055. segment.end - segment.start + 1);
  16056. }
  16057. var offsets = [];
  16058. for (j = 0; j < offsetsCount; j++) {
  16059. offsets.push(font.getUint16());
  16060. }
  16061. for (segIndex = 0; segIndex < segCount; segIndex++) {
  16062. segment = segments[segIndex];
  16063. start = segment.start;
  16064. var end = segment.end;
  16065. var delta = segment.delta;
  16066. offsetIndex = segment.offsetIndex;
  16067. for (j = start; j <= end; j++) {
  16068. if (j === 0xFFFF) {
  16069. continue;
  16070. }
  16071. glyphId = (offsetIndex < 0 ?
  16072. j : offsets[offsetIndex + j - start]);
  16073. glyphId = (glyphId + delta) & 0xFFFF;
  16074. if (glyphId === 0) {
  16075. continue;
  16076. }
  16077. mappings.push({
  16078. charCode: j,
  16079. glyphId: glyphId
  16080. });
  16081. }
  16082. }
  16083. } else if (format === 6) {
  16084. // Format 6 is a 2-bytes dense mapping, which means the font data
  16085. // lives glue together even if they are pretty far in the unicode
  16086. // table. (This looks weird, so I can have missed something), this
  16087. // works on Linux but seems to fails on Mac so let's rewrite the
  16088. // cmap table to a 3-1-4 style
  16089. var firstCode = font.getUint16();
  16090. var entryCount = font.getUint16();
  16091. for (j = 0; j < entryCount; j++) {
  16092. glyphId = font.getUint16();
  16093. var charCode = firstCode + j;
  16094. mappings.push({
  16095. charCode: charCode,
  16096. glyphId: glyphId
  16097. });
  16098. }
  16099. } else {
  16100. error('cmap table has unsupported format: ' + format);
  16101. }
  16102. // removing duplicate entries
  16103. mappings.sort(function (a, b) {
  16104. return a.charCode - b.charCode;
  16105. });
  16106. for (i = 1; i < mappings.length; i++) {
  16107. if (mappings[i - 1].charCode === mappings[i].charCode) {
  16108. mappings.splice(i, 1);
  16109. i--;
  16110. }
  16111. }
  16112. return {
  16113. platformId: potentialTable.platformId,
  16114. encodingId: potentialTable.encodingId,
  16115. mappings: mappings,
  16116. hasShortCmap: hasShortCmap
  16117. };
  16118. }
  16119. function sanitizeMetrics(font, header, metrics, numGlyphs) {
  16120. if (!header) {
  16121. if (metrics) {
  16122. metrics.data = null;
  16123. }
  16124. return;
  16125. }
  16126. font.pos = (font.start ? font.start : 0) + header.offset;
  16127. font.pos += header.length - 2;
  16128. var numOfMetrics = font.getUint16();
  16129. if (numOfMetrics > numGlyphs) {
  16130. info('The numOfMetrics (' + numOfMetrics + ') should not be ' +
  16131. 'greater than the numGlyphs (' + numGlyphs + ')');
  16132. // Reduce numOfMetrics if it is greater than numGlyphs
  16133. numOfMetrics = numGlyphs;
  16134. header.data[34] = (numOfMetrics & 0xff00) >> 8;
  16135. header.data[35] = numOfMetrics & 0x00ff;
  16136. }
  16137. var numOfSidebearings = numGlyphs - numOfMetrics;
  16138. var numMissing = numOfSidebearings -
  16139. ((metrics.length - numOfMetrics * 4) >> 1);
  16140. if (numMissing > 0) {
  16141. // For each missing glyph, we set both the width and lsb to 0 (zero).
  16142. // Since we need to add two properties for each glyph, this explains
  16143. // the use of |numMissing * 2| when initializing the typed array.
  16144. var entries = new Uint8Array(metrics.length + numMissing * 2);
  16145. entries.set(metrics.data);
  16146. metrics.data = entries;
  16147. }
  16148. }
  16149. function sanitizeGlyph(source, sourceStart, sourceEnd, dest, destStart,
  16150. hintsValid) {
  16151. if (sourceEnd - sourceStart <= 12) {
  16152. // glyph with data less than 12 is invalid one
  16153. return 0;
  16154. }
  16155. var glyf = source.subarray(sourceStart, sourceEnd);
  16156. var contoursCount = (glyf[0] << 8) | glyf[1];
  16157. if (contoursCount & 0x8000) {
  16158. // complex glyph, writing as is
  16159. dest.set(glyf, destStart);
  16160. return glyf.length;
  16161. }
  16162. var i, j = 10, flagsCount = 0;
  16163. for (i = 0; i < contoursCount; i++) {
  16164. var endPoint = (glyf[j] << 8) | glyf[j + 1];
  16165. flagsCount = endPoint + 1;
  16166. j += 2;
  16167. }
  16168. // skipping instructions
  16169. var instructionsStart = j;
  16170. var instructionsLength = (glyf[j] << 8) | glyf[j + 1];
  16171. j += 2 + instructionsLength;
  16172. var instructionsEnd = j;
  16173. // validating flags
  16174. var coordinatesLength = 0;
  16175. for (i = 0; i < flagsCount; i++) {
  16176. var flag = glyf[j++];
  16177. if (flag & 0xC0) {
  16178. // reserved flags must be zero, cleaning up
  16179. glyf[j - 1] = flag & 0x3F;
  16180. }
  16181. var xyLength = ((flag & 2) ? 1 : (flag & 16) ? 0 : 2) +
  16182. ((flag & 4) ? 1 : (flag & 32) ? 0 : 2);
  16183. coordinatesLength += xyLength;
  16184. if (flag & 8) {
  16185. var repeat = glyf[j++];
  16186. i += repeat;
  16187. coordinatesLength += repeat * xyLength;
  16188. }
  16189. }
  16190. // glyph without coordinates will be rejected
  16191. if (coordinatesLength === 0) {
  16192. return 0;
  16193. }
  16194. var glyphDataLength = j + coordinatesLength;
  16195. if (glyphDataLength > glyf.length) {
  16196. // not enough data for coordinates
  16197. return 0;
  16198. }
  16199. if (!hintsValid && instructionsLength > 0) {
  16200. dest.set(glyf.subarray(0, instructionsStart), destStart);
  16201. dest.set([0, 0], destStart + instructionsStart);
  16202. dest.set(glyf.subarray(instructionsEnd, glyphDataLength),
  16203. destStart + instructionsStart + 2);
  16204. glyphDataLength -= instructionsLength;
  16205. if (glyf.length - glyphDataLength > 3) {
  16206. glyphDataLength = (glyphDataLength + 3) & ~3;
  16207. }
  16208. return glyphDataLength;
  16209. }
  16210. if (glyf.length - glyphDataLength > 3) {
  16211. // truncating and aligning to 4 bytes the long glyph data
  16212. glyphDataLength = (glyphDataLength + 3) & ~3;
  16213. dest.set(glyf.subarray(0, glyphDataLength), destStart);
  16214. return glyphDataLength;
  16215. }
  16216. // glyph data is fine
  16217. dest.set(glyf, destStart);
  16218. return glyf.length;
  16219. }
  16220. function sanitizeHead(head, numGlyphs, locaLength) {
  16221. var data = head.data;
  16222. // Validate version:
  16223. // Should always be 0x00010000
  16224. var version = int32(data[0], data[1], data[2], data[3]);
  16225. if (version >> 16 !== 1) {
  16226. info('Attempting to fix invalid version in head table: ' + version);
  16227. data[0] = 0;
  16228. data[1] = 1;
  16229. data[2] = 0;
  16230. data[3] = 0;
  16231. }
  16232. var indexToLocFormat = int16(data[50], data[51]);
  16233. if (indexToLocFormat < 0 || indexToLocFormat > 1) {
  16234. info('Attempting to fix invalid indexToLocFormat in head table: ' +
  16235. indexToLocFormat);
  16236. // The value of indexToLocFormat should be 0 if the loca table
  16237. // consists of short offsets, and should be 1 if the loca table
  16238. // consists of long offsets.
  16239. //
  16240. // The number of entries in the loca table should be numGlyphs + 1.
  16241. //
  16242. // Using this information, we can work backwards to deduce if the
  16243. // size of each offset in the loca table, and thus figure out the
  16244. // appropriate value for indexToLocFormat.
  16245. var numGlyphsPlusOne = numGlyphs + 1;
  16246. if (locaLength === numGlyphsPlusOne << 1) {
  16247. // 0x0000 indicates the loca table consists of short offsets
  16248. data[50] = 0;
  16249. data[51] = 0;
  16250. } else if (locaLength === numGlyphsPlusOne << 2) {
  16251. // 0x0001 indicates the loca table consists of long offsets
  16252. data[50] = 0;
  16253. data[51] = 1;
  16254. } else {
  16255. warn('Could not fix indexToLocFormat: ' + indexToLocFormat);
  16256. }
  16257. }
  16258. }
  16259. function sanitizeGlyphLocations(loca, glyf, numGlyphs,
  16260. isGlyphLocationsLong, hintsValid,
  16261. dupFirstEntry) {
  16262. var itemSize, itemDecode, itemEncode;
  16263. if (isGlyphLocationsLong) {
  16264. itemSize = 4;
  16265. itemDecode = function fontItemDecodeLong(data, offset) {
  16266. return (data[offset] << 24) | (data[offset + 1] << 16) |
  16267. (data[offset + 2] << 8) | data[offset + 3];
  16268. };
  16269. itemEncode = function fontItemEncodeLong(data, offset, value) {
  16270. data[offset] = (value >>> 24) & 0xFF;
  16271. data[offset + 1] = (value >> 16) & 0xFF;
  16272. data[offset + 2] = (value >> 8) & 0xFF;
  16273. data[offset + 3] = value & 0xFF;
  16274. };
  16275. } else {
  16276. itemSize = 2;
  16277. itemDecode = function fontItemDecode(data, offset) {
  16278. return (data[offset] << 9) | (data[offset + 1] << 1);
  16279. };
  16280. itemEncode = function fontItemEncode(data, offset, value) {
  16281. data[offset] = (value >> 9) & 0xFF;
  16282. data[offset + 1] = (value >> 1) & 0xFF;
  16283. };
  16284. }
  16285. var locaData = loca.data;
  16286. var locaDataSize = itemSize * (1 + numGlyphs);
  16287. // is loca.data too short or long?
  16288. if (locaData.length !== locaDataSize) {
  16289. locaData = new Uint8Array(locaDataSize);
  16290. locaData.set(loca.data.subarray(0, locaDataSize));
  16291. loca.data = locaData;
  16292. }
  16293. // removing the invalid glyphs
  16294. var oldGlyfData = glyf.data;
  16295. var oldGlyfDataLength = oldGlyfData.length;
  16296. var newGlyfData = new Uint8Array(oldGlyfDataLength);
  16297. var startOffset = itemDecode(locaData, 0);
  16298. var writeOffset = 0;
  16299. var missingGlyphData = {};
  16300. itemEncode(locaData, 0, writeOffset);
  16301. var i, j;
  16302. for (i = 0, j = itemSize; i < numGlyphs; i++, j += itemSize) {
  16303. var endOffset = itemDecode(locaData, j);
  16304. if (endOffset > oldGlyfDataLength &&
  16305. ((oldGlyfDataLength + 3) & ~3) === endOffset) {
  16306. // Aspose breaks fonts by aligning the glyphs to the qword, but not
  16307. // the glyf table size, which makes last glyph out of range.
  16308. endOffset = oldGlyfDataLength;
  16309. }
  16310. if (endOffset > oldGlyfDataLength) {
  16311. // glyph end offset points outside glyf data, rejecting the glyph
  16312. itemEncode(locaData, j, writeOffset);
  16313. startOffset = endOffset;
  16314. continue;
  16315. }
  16316. if (startOffset === endOffset) {
  16317. missingGlyphData[i] = true;
  16318. }
  16319. var newLength = sanitizeGlyph(oldGlyfData, startOffset, endOffset,
  16320. newGlyfData, writeOffset, hintsValid);
  16321. writeOffset += newLength;
  16322. itemEncode(locaData, j, writeOffset);
  16323. startOffset = endOffset;
  16324. }
  16325. if (writeOffset === 0) {
  16326. // glyf table cannot be empty -- redoing the glyf and loca tables
  16327. // to have single glyph with one point
  16328. var simpleGlyph = new Uint8Array(
  16329. [0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 49, 0]);
  16330. for (i = 0, j = itemSize; i < numGlyphs; i++, j += itemSize) {
  16331. itemEncode(locaData, j, simpleGlyph.length);
  16332. }
  16333. glyf.data = simpleGlyph;
  16334. return missingGlyphData;
  16335. }
  16336. if (dupFirstEntry) {
  16337. var firstEntryLength = itemDecode(locaData, itemSize);
  16338. if (newGlyfData.length > firstEntryLength + writeOffset) {
  16339. glyf.data = newGlyfData.subarray(0, firstEntryLength + writeOffset);
  16340. } else {
  16341. glyf.data = new Uint8Array(firstEntryLength + writeOffset);
  16342. glyf.data.set(newGlyfData.subarray(0, writeOffset));
  16343. }
  16344. glyf.data.set(newGlyfData.subarray(0, firstEntryLength), writeOffset);
  16345. itemEncode(loca.data, locaData.length - itemSize,
  16346. writeOffset + firstEntryLength);
  16347. } else {
  16348. glyf.data = newGlyfData.subarray(0, writeOffset);
  16349. }
  16350. return missingGlyphData;
  16351. }
  16352. function readPostScriptTable(post, properties, maxpNumGlyphs) {
  16353. var start = (font.start ? font.start : 0) + post.offset;
  16354. font.pos = start;
  16355. var length = post.length, end = start + length;
  16356. var version = font.getInt32();
  16357. // skip rest to the tables
  16358. font.getBytes(28);
  16359. var glyphNames;
  16360. var valid = true;
  16361. var i;
  16362. switch (version) {
  16363. case 0x00010000:
  16364. glyphNames = MacStandardGlyphOrdering;
  16365. break;
  16366. case 0x00020000:
  16367. var numGlyphs = font.getUint16();
  16368. if (numGlyphs !== maxpNumGlyphs) {
  16369. valid = false;
  16370. break;
  16371. }
  16372. var glyphNameIndexes = [];
  16373. for (i = 0; i < numGlyphs; ++i) {
  16374. var index = font.getUint16();
  16375. if (index >= 32768) {
  16376. valid = false;
  16377. break;
  16378. }
  16379. glyphNameIndexes.push(index);
  16380. }
  16381. if (!valid) {
  16382. break;
  16383. }
  16384. var customNames = [];
  16385. var strBuf = [];
  16386. while (font.pos < end) {
  16387. var stringLength = font.getByte();
  16388. strBuf.length = stringLength;
  16389. for (i = 0; i < stringLength; ++i) {
  16390. strBuf[i] = String.fromCharCode(font.getByte());
  16391. }
  16392. customNames.push(strBuf.join(''));
  16393. }
  16394. glyphNames = [];
  16395. for (i = 0; i < numGlyphs; ++i) {
  16396. var j = glyphNameIndexes[i];
  16397. if (j < 258) {
  16398. glyphNames.push(MacStandardGlyphOrdering[j]);
  16399. continue;
  16400. }
  16401. glyphNames.push(customNames[j - 258]);
  16402. }
  16403. break;
  16404. case 0x00030000:
  16405. break;
  16406. default:
  16407. warn('Unknown/unsupported post table version ' + version);
  16408. valid = false;
  16409. break;
  16410. }
  16411. properties.glyphNames = glyphNames;
  16412. return valid;
  16413. }
  16414. function readNameTable(nameTable) {
  16415. var start = (font.start ? font.start : 0) + nameTable.offset;
  16416. font.pos = start;
  16417. var names = [[], []];
  16418. var length = nameTable.length, end = start + length;
  16419. var format = font.getUint16();
  16420. var FORMAT_0_HEADER_LENGTH = 6;
  16421. if (format !== 0 || length < FORMAT_0_HEADER_LENGTH) {
  16422. // unsupported name table format or table "too" small
  16423. return names;
  16424. }
  16425. var numRecords = font.getUint16();
  16426. var stringsStart = font.getUint16();
  16427. var records = [];
  16428. var NAME_RECORD_LENGTH = 12;
  16429. var i, ii;
  16430. for (i = 0; i < numRecords &&
  16431. font.pos + NAME_RECORD_LENGTH <= end; i++) {
  16432. var r = {
  16433. platform: font.getUint16(),
  16434. encoding: font.getUint16(),
  16435. language: font.getUint16(),
  16436. name: font.getUint16(),
  16437. length: font.getUint16(),
  16438. offset: font.getUint16()
  16439. };
  16440. // using only Macintosh and Windows platform/encoding names
  16441. if ((r.platform === 1 && r.encoding === 0 && r.language === 0) ||
  16442. (r.platform === 3 && r.encoding === 1 && r.language === 0x409)) {
  16443. records.push(r);
  16444. }
  16445. }
  16446. for (i = 0, ii = records.length; i < ii; i++) {
  16447. var record = records[i];
  16448. var pos = start + stringsStart + record.offset;
  16449. if (pos + record.length > end) {
  16450. continue; // outside of name table, ignoring
  16451. }
  16452. font.pos = pos;
  16453. var nameIndex = record.name;
  16454. if (record.encoding) {
  16455. // unicode
  16456. var str = '';
  16457. for (var j = 0, jj = record.length; j < jj; j += 2) {
  16458. str += String.fromCharCode(font.getUint16());
  16459. }
  16460. names[1][nameIndex] = str;
  16461. } else {
  16462. names[0][nameIndex] = bytesToString(font.getBytes(record.length));
  16463. }
  16464. }
  16465. return names;
  16466. }
  16467. var TTOpsStackDeltas = [
  16468. 0, 0, 0, 0, 0, 0, 0, 0, -2, -2, -2, -2, 0, 0, -2, -5,
  16469. -1, -1, -1, -1, -1, -1, -1, -1, 0, 0, -1, 0, -1, -1, -1, -1,
  16470. 1, -1, -999, 0, 1, 0, -1, -2, 0, -1, -2, -1, -1, 0, -1, -1,
  16471. 0, 0, -999, -999, -1, -1, -1, -1, -2, -999, -2, -2, -999, 0, -2, -2,
  16472. 0, 0, -2, 0, -2, 0, 0, 0, -2, -1, -1, 1, 1, 0, 0, -1,
  16473. -1, -1, -1, -1, -1, -1, 0, 0, -1, 0, -1, -1, 0, -999, -1, -1,
  16474. -1, -1, -1, -1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  16475. -2, -999, -999, -999, -999, -999, -1, -1, -2, -2, 0, 0, 0, 0, -1, -1,
  16476. -999, -2, -2, 0, 0, -1, -2, -2, 0, 0, 0, -1, -1, -1, -2];
  16477. // 0xC0-DF == -1 and 0xE0-FF == -2
  16478. function sanitizeTTProgram(table, ttContext) {
  16479. var data = table.data;
  16480. var i = 0, j, n, b, funcId, pc, lastEndf = 0, lastDeff = 0;
  16481. var stack = [];
  16482. var callstack = [];
  16483. var functionsCalled = [];
  16484. var tooComplexToFollowFunctions =
  16485. ttContext.tooComplexToFollowFunctions;
  16486. var inFDEF = false, ifLevel = 0, inELSE = 0;
  16487. for (var ii = data.length; i < ii;) {
  16488. var op = data[i++];
  16489. // The TrueType instruction set docs can be found at
  16490. // https://developer.apple.com/fonts/TTRefMan/RM05/Chap5.html
  16491. if (op === 0x40) { // NPUSHB - pushes n bytes
  16492. n = data[i++];
  16493. if (inFDEF || inELSE) {
  16494. i += n;
  16495. } else {
  16496. for (j = 0; j < n; j++) {
  16497. stack.push(data[i++]);
  16498. }
  16499. }
  16500. } else if (op === 0x41) { // NPUSHW - pushes n words
  16501. n = data[i++];
  16502. if (inFDEF || inELSE) {
  16503. i += n * 2;
  16504. } else {
  16505. for (j = 0; j < n; j++) {
  16506. b = data[i++];
  16507. stack.push((b << 8) | data[i++]);
  16508. }
  16509. }
  16510. } else if ((op & 0xF8) === 0xB0) { // PUSHB - pushes bytes
  16511. n = op - 0xB0 + 1;
  16512. if (inFDEF || inELSE) {
  16513. i += n;
  16514. } else {
  16515. for (j = 0; j < n; j++) {
  16516. stack.push(data[i++]);
  16517. }
  16518. }
  16519. } else if ((op & 0xF8) === 0xB8) { // PUSHW - pushes words
  16520. n = op - 0xB8 + 1;
  16521. if (inFDEF || inELSE) {
  16522. i += n * 2;
  16523. } else {
  16524. for (j = 0; j < n; j++) {
  16525. b = data[i++];
  16526. stack.push((b << 8) | data[i++]);
  16527. }
  16528. }
  16529. } else if (op === 0x2B && !tooComplexToFollowFunctions) { // CALL
  16530. if (!inFDEF && !inELSE) {
  16531. // collecting inforamtion about which functions are used
  16532. funcId = stack[stack.length - 1];
  16533. ttContext.functionsUsed[funcId] = true;
  16534. if (funcId in ttContext.functionsStackDeltas) {
  16535. stack.length += ttContext.functionsStackDeltas[funcId];
  16536. } else if (funcId in ttContext.functionsDefined &&
  16537. functionsCalled.indexOf(funcId) < 0) {
  16538. callstack.push({data: data, i: i, stackTop: stack.length - 1});
  16539. functionsCalled.push(funcId);
  16540. pc = ttContext.functionsDefined[funcId];
  16541. if (!pc) {
  16542. warn('TT: CALL non-existent function');
  16543. ttContext.hintsValid = false;
  16544. return;
  16545. }
  16546. data = pc.data;
  16547. i = pc.i;
  16548. }
  16549. }
  16550. } else if (op === 0x2C && !tooComplexToFollowFunctions) { // FDEF
  16551. if (inFDEF || inELSE) {
  16552. warn('TT: nested FDEFs not allowed');
  16553. tooComplexToFollowFunctions = true;
  16554. }
  16555. inFDEF = true;
  16556. // collecting inforamtion about which functions are defined
  16557. lastDeff = i;
  16558. funcId = stack.pop();
  16559. ttContext.functionsDefined[funcId] = {data: data, i: i};
  16560. } else if (op === 0x2D) { // ENDF - end of function
  16561. if (inFDEF) {
  16562. inFDEF = false;
  16563. lastEndf = i;
  16564. } else {
  16565. pc = callstack.pop();
  16566. if (!pc) {
  16567. warn('TT: ENDF bad stack');
  16568. ttContext.hintsValid = false;
  16569. return;
  16570. }
  16571. funcId = functionsCalled.pop();
  16572. data = pc.data;
  16573. i = pc.i;
  16574. ttContext.functionsStackDeltas[funcId] =
  16575. stack.length - pc.stackTop;
  16576. }
  16577. } else if (op === 0x89) { // IDEF - instruction definition
  16578. if (inFDEF || inELSE) {
  16579. warn('TT: nested IDEFs not allowed');
  16580. tooComplexToFollowFunctions = true;
  16581. }
  16582. inFDEF = true;
  16583. // recording it as a function to track ENDF
  16584. lastDeff = i;
  16585. } else if (op === 0x58) { // IF
  16586. ++ifLevel;
  16587. } else if (op === 0x1B) { // ELSE
  16588. inELSE = ifLevel;
  16589. } else if (op === 0x59) { // EIF
  16590. if (inELSE === ifLevel) {
  16591. inELSE = 0;
  16592. }
  16593. --ifLevel;
  16594. } else if (op === 0x1C) { // JMPR
  16595. if (!inFDEF && !inELSE) {
  16596. var offset = stack[stack.length - 1];
  16597. // only jumping forward to prevent infinite loop
  16598. if (offset > 0) {
  16599. i += offset - 1;
  16600. }
  16601. }
  16602. }
  16603. // Adjusting stack not extactly, but just enough to get function id
  16604. if (!inFDEF && !inELSE) {
  16605. var stackDelta = op <= 0x8E ? TTOpsStackDeltas[op] :
  16606. op >= 0xC0 && op <= 0xDF ? -1 : op >= 0xE0 ? -2 : 0;
  16607. if (op >= 0x71 && op <= 0x75) {
  16608. n = stack.pop();
  16609. if (n === n) {
  16610. stackDelta = -n * 2;
  16611. }
  16612. }
  16613. while (stackDelta < 0 && stack.length > 0) {
  16614. stack.pop();
  16615. stackDelta++;
  16616. }
  16617. while (stackDelta > 0) {
  16618. stack.push(NaN); // pushing any number into stack
  16619. stackDelta--;
  16620. }
  16621. }
  16622. }
  16623. ttContext.tooComplexToFollowFunctions = tooComplexToFollowFunctions;
  16624. var content = [data];
  16625. if (i > data.length) {
  16626. content.push(new Uint8Array(i - data.length));
  16627. }
  16628. if (lastDeff > lastEndf) {
  16629. warn('TT: complementing a missing function tail');
  16630. // new function definition started, but not finished
  16631. // complete function by [CLEAR, ENDF]
  16632. content.push(new Uint8Array([0x22, 0x2D]));
  16633. }
  16634. foldTTTable(table, content);
  16635. }
  16636. function checkInvalidFunctions(ttContext, maxFunctionDefs) {
  16637. if (ttContext.tooComplexToFollowFunctions) {
  16638. return;
  16639. }
  16640. if (ttContext.functionsDefined.length > maxFunctionDefs) {
  16641. warn('TT: more functions defined than expected');
  16642. ttContext.hintsValid = false;
  16643. return;
  16644. }
  16645. for (var j = 0, jj = ttContext.functionsUsed.length; j < jj; j++) {
  16646. if (j > maxFunctionDefs) {
  16647. warn('TT: invalid function id: ' + j);
  16648. ttContext.hintsValid = false;
  16649. return;
  16650. }
  16651. if (ttContext.functionsUsed[j] && !ttContext.functionsDefined[j]) {
  16652. warn('TT: undefined function: ' + j);
  16653. ttContext.hintsValid = false;
  16654. return;
  16655. }
  16656. }
  16657. }
  16658. function foldTTTable(table, content) {
  16659. if (content.length > 1) {
  16660. // concatenating the content items
  16661. var newLength = 0;
  16662. var j, jj;
  16663. for (j = 0, jj = content.length; j < jj; j++) {
  16664. newLength += content[j].length;
  16665. }
  16666. newLength = (newLength + 3) & ~3;
  16667. var result = new Uint8Array(newLength);
  16668. var pos = 0;
  16669. for (j = 0, jj = content.length; j < jj; j++) {
  16670. result.set(content[j], pos);
  16671. pos += content[j].length;
  16672. }
  16673. table.data = result;
  16674. table.length = newLength;
  16675. }
  16676. }
  16677. function sanitizeTTPrograms(fpgm, prep, cvt) {
  16678. var ttContext = {
  16679. functionsDefined: [],
  16680. functionsUsed: [],
  16681. functionsStackDeltas: [],
  16682. tooComplexToFollowFunctions: false,
  16683. hintsValid: true
  16684. };
  16685. if (fpgm) {
  16686. sanitizeTTProgram(fpgm, ttContext);
  16687. }
  16688. if (prep) {
  16689. sanitizeTTProgram(prep, ttContext);
  16690. }
  16691. if (fpgm) {
  16692. checkInvalidFunctions(ttContext, maxFunctionDefs);
  16693. }
  16694. if (cvt && (cvt.length & 1)) {
  16695. var cvtData = new Uint8Array(cvt.length + 1);
  16696. cvtData.set(cvt.data);
  16697. cvt.data = cvtData;
  16698. }
  16699. return ttContext.hintsValid;
  16700. }
  16701. // The following steps modify the original font data, making copy
  16702. font = new Stream(new Uint8Array(font.getBytes()));
  16703. var VALID_TABLES = ['OS/2', 'cmap', 'head', 'hhea', 'hmtx', 'maxp',
  16704. 'name', 'post', 'loca', 'glyf', 'fpgm', 'prep', 'cvt ', 'CFF '];
  16705. var header = readOpenTypeHeader(font);
  16706. var numTables = header.numTables;
  16707. var cff, cffFile;
  16708. var tables = { 'OS/2': null, cmap: null, head: null, hhea: null,
  16709. hmtx: null, maxp: null, name: null, post: null };
  16710. var table;
  16711. for (var i = 0; i < numTables; i++) {
  16712. table = readTableEntry(font);
  16713. if (VALID_TABLES.indexOf(table.tag) < 0) {
  16714. continue; // skipping table if it's not a required or optional table
  16715. }
  16716. if (table.length === 0) {
  16717. continue; // skipping empty tables
  16718. }
  16719. tables[table.tag] = table;
  16720. }
  16721. var isTrueType = !tables['CFF '];
  16722. if (!isTrueType) {
  16723. // OpenType font
  16724. if (header.version === 'OTTO' ||
  16725. !tables.head || !tables.hhea || !tables.maxp || !tables.post) {
  16726. // no major tables: throwing everything at CFFFont
  16727. cffFile = new Stream(tables['CFF '].data);
  16728. cff = new CFFFont(cffFile, properties);
  16729. return this.convert(name, cff, properties);
  16730. }
  16731. delete tables.glyf;
  16732. delete tables.loca;
  16733. delete tables.fpgm;
  16734. delete tables.prep;
  16735. delete tables['cvt '];
  16736. this.isOpenType = true;
  16737. } else {
  16738. if (!tables.glyf || !tables.loca) {
  16739. error('Required "glyf" or "loca" tables are not found');
  16740. }
  16741. this.isOpenType = false;
  16742. }
  16743. if (!tables.maxp) {
  16744. error('Required "maxp" table is not found');
  16745. }
  16746. font.pos = (font.start || 0) + tables.maxp.offset;
  16747. var version = font.getInt32();
  16748. var numGlyphs = font.getUint16();
  16749. var maxFunctionDefs = 0;
  16750. if (version >= 0x00010000 && tables.maxp.length >= 22) {
  16751. // maxZones can be invalid
  16752. font.pos += 8;
  16753. var maxZones = font.getUint16();
  16754. if (maxZones > 2) { // reset to 2 if font has invalid maxZones
  16755. tables.maxp.data[14] = 0;
  16756. tables.maxp.data[15] = 2;
  16757. }
  16758. font.pos += 4;
  16759. maxFunctionDefs = font.getUint16();
  16760. }
  16761. var dupFirstEntry = false;
  16762. if (properties.type === 'CIDFontType2' && properties.toUnicode &&
  16763. properties.toUnicode.get(0) > '\u0000') {
  16764. // oracle's defect (see 3427), duplicating first entry
  16765. dupFirstEntry = true;
  16766. numGlyphs++;
  16767. tables.maxp.data[4] = numGlyphs >> 8;
  16768. tables.maxp.data[5] = numGlyphs & 255;
  16769. }
  16770. var hintsValid = sanitizeTTPrograms(tables.fpgm, tables.prep,
  16771. tables['cvt '], maxFunctionDefs);
  16772. if (!hintsValid) {
  16773. delete tables.fpgm;
  16774. delete tables.prep;
  16775. delete tables['cvt '];
  16776. }
  16777. // Ensure the hmtx table contains the advance width and
  16778. // sidebearings information for numGlyphs in the maxp table
  16779. sanitizeMetrics(font, tables.hhea, tables.hmtx, numGlyphs);
  16780. if (!tables.head) {
  16781. error('Required "head" table is not found');
  16782. }
  16783. sanitizeHead(tables.head, numGlyphs, isTrueType ? tables.loca.length : 0);
  16784. var missingGlyphs = {};
  16785. if (isTrueType) {
  16786. var isGlyphLocationsLong = int16(tables.head.data[50],
  16787. tables.head.data[51]);
  16788. missingGlyphs = sanitizeGlyphLocations(tables.loca, tables.glyf,
  16789. numGlyphs, isGlyphLocationsLong,
  16790. hintsValid, dupFirstEntry);
  16791. }
  16792. if (!tables.hhea) {
  16793. error('Required "hhea" table is not found');
  16794. }
  16795. // Sanitizer reduces the glyph advanceWidth to the maxAdvanceWidth
  16796. // Sometimes it's 0. That needs to be fixed
  16797. if (tables.hhea.data[10] === 0 && tables.hhea.data[11] === 0) {
  16798. tables.hhea.data[10] = 0xFF;
  16799. tables.hhea.data[11] = 0xFF;
  16800. }
  16801. // The 'post' table has glyphs names.
  16802. if (tables.post) {
  16803. var valid = readPostScriptTable(tables.post, properties, numGlyphs);
  16804. if (!valid) {
  16805. tables.post = null;
  16806. }
  16807. }
  16808. var charCodeToGlyphId = [], charCode, toUnicode = properties.toUnicode;
  16809. function hasGlyph(glyphId, charCode) {
  16810. if (!missingGlyphs[glyphId]) {
  16811. return true;
  16812. }
  16813. if (charCode >= 0 && toUnicode.has(charCode)) {
  16814. return true;
  16815. }
  16816. return false;
  16817. }
  16818. if (properties.type === 'CIDFontType2') {
  16819. var cidToGidMap = properties.cidToGidMap || [];
  16820. var isCidToGidMapEmpty = cidToGidMap.length === 0;
  16821. properties.cMap.forEach(function(charCode, cid) {
  16822. assert(cid <= 0xffff, 'Max size of CID is 65,535');
  16823. var glyphId = -1;
  16824. if (isCidToGidMapEmpty) {
  16825. glyphId = charCode;
  16826. } else if (cidToGidMap[cid] !== undefined) {
  16827. glyphId = cidToGidMap[cid];
  16828. }
  16829. if (glyphId >= 0 && glyphId < numGlyphs &&
  16830. hasGlyph(glyphId, charCode)) {
  16831. charCodeToGlyphId[charCode] = glyphId;
  16832. }
  16833. });
  16834. if (dupFirstEntry) {
  16835. charCodeToGlyphId[0] = numGlyphs - 1;
  16836. }
  16837. } else {
  16838. // Most of the following logic in this code branch is based on the
  16839. // 9.6.6.4 of the PDF spec.
  16840. var cmapTable = readCmapTable(tables.cmap, font, this.isSymbolicFont);
  16841. var cmapPlatformId = cmapTable.platformId;
  16842. var cmapEncodingId = cmapTable.encodingId;
  16843. var cmapMappings = cmapTable.mappings;
  16844. var cmapMappingsLength = cmapMappings.length;
  16845. var hasEncoding = properties.differences.length ||
  16846. !!properties.baseEncodingName;
  16847. // The spec seems to imply that if the font is symbolic the encoding
  16848. // should be ignored, this doesn't appear to work for 'preistabelle.pdf'
  16849. // where the the font is symbolic and it has an encoding.
  16850. if (hasEncoding &&
  16851. (cmapPlatformId === 3 && cmapEncodingId === 1 ||
  16852. cmapPlatformId === 1 && cmapEncodingId === 0) ||
  16853. (cmapPlatformId === -1 && cmapEncodingId === -1 && // Temporary hack
  16854. !!Encodings[properties.baseEncodingName])) { // Temporary hack
  16855. // When no preferred cmap table was found and |baseEncodingName| is
  16856. // one of the predefined encodings, we seem to obtain a better
  16857. // |charCodeToGlyphId| map from the code below (fixes bug 1057544).
  16858. // TODO: Note that this is a hack which should be removed as soon as
  16859. // we have proper support for more exotic cmap tables.
  16860. var baseEncoding = [];
  16861. if (properties.baseEncodingName === 'MacRomanEncoding' ||
  16862. properties.baseEncodingName === 'WinAnsiEncoding') {
  16863. baseEncoding = Encodings[properties.baseEncodingName];
  16864. }
  16865. for (charCode = 0; charCode < 256; charCode++) {
  16866. var glyphName;
  16867. if (this.differences && charCode in this.differences) {
  16868. glyphName = this.differences[charCode];
  16869. } else if (charCode in baseEncoding &&
  16870. baseEncoding[charCode] !== '') {
  16871. glyphName = baseEncoding[charCode];
  16872. } else {
  16873. glyphName = Encodings.StandardEncoding[charCode];
  16874. }
  16875. if (!glyphName) {
  16876. continue;
  16877. }
  16878. var unicodeOrCharCode;
  16879. if (cmapPlatformId === 3 && cmapEncodingId === 1) {
  16880. unicodeOrCharCode = GlyphsUnicode[glyphName];
  16881. } else if (cmapPlatformId === 1 && cmapEncodingId === 0) {
  16882. // TODO: the encoding needs to be updated with mac os table.
  16883. unicodeOrCharCode = Encodings.MacRomanEncoding.indexOf(glyphName);
  16884. }
  16885. var found = false;
  16886. for (i = 0; i < cmapMappingsLength; ++i) {
  16887. if (cmapMappings[i].charCode === unicodeOrCharCode &&
  16888. hasGlyph(cmapMappings[i].glyphId, unicodeOrCharCode)) {
  16889. charCodeToGlyphId[charCode] = cmapMappings[i].glyphId;
  16890. found = true;
  16891. break;
  16892. }
  16893. }
  16894. if (!found && properties.glyphNames) {
  16895. // Try to map using the post table. There are currently no known
  16896. // pdfs that this fixes.
  16897. var glyphId = properties.glyphNames.indexOf(glyphName);
  16898. if (glyphId > 0 && hasGlyph(glyphId, -1)) {
  16899. charCodeToGlyphId[charCode] = glyphId;
  16900. }
  16901. }
  16902. }
  16903. } else if (cmapPlatformId === 0 && cmapEncodingId === 0) {
  16904. // Default Unicode semantics, use the charcodes as is.
  16905. for (i = 0; i < cmapMappingsLength; ++i) {
  16906. charCodeToGlyphId[cmapMappings[i].charCode] =
  16907. cmapMappings[i].glyphId;
  16908. }
  16909. } else {
  16910. // For (3, 0) cmap tables:
  16911. // The charcode key being stored in charCodeToGlyphId is the lower
  16912. // byte of the two-byte charcodes of the cmap table since according to
  16913. // the spec: 'each byte from the string shall be prepended with the
  16914. // high byte of the range [of charcodes in the cmap table], to form
  16915. // a two-byte character, which shall be used to select the
  16916. // associated glyph description from the subtable'.
  16917. //
  16918. // For (1, 0) cmap tables:
  16919. // 'single bytes from the string shall be used to look up the
  16920. // associated glyph descriptions from the subtable'. This means
  16921. // charcodes in the cmap will be single bytes, so no-op since
  16922. // glyph.charCode & 0xFF === glyph.charCode
  16923. for (i = 0; i < cmapMappingsLength; ++i) {
  16924. charCode = cmapMappings[i].charCode & 0xFF;
  16925. charCodeToGlyphId[charCode] = cmapMappings[i].glyphId;
  16926. }
  16927. }
  16928. }
  16929. if (charCodeToGlyphId.length === 0) {
  16930. // defines at least one glyph
  16931. charCodeToGlyphId[0] = 0;
  16932. }
  16933. // Converting glyphs and ids into font's cmap table
  16934. var newMapping = adjustMapping(charCodeToGlyphId, properties);
  16935. this.toFontChar = newMapping.toFontChar;
  16936. tables.cmap = {
  16937. tag: 'cmap',
  16938. data: createCmapTable(newMapping.charCodeToGlyphId)
  16939. };
  16940. if (!tables['OS/2'] || !validateOS2Table(tables['OS/2'])) {
  16941. // extract some more font properties from the OpenType head and
  16942. // hhea tables; yMin and descent value are always negative
  16943. var override = {
  16944. unitsPerEm: int16(tables.head.data[18], tables.head.data[19]),
  16945. yMax: int16(tables.head.data[42], tables.head.data[43]),
  16946. yMin: int16(tables.head.data[38], tables.head.data[39]) - 0x10000,
  16947. ascent: int16(tables.hhea.data[4], tables.hhea.data[5]),
  16948. descent: int16(tables.hhea.data[6], tables.hhea.data[7]) - 0x10000
  16949. };
  16950. tables['OS/2'] = {
  16951. tag: 'OS/2',
  16952. data: createOS2Table(properties, newMapping.charCodeToGlyphId,
  16953. override)
  16954. };
  16955. }
  16956. // Rewrite the 'post' table if needed
  16957. if (!tables.post) {
  16958. tables.post = {
  16959. tag: 'post',
  16960. data: createPostTable(properties)
  16961. };
  16962. }
  16963. if (!isTrueType) {
  16964. try {
  16965. // Trying to repair CFF file
  16966. cffFile = new Stream(tables['CFF '].data);
  16967. var parser = new CFFParser(cffFile, properties);
  16968. cff = parser.parse();
  16969. var compiler = new CFFCompiler(cff);
  16970. tables['CFF '].data = compiler.compile();
  16971. } catch (e) {
  16972. warn('Failed to compile font ' + properties.loadedName);
  16973. }
  16974. }
  16975. // Re-creating 'name' table
  16976. if (!tables.name) {
  16977. tables.name = {
  16978. tag: 'name',
  16979. data: createNameTable(this.name)
  16980. };
  16981. } else {
  16982. // ... using existing 'name' table as prototype
  16983. var namePrototype = readNameTable(tables.name);
  16984. tables.name.data = createNameTable(name, namePrototype);
  16985. }
  16986. var builder = new OpenTypeFileBuilder(header.version);
  16987. for (var tableTag in tables) {
  16988. builder.addTable(tableTag, tables[tableTag].data);
  16989. }
  16990. return builder.toArray();
  16991. },
  16992. convert: function Font_convert(fontName, font, properties) {
  16993. // TODO: Check the charstring widths to determine this.
  16994. properties.fixedPitch = false;
  16995. var mapping = font.getGlyphMapping(properties);
  16996. var newMapping = adjustMapping(mapping, properties);
  16997. this.toFontChar = newMapping.toFontChar;
  16998. var numGlyphs = font.numGlyphs;
  16999. function getCharCodes(charCodeToGlyphId, glyphId) {
  17000. var charCodes = null;
  17001. for (var charCode in charCodeToGlyphId) {
  17002. if (glyphId === charCodeToGlyphId[charCode]) {
  17003. if (!charCodes) {
  17004. charCodes = [];
  17005. }
  17006. charCodes.push(charCode | 0);
  17007. }
  17008. }
  17009. return charCodes;
  17010. }
  17011. function createCharCode(charCodeToGlyphId, glyphId) {
  17012. for (var charCode in charCodeToGlyphId) {
  17013. if (glyphId === charCodeToGlyphId[charCode]) {
  17014. return charCode | 0;
  17015. }
  17016. }
  17017. newMapping.charCodeToGlyphId[newMapping.nextAvailableFontCharCode] =
  17018. glyphId;
  17019. return newMapping.nextAvailableFontCharCode++;
  17020. }
  17021. var seacs = font.seacs;
  17022. if (SEAC_ANALYSIS_ENABLED && seacs && seacs.length) {
  17023. var matrix = properties.fontMatrix || FONT_IDENTITY_MATRIX;
  17024. var charset = font.getCharset();
  17025. var seacMap = Object.create(null);
  17026. for (var glyphId in seacs) {
  17027. glyphId |= 0;
  17028. var seac = seacs[glyphId];
  17029. var baseGlyphName = Encodings.StandardEncoding[seac[2]];
  17030. var accentGlyphName = Encodings.StandardEncoding[seac[3]];
  17031. var baseGlyphId = charset.indexOf(baseGlyphName);
  17032. var accentGlyphId = charset.indexOf(accentGlyphName);
  17033. if (baseGlyphId < 0 || accentGlyphId < 0) {
  17034. continue;
  17035. }
  17036. var accentOffset = {
  17037. x: seac[0] * matrix[0] + seac[1] * matrix[2] + matrix[4],
  17038. y: seac[0] * matrix[1] + seac[1] * matrix[3] + matrix[5]
  17039. };
  17040. var charCodes = getCharCodes(mapping, glyphId);
  17041. if (!charCodes) {
  17042. // There's no point in mapping it if the char code was never mapped
  17043. // to begin with.
  17044. continue;
  17045. }
  17046. for (var i = 0, ii = charCodes.length; i < ii; i++) {
  17047. var charCode = charCodes[i];
  17048. // Find a fontCharCode that maps to the base and accent glyphs.
  17049. // If one doesn't exists, create it.
  17050. var charCodeToGlyphId = newMapping.charCodeToGlyphId;
  17051. var baseFontCharCode = createCharCode(charCodeToGlyphId,
  17052. baseGlyphId);
  17053. var accentFontCharCode = createCharCode(charCodeToGlyphId,
  17054. accentGlyphId);
  17055. seacMap[charCode] = {
  17056. baseFontCharCode: baseFontCharCode,
  17057. accentFontCharCode: accentFontCharCode,
  17058. accentOffset: accentOffset
  17059. };
  17060. }
  17061. }
  17062. properties.seacMap = seacMap;
  17063. }
  17064. var unitsPerEm = 1 / (properties.fontMatrix || FONT_IDENTITY_MATRIX)[0];
  17065. var builder = new OpenTypeFileBuilder('\x4F\x54\x54\x4F');
  17066. // PostScript Font Program
  17067. builder.addTable('CFF ', font.data);
  17068. // OS/2 and Windows Specific metrics
  17069. builder.addTable('OS/2', createOS2Table(properties,
  17070. newMapping.charCodeToGlyphId));
  17071. // Character to glyphs mapping
  17072. builder.addTable('cmap', createCmapTable(newMapping.charCodeToGlyphId));
  17073. // Font header
  17074. builder.addTable('head',
  17075. '\x00\x01\x00\x00' + // Version number
  17076. '\x00\x00\x10\x00' + // fontRevision
  17077. '\x00\x00\x00\x00' + // checksumAdjustement
  17078. '\x5F\x0F\x3C\xF5' + // magicNumber
  17079. '\x00\x00' + // Flags
  17080. safeString16(unitsPerEm) + // unitsPerEM
  17081. '\x00\x00\x00\x00\x9e\x0b\x7e\x27' + // creation date
  17082. '\x00\x00\x00\x00\x9e\x0b\x7e\x27' + // modifification date
  17083. '\x00\x00' + // xMin
  17084. safeString16(properties.descent) + // yMin
  17085. '\x0F\xFF' + // xMax
  17086. safeString16(properties.ascent) + // yMax
  17087. string16(properties.italicAngle ? 2 : 0) + // macStyle
  17088. '\x00\x11' + // lowestRecPPEM
  17089. '\x00\x00' + // fontDirectionHint
  17090. '\x00\x00' + // indexToLocFormat
  17091. '\x00\x00'); // glyphDataFormat
  17092. // Horizontal header
  17093. builder.addTable('hhea',
  17094. '\x00\x01\x00\x00' + // Version number
  17095. safeString16(properties.ascent) + // Typographic Ascent
  17096. safeString16(properties.descent) + // Typographic Descent
  17097. '\x00\x00' + // Line Gap
  17098. '\xFF\xFF' + // advanceWidthMax
  17099. '\x00\x00' + // minLeftSidebearing
  17100. '\x00\x00' + // minRightSidebearing
  17101. '\x00\x00' + // xMaxExtent
  17102. safeString16(properties.capHeight) + // caretSlopeRise
  17103. safeString16(Math.tan(properties.italicAngle) *
  17104. properties.xHeight) + // caretSlopeRun
  17105. '\x00\x00' + // caretOffset
  17106. '\x00\x00' + // -reserved-
  17107. '\x00\x00' + // -reserved-
  17108. '\x00\x00' + // -reserved-
  17109. '\x00\x00' + // -reserved-
  17110. '\x00\x00' + // metricDataFormat
  17111. string16(numGlyphs)); // Number of HMetrics
  17112. // Horizontal metrics
  17113. builder.addTable('hmtx', (function fontFieldsHmtx() {
  17114. var charstrings = font.charstrings;
  17115. var cffWidths = font.cff ? font.cff.widths : null;
  17116. var hmtx = '\x00\x00\x00\x00'; // Fake .notdef
  17117. for (var i = 1, ii = numGlyphs; i < ii; i++) {
  17118. var width = 0;
  17119. if (charstrings) {
  17120. var charstring = charstrings[i - 1];
  17121. width = 'width' in charstring ? charstring.width : 0;
  17122. } else if (cffWidths) {
  17123. width = Math.ceil(cffWidths[i] || 0);
  17124. }
  17125. hmtx += string16(width) + string16(0);
  17126. }
  17127. return hmtx;
  17128. })());
  17129. // Maximum profile
  17130. builder.addTable('maxp',
  17131. '\x00\x00\x50\x00' + // Version number
  17132. string16(numGlyphs)); // Num of glyphs
  17133. // Naming tables
  17134. builder.addTable('name', createNameTable(fontName));
  17135. // PostScript informations
  17136. builder.addTable('post', createPostTable(properties));
  17137. return builder.toArray();
  17138. },
  17139. /**
  17140. * Builds a char code to unicode map based on section 9.10 of the spec.
  17141. * @param {Object} properties Font properties object.
  17142. * @return {Object} A ToUnicodeMap object.
  17143. */
  17144. buildToUnicode: function Font_buildToUnicode(properties) {
  17145. // Section 9.10.2 Mapping Character Codes to Unicode Values
  17146. if (properties.toUnicode && properties.toUnicode.length !== 0) {
  17147. return properties.toUnicode;
  17148. }
  17149. // According to the spec if the font is a simple font we should only map
  17150. // to unicode if the base encoding is MacRoman, MacExpert, or WinAnsi or
  17151. // the differences array only contains adobe standard or symbol set names,
  17152. // in pratice it seems better to always try to create a toUnicode
  17153. // map based of the default encoding.
  17154. var toUnicode, charcode;
  17155. if (!properties.composite /* is simple font */) {
  17156. toUnicode = [];
  17157. var encoding = properties.defaultEncoding.slice();
  17158. var baseEncodingName = properties.baseEncodingName;
  17159. // Merge in the differences array.
  17160. var differences = properties.differences;
  17161. for (charcode in differences) {
  17162. encoding[charcode] = differences[charcode];
  17163. }
  17164. for (charcode in encoding) {
  17165. // a) Map the character code to a character name.
  17166. var glyphName = encoding[charcode];
  17167. // b) Look up the character name in the Adobe Glyph List (see the
  17168. // Bibliography) to obtain the corresponding Unicode value.
  17169. if (glyphName === '') {
  17170. continue;
  17171. } else if (GlyphsUnicode[glyphName] === undefined) {
  17172. // (undocumented) c) Few heuristics to recognize unknown glyphs
  17173. // NOTE: Adobe Reader does not do this step, but OSX Preview does
  17174. var code = 0;
  17175. switch (glyphName[0]) {
  17176. case 'G': // Gxx glyph
  17177. if (glyphName.length === 3) {
  17178. code = parseInt(glyphName.substr(1), 16);
  17179. }
  17180. break;
  17181. case 'g': // g00xx glyph
  17182. if (glyphName.length === 5) {
  17183. code = parseInt(glyphName.substr(1), 16);
  17184. }
  17185. break;
  17186. case 'C': // Cddd glyph
  17187. case 'c': // cddd glyph
  17188. if (glyphName.length >= 3) {
  17189. code = +glyphName.substr(1);
  17190. }
  17191. break;
  17192. }
  17193. if (code) {
  17194. // If |baseEncodingName| is one the predefined encodings,
  17195. // and |code| equals |charcode|, using the glyph defined in the
  17196. // baseEncoding seems to yield a better |toUnicode| mapping
  17197. // (fixes issue 5070).
  17198. if (baseEncodingName && code === +charcode) {
  17199. var baseEncoding = Encodings[baseEncodingName];
  17200. if (baseEncoding && (glyphName = baseEncoding[charcode])) {
  17201. toUnicode[charcode] =
  17202. String.fromCharCode(GlyphsUnicode[glyphName]);
  17203. continue;
  17204. }
  17205. }
  17206. toUnicode[charcode] = String.fromCharCode(code);
  17207. }
  17208. continue;
  17209. }
  17210. toUnicode[charcode] = String.fromCharCode(GlyphsUnicode[glyphName]);
  17211. }
  17212. return new ToUnicodeMap(toUnicode);
  17213. }
  17214. // If the font is a composite font that uses one of the predefined CMaps
  17215. // listed in Table 118 (except Identity–H and Identity–V) or whose
  17216. // descendant CIDFont uses the Adobe-GB1, Adobe-CNS1, Adobe-Japan1, or
  17217. // Adobe-Korea1 character collection:
  17218. if (properties.composite && (
  17219. (properties.cMap.builtInCMap &&
  17220. !(properties.cMap instanceof IdentityCMap)) ||
  17221. (properties.cidSystemInfo.registry === 'Adobe' &&
  17222. (properties.cidSystemInfo.ordering === 'GB1' ||
  17223. properties.cidSystemInfo.ordering === 'CNS1' ||
  17224. properties.cidSystemInfo.ordering === 'Japan1' ||
  17225. properties.cidSystemInfo.ordering === 'Korea1')))) {
  17226. // Then:
  17227. // a) Map the character code to a character identifier (CID) according
  17228. // to the font’s CMap.
  17229. // b) Obtain the registry and ordering of the character collection used
  17230. // by the font’s CMap (for example, Adobe and Japan1) from its
  17231. // CIDSystemInfo dictionary.
  17232. var registry = properties.cidSystemInfo.registry;
  17233. var ordering = properties.cidSystemInfo.ordering;
  17234. // c) Construct a second CMap name by concatenating the registry and
  17235. // ordering obtained in step (b) in the format registry–ordering–UCS2
  17236. // (for example, Adobe–Japan1–UCS2).
  17237. var ucs2CMapName = new Name(registry + '-' + ordering + '-UCS2');
  17238. // d) Obtain the CMap with the name constructed in step (c) (available
  17239. // from the ASN Web site; see the Bibliography).
  17240. var ucs2CMap = CMapFactory.create(ucs2CMapName,
  17241. { url: PDFJS.cMapUrl, packed: PDFJS.cMapPacked }, null);
  17242. var cMap = properties.cMap;
  17243. toUnicode = [];
  17244. cMap.forEach(function(charcode, cid) {
  17245. assert(cid <= 0xffff, 'Max size of CID is 65,535');
  17246. // e) Map the CID obtained in step (a) according to the CMap obtained
  17247. // in step (d), producing a Unicode value.
  17248. var ucs2 = ucs2CMap.lookup(cid);
  17249. if (ucs2) {
  17250. toUnicode[charcode] =
  17251. String.fromCharCode((ucs2.charCodeAt(0) << 8) +
  17252. ucs2.charCodeAt(1));
  17253. }
  17254. });
  17255. return new ToUnicodeMap(toUnicode);
  17256. }
  17257. // The viewer's choice, just use an identity map.
  17258. return new IdentityToUnicodeMap(properties.firstChar,
  17259. properties.lastChar);
  17260. },
  17261. get spaceWidth() {
  17262. if ('_shadowWidth' in this) {
  17263. return this._shadowWidth;
  17264. }
  17265. // trying to estimate space character width
  17266. var possibleSpaceReplacements = ['space', 'minus', 'one', 'i'];
  17267. var width;
  17268. for (var i = 0, ii = possibleSpaceReplacements.length; i < ii; i++) {
  17269. var glyphName = possibleSpaceReplacements[i];
  17270. // if possible, getting width by glyph name
  17271. if (glyphName in this.widths) {
  17272. width = this.widths[glyphName];
  17273. break;
  17274. }
  17275. var glyphUnicode = GlyphsUnicode[glyphName];
  17276. // finding the charcode via unicodeToCID map
  17277. var charcode = 0;
  17278. if (this.composite) {
  17279. if (this.cMap.contains(glyphUnicode)) {
  17280. charcode = this.cMap.lookup(glyphUnicode);
  17281. }
  17282. }
  17283. // ... via toUnicode map
  17284. if (!charcode && 'toUnicode' in this) {
  17285. charcode = this.toUnicode.charCodeOf(glyphUnicode);
  17286. }
  17287. // setting it to unicode if negative or undefined
  17288. if (charcode <= 0) {
  17289. charcode = glyphUnicode;
  17290. }
  17291. // trying to get width via charcode
  17292. width = this.widths[charcode];
  17293. if (width) {
  17294. break; // the non-zero width found
  17295. }
  17296. }
  17297. width = width || this.defaultWidth;
  17298. // Do not shadow the property here. See discussion:
  17299. // https://github.com/mozilla/pdf.js/pull/2127#discussion_r1662280
  17300. this._shadowWidth = width;
  17301. return width;
  17302. },
  17303. charToGlyph: function Font_charToGlyph(charcode) {
  17304. var fontCharCode, width, operatorListId;
  17305. var widthCode = charcode;
  17306. if (this.cMap && this.cMap.contains(charcode)) {
  17307. widthCode = this.cMap.lookup(charcode);
  17308. }
  17309. width = this.widths[widthCode];
  17310. width = isNum(width) ? width : this.defaultWidth;
  17311. var vmetric = this.vmetrics && this.vmetrics[widthCode];
  17312. var unicode = this.toUnicode.get(charcode) || charcode;
  17313. if (typeof unicode === 'number') {
  17314. unicode = String.fromCharCode(unicode);
  17315. }
  17316. // First try the toFontChar map, if it's not there then try falling
  17317. // back to the char code.
  17318. fontCharCode = this.toFontChar[charcode] || charcode;
  17319. if (this.missingFile) {
  17320. fontCharCode = mapSpecialUnicodeValues(fontCharCode);
  17321. }
  17322. if (this.isType3Font) {
  17323. // Font char code in this case is actually a glyph name.
  17324. operatorListId = fontCharCode;
  17325. }
  17326. var accent = null;
  17327. if (this.seacMap && this.seacMap[charcode]) {
  17328. var seac = this.seacMap[charcode];
  17329. fontCharCode = seac.baseFontCharCode;
  17330. accent = {
  17331. fontChar: String.fromCharCode(seac.accentFontCharCode),
  17332. offset: seac.accentOffset
  17333. };
  17334. }
  17335. var fontChar = String.fromCharCode(fontCharCode);
  17336. var glyph = this.glyphCache[charcode];
  17337. if (!glyph ||
  17338. !glyph.matchesForCache(fontChar, unicode, accent, width, vmetric,
  17339. operatorListId)) {
  17340. glyph = new Glyph(fontChar, unicode, accent, width, vmetric,
  17341. operatorListId);
  17342. this.glyphCache[charcode] = glyph;
  17343. }
  17344. return glyph;
  17345. },
  17346. charsToGlyphs: function Font_charsToGlyphs(chars) {
  17347. var charsCache = this.charsCache;
  17348. var glyphs, glyph, charcode;
  17349. // if we translated this string before, just grab it from the cache
  17350. if (charsCache) {
  17351. glyphs = charsCache[chars];
  17352. if (glyphs) {
  17353. return glyphs;
  17354. }
  17355. }
  17356. // lazily create the translation cache
  17357. if (!charsCache) {
  17358. charsCache = this.charsCache = Object.create(null);
  17359. }
  17360. glyphs = [];
  17361. var charsCacheKey = chars;
  17362. var i = 0, ii;
  17363. if (this.cMap) {
  17364. // composite fonts have multi-byte strings convert the string from
  17365. // single-byte to multi-byte
  17366. var c = {};
  17367. while (i < chars.length) {
  17368. this.cMap.readCharCode(chars, i, c);
  17369. charcode = c.charcode;
  17370. var length = c.length;
  17371. i += length;
  17372. glyph = this.charToGlyph(charcode);
  17373. glyphs.push(glyph);
  17374. // placing null after each word break charcode (ASCII SPACE)
  17375. // Ignore occurences of 0x20 in multiple-byte codes.
  17376. if (length === 1 && chars.charCodeAt(i - 1) === 0x20) {
  17377. glyphs.push(null);
  17378. }
  17379. }
  17380. } else {
  17381. for (i = 0, ii = chars.length; i < ii; ++i) {
  17382. charcode = chars.charCodeAt(i);
  17383. glyph = this.charToGlyph(charcode);
  17384. glyphs.push(glyph);
  17385. if (charcode === 0x20) {
  17386. glyphs.push(null);
  17387. }
  17388. }
  17389. }
  17390. // Enter the translated string into the cache
  17391. return (charsCache[charsCacheKey] = glyphs);
  17392. }
  17393. };
  17394. return Font;
  17395. })();
  17396. var ErrorFont = (function ErrorFontClosure() {
  17397. function ErrorFont(error) {
  17398. this.error = error;
  17399. this.loadedName = 'g_font_error';
  17400. this.loading = false;
  17401. }
  17402. ErrorFont.prototype = {
  17403. charsToGlyphs: function ErrorFont_charsToGlyphs() {
  17404. return [];
  17405. },
  17406. exportData: function ErrorFont_exportData() {
  17407. return {error: this.error};
  17408. }
  17409. };
  17410. return ErrorFont;
  17411. })();
  17412. /**
  17413. * Shared logic for building a char code to glyph id mapping for Type1 and
  17414. * simple CFF fonts. See section 9.6.6.2 of the spec.
  17415. * @param {Object} properties Font properties object.
  17416. * @param {Object} builtInEncoding The encoding contained within the actual font
  17417. * data.
  17418. * @param {Array} Array of glyph names where the index is the glyph ID.
  17419. * @returns {Object} A char code to glyph ID map.
  17420. */
  17421. function type1FontGlyphMapping(properties, builtInEncoding, glyphNames) {
  17422. var charCodeToGlyphId = Object.create(null);
  17423. var glyphId, charCode, baseEncoding;
  17424. if (properties.baseEncodingName) {
  17425. // If a valid base encoding name was used, the mapping is initialized with
  17426. // that.
  17427. baseEncoding = Encodings[properties.baseEncodingName];
  17428. for (charCode = 0; charCode < baseEncoding.length; charCode++) {
  17429. glyphId = glyphNames.indexOf(baseEncoding[charCode]);
  17430. if (glyphId >= 0) {
  17431. charCodeToGlyphId[charCode] = glyphId;
  17432. } else {
  17433. charCodeToGlyphId[charCode] = 0; // notdef
  17434. }
  17435. }
  17436. } else if (!!(properties.flags & FontFlags.Symbolic)) {
  17437. // For a symbolic font the encoding should be the fonts built-in
  17438. // encoding.
  17439. for (charCode in builtInEncoding) {
  17440. charCodeToGlyphId[charCode] = builtInEncoding[charCode];
  17441. }
  17442. } else {
  17443. // For non-symbolic fonts that don't have a base encoding the standard
  17444. // encoding should be used.
  17445. baseEncoding = Encodings.StandardEncoding;
  17446. for (charCode = 0; charCode < baseEncoding.length; charCode++) {
  17447. glyphId = glyphNames.indexOf(baseEncoding[charCode]);
  17448. if (glyphId >= 0) {
  17449. charCodeToGlyphId[charCode] = glyphId;
  17450. } else {
  17451. charCodeToGlyphId[charCode] = 0; // notdef
  17452. }
  17453. }
  17454. }
  17455. // Lastly, merge in the differences.
  17456. var differences = properties.differences;
  17457. if (differences) {
  17458. for (charCode in differences) {
  17459. var glyphName = differences[charCode];
  17460. glyphId = glyphNames.indexOf(glyphName);
  17461. if (glyphId >= 0) {
  17462. charCodeToGlyphId[charCode] = glyphId;
  17463. } else {
  17464. charCodeToGlyphId[charCode] = 0; // notdef
  17465. }
  17466. }
  17467. }
  17468. return charCodeToGlyphId;
  17469. }
  17470. /*
  17471. * CharStrings are encoded following the the CharString Encoding sequence
  17472. * describe in Chapter 6 of the "Adobe Type1 Font Format" specification.
  17473. * The value in a byte indicates a command, a number, or subsequent bytes
  17474. * that are to be interpreted in a special way.
  17475. *
  17476. * CharString Number Encoding:
  17477. * A CharString byte containing the values from 32 through 255 inclusive
  17478. * indicate an integer. These values are decoded in four ranges.
  17479. *
  17480. * 1. A CharString byte containing a value, v, between 32 and 246 inclusive,
  17481. * indicate the integer v - 139. Thus, the integer values from -107 through
  17482. * 107 inclusive may be encoded in single byte.
  17483. *
  17484. * 2. A CharString byte containing a value, v, between 247 and 250 inclusive,
  17485. * indicates an integer involving the next byte, w, according to the formula:
  17486. * [(v - 247) x 256] + w + 108
  17487. *
  17488. * 3. A CharString byte containing a value, v, between 251 and 254 inclusive,
  17489. * indicates an integer involving the next byte, w, according to the formula:
  17490. * -[(v - 251) * 256] - w - 108
  17491. *
  17492. * 4. A CharString containing the value 255 indicates that the next 4 bytes
  17493. * are a two complement signed integer. The first of these bytes contains the
  17494. * highest order bits, the second byte contains the next higher order bits
  17495. * and the fourth byte contain the lowest order bits.
  17496. *
  17497. *
  17498. * CharString Command Encoding:
  17499. * CharStrings commands are encoded in 1 or 2 bytes.
  17500. *
  17501. * Single byte commands are encoded in 1 byte that contains a value between
  17502. * 0 and 31 inclusive.
  17503. * If a command byte contains the value 12, then the value in the next byte
  17504. * indicates a command. This "escape" mechanism allows many extra commands
  17505. * to be encoded and this encoding technique helps to minimize the length of
  17506. * the charStrings.
  17507. */
  17508. var Type1CharString = (function Type1CharStringClosure() {
  17509. var COMMAND_MAP = {
  17510. 'hstem': [1],
  17511. 'vstem': [3],
  17512. 'vmoveto': [4],
  17513. 'rlineto': [5],
  17514. 'hlineto': [6],
  17515. 'vlineto': [7],
  17516. 'rrcurveto': [8],
  17517. 'callsubr': [10],
  17518. 'flex': [12, 35],
  17519. 'drop' : [12, 18],
  17520. 'endchar': [14],
  17521. 'rmoveto': [21],
  17522. 'hmoveto': [22],
  17523. 'vhcurveto': [30],
  17524. 'hvcurveto': [31]
  17525. };
  17526. function Type1CharString() {
  17527. this.width = 0;
  17528. this.lsb = 0;
  17529. this.flexing = false;
  17530. this.output = [];
  17531. this.stack = [];
  17532. }
  17533. Type1CharString.prototype = {
  17534. convert: function Type1CharString_convert(encoded, subrs) {
  17535. var count = encoded.length;
  17536. var error = false;
  17537. var wx, sbx, subrNumber;
  17538. for (var i = 0; i < count; i++) {
  17539. var value = encoded[i];
  17540. if (value < 32) {
  17541. if (value === 12) {
  17542. value = (value << 8) + encoded[++i];
  17543. }
  17544. switch (value) {
  17545. case 1: // hstem
  17546. if (!HINTING_ENABLED) {
  17547. this.stack = [];
  17548. break;
  17549. }
  17550. error = this.executeCommand(2, COMMAND_MAP.hstem);
  17551. break;
  17552. case 3: // vstem
  17553. if (!HINTING_ENABLED) {
  17554. this.stack = [];
  17555. break;
  17556. }
  17557. error = this.executeCommand(2, COMMAND_MAP.vstem);
  17558. break;
  17559. case 4: // vmoveto
  17560. if (this.flexing) {
  17561. if (this.stack.length < 1) {
  17562. error = true;
  17563. break;
  17564. }
  17565. // Add the dx for flex and but also swap the values so they are
  17566. // the right order.
  17567. var dy = this.stack.pop();
  17568. this.stack.push(0, dy);
  17569. break;
  17570. }
  17571. error = this.executeCommand(1, COMMAND_MAP.vmoveto);
  17572. break;
  17573. case 5: // rlineto
  17574. error = this.executeCommand(2, COMMAND_MAP.rlineto);
  17575. break;
  17576. case 6: // hlineto
  17577. error = this.executeCommand(1, COMMAND_MAP.hlineto);
  17578. break;
  17579. case 7: // vlineto
  17580. error = this.executeCommand(1, COMMAND_MAP.vlineto);
  17581. break;
  17582. case 8: // rrcurveto
  17583. error = this.executeCommand(6, COMMAND_MAP.rrcurveto);
  17584. break;
  17585. case 9: // closepath
  17586. // closepath is a Type1 command that does not take argument and is
  17587. // useless in Type2 and it can simply be ignored.
  17588. this.stack = [];
  17589. break;
  17590. case 10: // callsubr
  17591. if (this.stack.length < 1) {
  17592. error = true;
  17593. break;
  17594. }
  17595. subrNumber = this.stack.pop();
  17596. error = this.convert(subrs[subrNumber], subrs);
  17597. break;
  17598. case 11: // return
  17599. return error;
  17600. case 13: // hsbw
  17601. if (this.stack.length < 2) {
  17602. error = true;
  17603. break;
  17604. }
  17605. // To convert to type2 we have to move the width value to the
  17606. // first part of the charstring and then use hmoveto with lsb.
  17607. wx = this.stack.pop();
  17608. sbx = this.stack.pop();
  17609. this.lsb = sbx;
  17610. this.width = wx;
  17611. this.stack.push(wx, sbx);
  17612. error = this.executeCommand(2, COMMAND_MAP.hmoveto);
  17613. break;
  17614. case 14: // endchar
  17615. this.output.push(COMMAND_MAP.endchar[0]);
  17616. break;
  17617. case 21: // rmoveto
  17618. if (this.flexing) {
  17619. break;
  17620. }
  17621. error = this.executeCommand(2, COMMAND_MAP.rmoveto);
  17622. break;
  17623. case 22: // hmoveto
  17624. if (this.flexing) {
  17625. // Add the dy for flex.
  17626. this.stack.push(0);
  17627. break;
  17628. }
  17629. error = this.executeCommand(1, COMMAND_MAP.hmoveto);
  17630. break;
  17631. case 30: // vhcurveto
  17632. error = this.executeCommand(4, COMMAND_MAP.vhcurveto);
  17633. break;
  17634. case 31: // hvcurveto
  17635. error = this.executeCommand(4, COMMAND_MAP.hvcurveto);
  17636. break;
  17637. case (12 << 8) + 0: // dotsection
  17638. // dotsection is a Type1 command to specify some hinting feature
  17639. // for dots that do not take a parameter and it can safely be
  17640. // ignored for Type2.
  17641. this.stack = [];
  17642. break;
  17643. case (12 << 8) + 1: // vstem3
  17644. if (!HINTING_ENABLED) {
  17645. this.stack = [];
  17646. break;
  17647. }
  17648. // [vh]stem3 are Type1 only and Type2 supports [vh]stem with
  17649. // multiple parameters, so instead of returning [vh]stem3 take a
  17650. // shortcut and return [vhstem] instead.
  17651. error = this.executeCommand(2, COMMAND_MAP.vstem);
  17652. break;
  17653. case (12 << 8) + 2: // hstem3
  17654. if (!HINTING_ENABLED) {
  17655. this.stack = [];
  17656. break;
  17657. }
  17658. // See vstem3.
  17659. error = this.executeCommand(2, COMMAND_MAP.hstem);
  17660. break;
  17661. case (12 << 8) + 6: // seac
  17662. // seac is like type 2's special endchar but it doesn't use the
  17663. // first argument asb, so remove it.
  17664. if (SEAC_ANALYSIS_ENABLED) {
  17665. this.seac = this.stack.splice(-4, 4);
  17666. error = this.executeCommand(0, COMMAND_MAP.endchar);
  17667. } else {
  17668. error = this.executeCommand(4, COMMAND_MAP.endchar);
  17669. }
  17670. break;
  17671. case (12 << 8) + 7: // sbw
  17672. if (this.stack.length < 4) {
  17673. error = true;
  17674. break;
  17675. }
  17676. // To convert to type2 we have to move the width value to the
  17677. // first part of the charstring and then use rmoveto with
  17678. // (dx, dy). The height argument will not be used for vmtx and
  17679. // vhea tables reconstruction -- ignoring it.
  17680. var wy = this.stack.pop();
  17681. wx = this.stack.pop();
  17682. var sby = this.stack.pop();
  17683. sbx = this.stack.pop();
  17684. this.lsb = sbx;
  17685. this.width = wx;
  17686. this.stack.push(wx, sbx, sby);
  17687. error = this.executeCommand(3, COMMAND_MAP.rmoveto);
  17688. break;
  17689. case (12 << 8) + 12: // div
  17690. if (this.stack.length < 2) {
  17691. error = true;
  17692. break;
  17693. }
  17694. var num2 = this.stack.pop();
  17695. var num1 = this.stack.pop();
  17696. this.stack.push(num1 / num2);
  17697. break;
  17698. case (12 << 8) + 16: // callothersubr
  17699. if (this.stack.length < 2) {
  17700. error = true;
  17701. break;
  17702. }
  17703. subrNumber = this.stack.pop();
  17704. var numArgs = this.stack.pop();
  17705. if (subrNumber === 0 && numArgs === 3) {
  17706. var flexArgs = this.stack.splice(this.stack.length - 17, 17);
  17707. this.stack.push(
  17708. flexArgs[2] + flexArgs[0], // bcp1x + rpx
  17709. flexArgs[3] + flexArgs[1], // bcp1y + rpy
  17710. flexArgs[4], // bcp2x
  17711. flexArgs[5], // bcp2y
  17712. flexArgs[6], // p2x
  17713. flexArgs[7], // p2y
  17714. flexArgs[8], // bcp3x
  17715. flexArgs[9], // bcp3y
  17716. flexArgs[10], // bcp4x
  17717. flexArgs[11], // bcp4y
  17718. flexArgs[12], // p3x
  17719. flexArgs[13], // p3y
  17720. flexArgs[14] // flexDepth
  17721. // 15 = finalx unused by flex
  17722. // 16 = finaly unused by flex
  17723. );
  17724. error = this.executeCommand(13, COMMAND_MAP.flex, true);
  17725. this.flexing = false;
  17726. this.stack.push(flexArgs[15], flexArgs[16]);
  17727. } else if (subrNumber === 1 && numArgs === 0) {
  17728. this.flexing = true;
  17729. }
  17730. break;
  17731. case (12 << 8) + 17: // pop
  17732. // Ignore this since it is only used with othersubr.
  17733. break;
  17734. case (12 << 8) + 33: // setcurrentpoint
  17735. // Ignore for now.
  17736. this.stack = [];
  17737. break;
  17738. default:
  17739. warn('Unknown type 1 charstring command of "' + value + '"');
  17740. break;
  17741. }
  17742. if (error) {
  17743. break;
  17744. }
  17745. continue;
  17746. } else if (value <= 246) {
  17747. value = value - 139;
  17748. } else if (value <= 250) {
  17749. value = ((value - 247) * 256) + encoded[++i] + 108;
  17750. } else if (value <= 254) {
  17751. value = -((value - 251) * 256) - encoded[++i] - 108;
  17752. } else {
  17753. value = (encoded[++i] & 0xff) << 24 | (encoded[++i] & 0xff) << 16 |
  17754. (encoded[++i] & 0xff) << 8 | (encoded[++i] & 0xff) << 0;
  17755. }
  17756. this.stack.push(value);
  17757. }
  17758. return error;
  17759. },
  17760. executeCommand: function(howManyArgs, command, keepStack) {
  17761. var stackLength = this.stack.length;
  17762. if (howManyArgs > stackLength) {
  17763. return true;
  17764. }
  17765. var start = stackLength - howManyArgs;
  17766. for (var i = start; i < stackLength; i++) {
  17767. var value = this.stack[i];
  17768. if (value === (value | 0)) { // int
  17769. this.output.push(28, (value >> 8) & 0xff, value & 0xff);
  17770. } else { // fixed point
  17771. value = (65536 * value) | 0;
  17772. this.output.push(255,
  17773. (value >> 24) & 0xFF,
  17774. (value >> 16) & 0xFF,
  17775. (value >> 8) & 0xFF,
  17776. value & 0xFF);
  17777. }
  17778. }
  17779. this.output.push.apply(this.output, command);
  17780. if (keepStack) {
  17781. this.stack.splice(start, howManyArgs);
  17782. } else {
  17783. this.stack.length = 0;
  17784. }
  17785. return false;
  17786. }
  17787. };
  17788. return Type1CharString;
  17789. })();
  17790. /*
  17791. * Type1Parser encapsulate the needed code for parsing a Type1 font
  17792. * program. Some of its logic depends on the Type2 charstrings
  17793. * structure.
  17794. * Note: this doesn't really parse the font since that would require evaluation
  17795. * of PostScript, but it is possible in most cases to extract what we need
  17796. * without a full parse.
  17797. */
  17798. var Type1Parser = (function Type1ParserClosure() {
  17799. /*
  17800. * Decrypt a Sequence of Ciphertext Bytes to Produce the Original Sequence
  17801. * of Plaintext Bytes. The function took a key as a parameter which can be
  17802. * for decrypting the eexec block of for decoding charStrings.
  17803. */
  17804. var EEXEC_ENCRYPT_KEY = 55665;
  17805. var CHAR_STRS_ENCRYPT_KEY = 4330;
  17806. function isHexDigit(code) {
  17807. return code >= 48 && code <= 57 || // '0'-'9'
  17808. code >= 65 && code <= 70 || // 'A'-'F'
  17809. code >= 97 && code <= 102; // 'a'-'f'
  17810. }
  17811. function decrypt(data, key, discardNumber) {
  17812. var r = key | 0, c1 = 52845, c2 = 22719;
  17813. var count = data.length;
  17814. var decrypted = new Uint8Array(count);
  17815. for (var i = 0; i < count; i++) {
  17816. var value = data[i];
  17817. decrypted[i] = value ^ (r >> 8);
  17818. r = ((value + r) * c1 + c2) & ((1 << 16) - 1);
  17819. }
  17820. return Array.prototype.slice.call(decrypted, discardNumber);
  17821. }
  17822. function decryptAscii(data, key, discardNumber) {
  17823. var r = key | 0, c1 = 52845, c2 = 22719;
  17824. var count = data.length, maybeLength = count >>> 1;
  17825. var decrypted = new Uint8Array(maybeLength);
  17826. var i, j;
  17827. for (i = 0, j = 0; i < count; i++) {
  17828. var digit1 = data[i];
  17829. if (!isHexDigit(digit1)) {
  17830. continue;
  17831. }
  17832. i++;
  17833. var digit2;
  17834. while (i < count && !isHexDigit(digit2 = data[i])) {
  17835. i++;
  17836. }
  17837. if (i < count) {
  17838. var value = parseInt(String.fromCharCode(digit1, digit2), 16);
  17839. decrypted[j++] = value ^ (r >> 8);
  17840. r = ((value + r) * c1 + c2) & ((1 << 16) - 1);
  17841. }
  17842. }
  17843. return Array.prototype.slice.call(decrypted, discardNumber, j);
  17844. }
  17845. function isSpecial(c) {
  17846. return c === 0x2F || // '/'
  17847. c === 0x5B || c === 0x5D || // '[', ']'
  17848. c === 0x7B || c === 0x7D || // '{', '}'
  17849. c === 0x28 || c === 0x29; // '(', ')'
  17850. }
  17851. function Type1Parser(stream, encrypted) {
  17852. if (encrypted) {
  17853. var data = stream.getBytes();
  17854. var isBinary = !(isHexDigit(data[0]) && isHexDigit(data[1]) &&
  17855. isHexDigit(data[2]) && isHexDigit(data[3]));
  17856. stream = new Stream(isBinary ? decrypt(data, EEXEC_ENCRYPT_KEY, 4) :
  17857. decryptAscii(data, EEXEC_ENCRYPT_KEY, 4));
  17858. }
  17859. this.stream = stream;
  17860. this.nextChar();
  17861. }
  17862. Type1Parser.prototype = {
  17863. readNumberArray: function Type1Parser_readNumberArray() {
  17864. this.getToken(); // read '[' or '{' (arrays can start with either)
  17865. var array = [];
  17866. while (true) {
  17867. var token = this.getToken();
  17868. if (token === null || token === ']' || token === '}') {
  17869. break;
  17870. }
  17871. array.push(parseFloat(token || 0));
  17872. }
  17873. return array;
  17874. },
  17875. readNumber: function Type1Parser_readNumber() {
  17876. var token = this.getToken();
  17877. return parseFloat(token || 0);
  17878. },
  17879. readInt: function Type1Parser_readInt() {
  17880. // Use '| 0' to prevent setting a double into length such as the double
  17881. // does not flow into the loop variable.
  17882. var token = this.getToken();
  17883. return parseInt(token || 0, 10) | 0;
  17884. },
  17885. readBoolean: function Type1Parser_readBoolean() {
  17886. var token = this.getToken();
  17887. // Use 1 and 0 since that's what type2 charstrings use.
  17888. return token === 'true' ? 1 : 0;
  17889. },
  17890. nextChar : function Type1_nextChar() {
  17891. return (this.currentChar = this.stream.getByte());
  17892. },
  17893. getToken: function Type1Parser_getToken() {
  17894. // Eat whitespace and comments.
  17895. var comment = false;
  17896. var ch = this.currentChar;
  17897. while (true) {
  17898. if (ch === -1) {
  17899. return null;
  17900. }
  17901. if (comment) {
  17902. if (ch === 0x0A || ch === 0x0D) {
  17903. comment = false;
  17904. }
  17905. } else if (ch === 0x25) { // '%'
  17906. comment = true;
  17907. } else if (!Lexer.isSpace(ch)) {
  17908. break;
  17909. }
  17910. ch = this.nextChar();
  17911. }
  17912. if (isSpecial(ch)) {
  17913. this.nextChar();
  17914. return String.fromCharCode(ch);
  17915. }
  17916. var token = '';
  17917. do {
  17918. token += String.fromCharCode(ch);
  17919. ch = this.nextChar();
  17920. } while (ch >= 0 && !Lexer.isSpace(ch) && !isSpecial(ch));
  17921. return token;
  17922. },
  17923. /*
  17924. * Returns an object containing a Subrs array and a CharStrings
  17925. * array extracted from and eexec encrypted block of data
  17926. */
  17927. extractFontProgram: function Type1Parser_extractFontProgram() {
  17928. var stream = this.stream;
  17929. var subrs = [], charstrings = [];
  17930. var program = {
  17931. subrs: [],
  17932. charstrings: [],
  17933. properties: {
  17934. 'privateData': {
  17935. 'lenIV': 4
  17936. }
  17937. }
  17938. };
  17939. var token, length, data, lenIV, encoded;
  17940. while ((token = this.getToken()) !== null) {
  17941. if (token !== '/') {
  17942. continue;
  17943. }
  17944. token = this.getToken();
  17945. switch (token) {
  17946. case 'CharStrings':
  17947. // The number immediately following CharStrings must be greater or
  17948. // equal to the number of CharStrings.
  17949. this.getToken();
  17950. this.getToken(); // read in 'dict'
  17951. this.getToken(); // read in 'dup'
  17952. this.getToken(); // read in 'begin'
  17953. while(true) {
  17954. token = this.getToken();
  17955. if (token === null || token === 'end') {
  17956. break;
  17957. }
  17958. if (token !== '/') {
  17959. continue;
  17960. }
  17961. var glyph = this.getToken();
  17962. length = this.readInt();
  17963. this.getToken(); // read in 'RD' or '-|'
  17964. data = stream.makeSubStream(stream.pos, length);
  17965. lenIV = program.properties.privateData['lenIV'];
  17966. encoded = decrypt(data.getBytes(), CHAR_STRS_ENCRYPT_KEY, lenIV);
  17967. // Skip past the required space and binary data.
  17968. stream.skip(length);
  17969. this.nextChar();
  17970. token = this.getToken(); // read in 'ND' or '|-'
  17971. if (token === 'noaccess') {
  17972. this.getToken(); // read in 'def'
  17973. }
  17974. charstrings.push({
  17975. glyph: glyph,
  17976. encoded: encoded
  17977. });
  17978. }
  17979. break;
  17980. case 'Subrs':
  17981. var num = this.readInt();
  17982. this.getToken(); // read in 'array'
  17983. while ((token = this.getToken()) === 'dup') {
  17984. var index = this.readInt();
  17985. length = this.readInt();
  17986. this.getToken(); // read in 'RD' or '-|'
  17987. data = stream.makeSubStream(stream.pos, length);
  17988. lenIV = program.properties.privateData['lenIV'];
  17989. encoded = decrypt(data.getBytes(), CHAR_STRS_ENCRYPT_KEY, lenIV);
  17990. // Skip past the required space and binary data.
  17991. stream.skip(length);
  17992. this.nextChar();
  17993. token = this.getToken(); // read in 'NP' or '|'
  17994. if (token === 'noaccess') {
  17995. this.getToken(); // read in 'put'
  17996. }
  17997. subrs[index] = encoded;
  17998. }
  17999. break;
  18000. case 'BlueValues':
  18001. case 'OtherBlues':
  18002. case 'FamilyBlues':
  18003. case 'FamilyOtherBlues':
  18004. var blueArray = this.readNumberArray();
  18005. // *Blue* values may contain invalid data: disables reading of
  18006. // those values when hinting is disabled.
  18007. if (blueArray.length > 0 && (blueArray.length % 2) === 0 &&
  18008. HINTING_ENABLED) {
  18009. program.properties.privateData[token] = blueArray;
  18010. }
  18011. break;
  18012. case 'StemSnapH':
  18013. case 'StemSnapV':
  18014. program.properties.privateData[token] = this.readNumberArray();
  18015. break;
  18016. case 'StdHW':
  18017. case 'StdVW':
  18018. program.properties.privateData[token] =
  18019. this.readNumberArray()[0];
  18020. break;
  18021. case 'BlueShift':
  18022. case 'lenIV':
  18023. case 'BlueFuzz':
  18024. case 'BlueScale':
  18025. case 'LanguageGroup':
  18026. case 'ExpansionFactor':
  18027. program.properties.privateData[token] = this.readNumber();
  18028. break;
  18029. case 'ForceBold':
  18030. program.properties.privateData[token] = this.readBoolean();
  18031. break;
  18032. }
  18033. }
  18034. for (var i = 0; i < charstrings.length; i++) {
  18035. glyph = charstrings[i].glyph;
  18036. encoded = charstrings[i].encoded;
  18037. var charString = new Type1CharString();
  18038. var error = charString.convert(encoded, subrs);
  18039. var output = charString.output;
  18040. if (error) {
  18041. // It seems when FreeType encounters an error while evaluating a glyph
  18042. // that it completely ignores the glyph so we'll mimic that behaviour
  18043. // here and put an endchar to make the validator happy.
  18044. output = [14];
  18045. }
  18046. program.charstrings.push({
  18047. glyphName: glyph,
  18048. charstring: output,
  18049. width: charString.width,
  18050. lsb: charString.lsb,
  18051. seac: charString.seac
  18052. });
  18053. }
  18054. return program;
  18055. },
  18056. extractFontHeader: function Type1Parser_extractFontHeader(properties) {
  18057. var token;
  18058. while ((token = this.getToken()) !== null) {
  18059. if (token !== '/') {
  18060. continue;
  18061. }
  18062. token = this.getToken();
  18063. switch (token) {
  18064. case 'FontMatrix':
  18065. var matrix = this.readNumberArray();
  18066. properties.fontMatrix = matrix;
  18067. break;
  18068. case 'Encoding':
  18069. var encodingArg = this.getToken();
  18070. var encoding;
  18071. if (!/^\d+$/.test(encodingArg)) {
  18072. // encoding name is specified
  18073. encoding = Encodings[encodingArg];
  18074. } else {
  18075. encoding = [];
  18076. var size = parseInt(encodingArg, 10) | 0;
  18077. this.getToken(); // read in 'array'
  18078. for (var j = 0; j < size; j++) {
  18079. token = this.getToken();
  18080. // skipping till first dup or def (e.g. ignoring for statement)
  18081. while (token !== 'dup' && token !== 'def') {
  18082. token = this.getToken();
  18083. if (token === null) {
  18084. return; // invalid header
  18085. }
  18086. }
  18087. if (token === 'def') {
  18088. break; // read all array data
  18089. }
  18090. var index = this.readInt();
  18091. this.getToken(); // read in '/'
  18092. var glyph = this.getToken();
  18093. encoding[index] = glyph;
  18094. this.getToken(); // read the in 'put'
  18095. }
  18096. }
  18097. properties.builtInEncoding = encoding;
  18098. break;
  18099. case 'FontBBox':
  18100. var fontBBox = this.readNumberArray();
  18101. // adjusting ascent/descent
  18102. properties.ascent = fontBBox[3];
  18103. properties.descent = fontBBox[1];
  18104. properties.ascentScaled = true;
  18105. break;
  18106. }
  18107. }
  18108. }
  18109. };
  18110. return Type1Parser;
  18111. })();
  18112. /**
  18113. * The CFF class takes a Type1 file and wrap it into a
  18114. * 'Compact Font Format' which itself embed Type2 charstrings.
  18115. */
  18116. var CFFStandardStrings = [
  18117. '.notdef', 'space', 'exclam', 'quotedbl', 'numbersign', 'dollar', 'percent',
  18118. 'ampersand', 'quoteright', 'parenleft', 'parenright', 'asterisk', 'plus',
  18119. 'comma', 'hyphen', 'period', 'slash', 'zero', 'one', 'two', 'three', 'four',
  18120. 'five', 'six', 'seven', 'eight', 'nine', 'colon', 'semicolon', 'less',
  18121. 'equal', 'greater', 'question', 'at', 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H',
  18122. 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W',
  18123. 'X', 'Y', 'Z', 'bracketleft', 'backslash', 'bracketright', 'asciicircum',
  18124. 'underscore', 'quoteleft', 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j',
  18125. 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y',
  18126. 'z', 'braceleft', 'bar', 'braceright', 'asciitilde', 'exclamdown', 'cent',
  18127. 'sterling', 'fraction', 'yen', 'florin', 'section', 'currency',
  18128. 'quotesingle', 'quotedblleft', 'guillemotleft', 'guilsinglleft',
  18129. 'guilsinglright', 'fi', 'fl', 'endash', 'dagger', 'daggerdbl',
  18130. 'periodcentered', 'paragraph', 'bullet', 'quotesinglbase', 'quotedblbase',
  18131. 'quotedblright', 'guillemotright', 'ellipsis', 'perthousand', 'questiondown',
  18132. 'grave', 'acute', 'circumflex', 'tilde', 'macron', 'breve', 'dotaccent',
  18133. 'dieresis', 'ring', 'cedilla', 'hungarumlaut', 'ogonek', 'caron', 'emdash',
  18134. 'AE', 'ordfeminine', 'Lslash', 'Oslash', 'OE', 'ordmasculine', 'ae',
  18135. 'dotlessi', 'lslash', 'oslash', 'oe', 'germandbls', 'onesuperior',
  18136. 'logicalnot', 'mu', 'trademark', 'Eth', 'onehalf', 'plusminus', 'Thorn',
  18137. 'onequarter', 'divide', 'brokenbar', 'degree', 'thorn', 'threequarters',
  18138. 'twosuperior', 'registered', 'minus', 'eth', 'multiply', 'threesuperior',
  18139. 'copyright', 'Aacute', 'Acircumflex', 'Adieresis', 'Agrave', 'Aring',
  18140. 'Atilde', 'Ccedilla', 'Eacute', 'Ecircumflex', 'Edieresis', 'Egrave',
  18141. 'Iacute', 'Icircumflex', 'Idieresis', 'Igrave', 'Ntilde', 'Oacute',
  18142. 'Ocircumflex', 'Odieresis', 'Ograve', 'Otilde', 'Scaron', 'Uacute',
  18143. 'Ucircumflex', 'Udieresis', 'Ugrave', 'Yacute', 'Ydieresis', 'Zcaron',
  18144. 'aacute', 'acircumflex', 'adieresis', 'agrave', 'aring', 'atilde',
  18145. 'ccedilla', 'eacute', 'ecircumflex', 'edieresis', 'egrave', 'iacute',
  18146. 'icircumflex', 'idieresis', 'igrave', 'ntilde', 'oacute', 'ocircumflex',
  18147. 'odieresis', 'ograve', 'otilde', 'scaron', 'uacute', 'ucircumflex',
  18148. 'udieresis', 'ugrave', 'yacute', 'ydieresis', 'zcaron', 'exclamsmall',
  18149. 'Hungarumlautsmall', 'dollaroldstyle', 'dollarsuperior', 'ampersandsmall',
  18150. 'Acutesmall', 'parenleftsuperior', 'parenrightsuperior', 'twodotenleader',
  18151. 'onedotenleader', 'zerooldstyle', 'oneoldstyle', 'twooldstyle',
  18152. 'threeoldstyle', 'fouroldstyle', 'fiveoldstyle', 'sixoldstyle',
  18153. 'sevenoldstyle', 'eightoldstyle', 'nineoldstyle', 'commasuperior',
  18154. 'threequartersemdash', 'periodsuperior', 'questionsmall', 'asuperior',
  18155. 'bsuperior', 'centsuperior', 'dsuperior', 'esuperior', 'isuperior',
  18156. 'lsuperior', 'msuperior', 'nsuperior', 'osuperior', 'rsuperior', 'ssuperior',
  18157. 'tsuperior', 'ff', 'ffi', 'ffl', 'parenleftinferior', 'parenrightinferior',
  18158. 'Circumflexsmall', 'hyphensuperior', 'Gravesmall', 'Asmall', 'Bsmall',
  18159. 'Csmall', 'Dsmall', 'Esmall', 'Fsmall', 'Gsmall', 'Hsmall', 'Ismall',
  18160. 'Jsmall', 'Ksmall', 'Lsmall', 'Msmall', 'Nsmall', 'Osmall', 'Psmall',
  18161. 'Qsmall', 'Rsmall', 'Ssmall', 'Tsmall', 'Usmall', 'Vsmall', 'Wsmall',
  18162. 'Xsmall', 'Ysmall', 'Zsmall', 'colonmonetary', 'onefitted', 'rupiah',
  18163. 'Tildesmall', 'exclamdownsmall', 'centoldstyle', 'Lslashsmall',
  18164. 'Scaronsmall', 'Zcaronsmall', 'Dieresissmall', 'Brevesmall', 'Caronsmall',
  18165. 'Dotaccentsmall', 'Macronsmall', 'figuredash', 'hypheninferior',
  18166. 'Ogoneksmall', 'Ringsmall', 'Cedillasmall', 'questiondownsmall', 'oneeighth',
  18167. 'threeeighths', 'fiveeighths', 'seveneighths', 'onethird', 'twothirds',
  18168. 'zerosuperior', 'foursuperior', 'fivesuperior', 'sixsuperior',
  18169. 'sevensuperior', 'eightsuperior', 'ninesuperior', 'zeroinferior',
  18170. 'oneinferior', 'twoinferior', 'threeinferior', 'fourinferior',
  18171. 'fiveinferior', 'sixinferior', 'seveninferior', 'eightinferior',
  18172. 'nineinferior', 'centinferior', 'dollarinferior', 'periodinferior',
  18173. 'commainferior', 'Agravesmall', 'Aacutesmall', 'Acircumflexsmall',
  18174. 'Atildesmall', 'Adieresissmall', 'Aringsmall', 'AEsmall', 'Ccedillasmall',
  18175. 'Egravesmall', 'Eacutesmall', 'Ecircumflexsmall', 'Edieresissmall',
  18176. 'Igravesmall', 'Iacutesmall', 'Icircumflexsmall', 'Idieresissmall',
  18177. 'Ethsmall', 'Ntildesmall', 'Ogravesmall', 'Oacutesmall', 'Ocircumflexsmall',
  18178. 'Otildesmall', 'Odieresissmall', 'OEsmall', 'Oslashsmall', 'Ugravesmall',
  18179. 'Uacutesmall', 'Ucircumflexsmall', 'Udieresissmall', 'Yacutesmall',
  18180. 'Thornsmall', 'Ydieresissmall', '001.000', '001.001', '001.002', '001.003',
  18181. 'Black', 'Bold', 'Book', 'Light', 'Medium', 'Regular', 'Roman', 'Semibold'
  18182. ];
  18183. // Type1Font is also a CIDFontType0.
  18184. var Type1Font = function Type1Font(name, file, properties) {
  18185. // Some bad generators embed pfb file as is, we have to strip 6-byte headers.
  18186. // Also, length1 and length2 might be off by 6 bytes as well.
  18187. // http://www.math.ubc.ca/~cass/piscript/type1.pdf
  18188. var PFB_HEADER_SIZE = 6;
  18189. var headerBlockLength = properties.length1;
  18190. var eexecBlockLength = properties.length2;
  18191. var pfbHeader = file.peekBytes(PFB_HEADER_SIZE);
  18192. var pfbHeaderPresent = pfbHeader[0] === 0x80 && pfbHeader[1] === 0x01;
  18193. if (pfbHeaderPresent) {
  18194. file.skip(PFB_HEADER_SIZE);
  18195. headerBlockLength = (pfbHeader[5] << 24) | (pfbHeader[4] << 16) |
  18196. (pfbHeader[3] << 8) | pfbHeader[2];
  18197. }
  18198. // Get the data block containing glyphs and subrs informations
  18199. var headerBlock = new Stream(file.getBytes(headerBlockLength));
  18200. var headerBlockParser = new Type1Parser(headerBlock);
  18201. headerBlockParser.extractFontHeader(properties);
  18202. if (pfbHeaderPresent) {
  18203. pfbHeader = file.getBytes(PFB_HEADER_SIZE);
  18204. eexecBlockLength = (pfbHeader[5] << 24) | (pfbHeader[4] << 16) |
  18205. (pfbHeader[3] << 8) | pfbHeader[2];
  18206. }
  18207. // Decrypt the data blocks and retrieve it's content
  18208. var eexecBlock = new Stream(file.getBytes(eexecBlockLength));
  18209. var eexecBlockParser = new Type1Parser(eexecBlock, true);
  18210. var data = eexecBlockParser.extractFontProgram();
  18211. for (var info in data.properties) {
  18212. properties[info] = data.properties[info];
  18213. }
  18214. var charstrings = data.charstrings;
  18215. var type2Charstrings = this.getType2Charstrings(charstrings);
  18216. var subrs = this.getType2Subrs(data.subrs);
  18217. this.charstrings = charstrings;
  18218. this.data = this.wrap(name, type2Charstrings, this.charstrings,
  18219. subrs, properties);
  18220. this.seacs = this.getSeacs(data.charstrings);
  18221. };
  18222. Type1Font.prototype = {
  18223. get numGlyphs() {
  18224. return this.charstrings.length + 1;
  18225. },
  18226. getCharset: function Type1Font_getCharset() {
  18227. var charset = ['.notdef'];
  18228. var charstrings = this.charstrings;
  18229. for (var glyphId = 0; glyphId < charstrings.length; glyphId++) {
  18230. charset.push(charstrings[glyphId].glyphName);
  18231. }
  18232. return charset;
  18233. },
  18234. getGlyphMapping: function Type1Font_getGlyphMapping(properties) {
  18235. var charstrings = this.charstrings;
  18236. var glyphNames = ['.notdef'], glyphId;
  18237. for (glyphId = 0; glyphId < charstrings.length; glyphId++) {
  18238. glyphNames.push(charstrings[glyphId].glyphName);
  18239. }
  18240. var encoding = properties.builtInEncoding;
  18241. if (encoding) {
  18242. var builtInEncoding = {};
  18243. for (var charCode in encoding) {
  18244. glyphId = glyphNames.indexOf(encoding[charCode]);
  18245. if (glyphId >= 0) {
  18246. builtInEncoding[charCode] = glyphId;
  18247. }
  18248. }
  18249. }
  18250. return type1FontGlyphMapping(properties, builtInEncoding, glyphNames);
  18251. },
  18252. getSeacs: function Type1Font_getSeacs(charstrings) {
  18253. var i, ii;
  18254. var seacMap = [];
  18255. for (i = 0, ii = charstrings.length; i < ii; i++) {
  18256. var charstring = charstrings[i];
  18257. if (charstring.seac) {
  18258. // Offset by 1 for .notdef
  18259. seacMap[i + 1] = charstring.seac;
  18260. }
  18261. }
  18262. return seacMap;
  18263. },
  18264. getType2Charstrings: function Type1Font_getType2Charstrings(
  18265. type1Charstrings) {
  18266. var type2Charstrings = [];
  18267. for (var i = 0, ii = type1Charstrings.length; i < ii; i++) {
  18268. type2Charstrings.push(type1Charstrings[i].charstring);
  18269. }
  18270. return type2Charstrings;
  18271. },
  18272. getType2Subrs: function Type1Font_getType2Subrs(type1Subrs) {
  18273. var bias = 0;
  18274. var count = type1Subrs.length;
  18275. if (count < 1133) {
  18276. bias = 107;
  18277. } else if (count < 33769) {
  18278. bias = 1131;
  18279. } else {
  18280. bias = 32768;
  18281. }
  18282. // Add a bunch of empty subrs to deal with the Type2 bias
  18283. var type2Subrs = [];
  18284. var i;
  18285. for (i = 0; i < bias; i++) {
  18286. type2Subrs.push([0x0B]);
  18287. }
  18288. for (i = 0; i < count; i++) {
  18289. type2Subrs.push(type1Subrs[i]);
  18290. }
  18291. return type2Subrs;
  18292. },
  18293. wrap: function Type1Font_wrap(name, glyphs, charstrings, subrs, properties) {
  18294. var cff = new CFF();
  18295. cff.header = new CFFHeader(1, 0, 4, 4);
  18296. cff.names = [name];
  18297. var topDict = new CFFTopDict();
  18298. // CFF strings IDs 0...390 are predefined names, so refering
  18299. // to entries in our own String INDEX starts at SID 391.
  18300. topDict.setByName('version', 391);
  18301. topDict.setByName('Notice', 392);
  18302. topDict.setByName('FullName', 393);
  18303. topDict.setByName('FamilyName', 394);
  18304. topDict.setByName('Weight', 395);
  18305. topDict.setByName('Encoding', null); // placeholder
  18306. topDict.setByName('FontMatrix', properties.fontMatrix);
  18307. topDict.setByName('FontBBox', properties.bbox);
  18308. topDict.setByName('charset', null); // placeholder
  18309. topDict.setByName('CharStrings', null); // placeholder
  18310. topDict.setByName('Private', null); // placeholder
  18311. cff.topDict = topDict;
  18312. var strings = new CFFStrings();
  18313. strings.add('Version 0.11'); // Version
  18314. strings.add('See original notice'); // Notice
  18315. strings.add(name); // FullName
  18316. strings.add(name); // FamilyName
  18317. strings.add('Medium'); // Weight
  18318. cff.strings = strings;
  18319. cff.globalSubrIndex = new CFFIndex();
  18320. var count = glyphs.length;
  18321. var charsetArray = [0];
  18322. var i, ii;
  18323. for (i = 0; i < count; i++) {
  18324. var index = CFFStandardStrings.indexOf(charstrings[i].glyphName);
  18325. // TODO: Insert the string and correctly map it. Previously it was
  18326. // thought mapping names that aren't in the standard strings to .notdef
  18327. // was fine, however in issue818 when mapping them all to .notdef the
  18328. // adieresis glyph no longer worked.
  18329. if (index === -1) {
  18330. index = 0;
  18331. }
  18332. charsetArray.push((index >> 8) & 0xff, index & 0xff);
  18333. }
  18334. cff.charset = new CFFCharset(false, 0, [], charsetArray);
  18335. var charStringsIndex = new CFFIndex();
  18336. charStringsIndex.add([0x8B, 0x0E]); // .notdef
  18337. for (i = 0; i < count; i++) {
  18338. charStringsIndex.add(glyphs[i]);
  18339. }
  18340. cff.charStrings = charStringsIndex;
  18341. var privateDict = new CFFPrivateDict();
  18342. privateDict.setByName('Subrs', null); // placeholder
  18343. var fields = [
  18344. 'BlueValues',
  18345. 'OtherBlues',
  18346. 'FamilyBlues',
  18347. 'FamilyOtherBlues',
  18348. 'StemSnapH',
  18349. 'StemSnapV',
  18350. 'BlueShift',
  18351. 'BlueFuzz',
  18352. 'BlueScale',
  18353. 'LanguageGroup',
  18354. 'ExpansionFactor',
  18355. 'ForceBold',
  18356. 'StdHW',
  18357. 'StdVW'
  18358. ];
  18359. for (i = 0, ii = fields.length; i < ii; i++) {
  18360. var field = fields[i];
  18361. if (!properties.privateData.hasOwnProperty(field)) {
  18362. continue;
  18363. }
  18364. var value = properties.privateData[field];
  18365. if (isArray(value)) {
  18366. // All of the private dictionary array data in CFF must be stored as
  18367. // "delta-encoded" numbers.
  18368. for (var j = value.length - 1; j > 0; j--) {
  18369. value[j] -= value[j - 1]; // ... difference from previous value
  18370. }
  18371. }
  18372. privateDict.setByName(field, value);
  18373. }
  18374. cff.topDict.privateDict = privateDict;
  18375. var subrIndex = new CFFIndex();
  18376. for (i = 0, ii = subrs.length; i < ii; i++) {
  18377. subrIndex.add(subrs[i]);
  18378. }
  18379. privateDict.subrsIndex = subrIndex;
  18380. var compiler = new CFFCompiler(cff);
  18381. return compiler.compile();
  18382. }
  18383. };
  18384. var CFFFont = (function CFFFontClosure() {
  18385. function CFFFont(file, properties) {
  18386. this.properties = properties;
  18387. var parser = new CFFParser(file, properties);
  18388. this.cff = parser.parse();
  18389. var compiler = new CFFCompiler(this.cff);
  18390. this.seacs = this.cff.seacs;
  18391. try {
  18392. this.data = compiler.compile();
  18393. } catch (e) {
  18394. warn('Failed to compile font ' + properties.loadedName);
  18395. // There may have just been an issue with the compiler, set the data
  18396. // anyway and hope the font loaded.
  18397. this.data = file;
  18398. }
  18399. }
  18400. CFFFont.prototype = {
  18401. get numGlyphs() {
  18402. return this.cff.charStrings.count;
  18403. },
  18404. getCharset: function CFFFont_getCharset() {
  18405. return this.cff.charset.charset;
  18406. },
  18407. getGlyphMapping: function CFFFont_getGlyphMapping() {
  18408. var cff = this.cff;
  18409. var properties = this.properties;
  18410. var charsets = cff.charset.charset;
  18411. var charCodeToGlyphId;
  18412. var glyphId;
  18413. if (properties.composite) {
  18414. charCodeToGlyphId = Object.create(null);
  18415. if (cff.isCIDFont) {
  18416. // If the font is actually a CID font then we should use the charset
  18417. // to map CIDs to GIDs.
  18418. for (glyphId = 0; glyphId < charsets.length; glyphId++) {
  18419. var cid = charsets[glyphId];
  18420. var charCode = properties.cMap.charCodeOf(cid);
  18421. charCodeToGlyphId[charCode] = glyphId;
  18422. }
  18423. } else {
  18424. // If it is NOT actually a CID font then CIDs should be mapped
  18425. // directly to GIDs.
  18426. for (glyphId = 0; glyphId < cff.charStrings.count; glyphId++) {
  18427. charCodeToGlyphId[glyphId] = glyphId;
  18428. }
  18429. }
  18430. return charCodeToGlyphId;
  18431. }
  18432. var encoding = cff.encoding ? cff.encoding.encoding : null;
  18433. charCodeToGlyphId = type1FontGlyphMapping(properties, encoding, charsets);
  18434. return charCodeToGlyphId;
  18435. }
  18436. };
  18437. return CFFFont;
  18438. })();
  18439. var CFFParser = (function CFFParserClosure() {
  18440. var CharstringValidationData = [
  18441. null,
  18442. { id: 'hstem', min: 2, stackClearing: true, stem: true },
  18443. null,
  18444. { id: 'vstem', min: 2, stackClearing: true, stem: true },
  18445. { id: 'vmoveto', min: 1, stackClearing: true },
  18446. { id: 'rlineto', min: 2, resetStack: true },
  18447. { id: 'hlineto', min: 1, resetStack: true },
  18448. { id: 'vlineto', min: 1, resetStack: true },
  18449. { id: 'rrcurveto', min: 6, resetStack: true },
  18450. null,
  18451. { id: 'callsubr', min: 1, undefStack: true },
  18452. { id: 'return', min: 0, undefStack: true },
  18453. null, // 12
  18454. null,
  18455. { id: 'endchar', min: 0, stackClearing: true },
  18456. null,
  18457. null,
  18458. null,
  18459. { id: 'hstemhm', min: 2, stackClearing: true, stem: true },
  18460. { id: 'hintmask', min: 0, stackClearing: true },
  18461. { id: 'cntrmask', min: 0, stackClearing: true },
  18462. { id: 'rmoveto', min: 2, stackClearing: true },
  18463. { id: 'hmoveto', min: 1, stackClearing: true },
  18464. { id: 'vstemhm', min: 2, stackClearing: true, stem: true },
  18465. { id: 'rcurveline', min: 8, resetStack: true },
  18466. { id: 'rlinecurve', min: 8, resetStack: true },
  18467. { id: 'vvcurveto', min: 4, resetStack: true },
  18468. { id: 'hhcurveto', min: 4, resetStack: true },
  18469. null, // shortint
  18470. { id: 'callgsubr', min: 1, undefStack: true },
  18471. { id: 'vhcurveto', min: 4, resetStack: true },
  18472. { id: 'hvcurveto', min: 4, resetStack: true }
  18473. ];
  18474. var CharstringValidationData12 = [
  18475. null,
  18476. null,
  18477. null,
  18478. { id: 'and', min: 2, stackDelta: -1 },
  18479. { id: 'or', min: 2, stackDelta: -1 },
  18480. { id: 'not', min: 1, stackDelta: 0 },
  18481. null,
  18482. null,
  18483. null,
  18484. { id: 'abs', min: 1, stackDelta: 0 },
  18485. { id: 'add', min: 2, stackDelta: -1,
  18486. stackFn: function stack_div(stack, index) {
  18487. stack[index - 2] = stack[index - 2] + stack[index - 1];
  18488. }
  18489. },
  18490. { id: 'sub', min: 2, stackDelta: -1,
  18491. stackFn: function stack_div(stack, index) {
  18492. stack[index - 2] = stack[index - 2] - stack[index - 1];
  18493. }
  18494. },
  18495. { id: 'div', min: 2, stackDelta: -1,
  18496. stackFn: function stack_div(stack, index) {
  18497. stack[index - 2] = stack[index - 2] / stack[index - 1];
  18498. }
  18499. },
  18500. null,
  18501. { id: 'neg', min: 1, stackDelta: 0,
  18502. stackFn: function stack_div(stack, index) {
  18503. stack[index - 1] = -stack[index - 1];
  18504. }
  18505. },
  18506. { id: 'eq', min: 2, stackDelta: -1 },
  18507. null,
  18508. null,
  18509. { id: 'drop', min: 1, stackDelta: -1 },
  18510. null,
  18511. { id: 'put', min: 2, stackDelta: -2 },
  18512. { id: 'get', min: 1, stackDelta: 0 },
  18513. { id: 'ifelse', min: 4, stackDelta: -3 },
  18514. { id: 'random', min: 0, stackDelta: 1 },
  18515. { id: 'mul', min: 2, stackDelta: -1,
  18516. stackFn: function stack_div(stack, index) {
  18517. stack[index - 2] = stack[index - 2] * stack[index - 1];
  18518. }
  18519. },
  18520. null,
  18521. { id: 'sqrt', min: 1, stackDelta: 0 },
  18522. { id: 'dup', min: 1, stackDelta: 1 },
  18523. { id: 'exch', min: 2, stackDelta: 0 },
  18524. { id: 'index', min: 2, stackDelta: 0 },
  18525. { id: 'roll', min: 3, stackDelta: -2 },
  18526. null,
  18527. null,
  18528. null,
  18529. { id: 'hflex', min: 7, resetStack: true },
  18530. { id: 'flex', min: 13, resetStack: true },
  18531. { id: 'hflex1', min: 9, resetStack: true },
  18532. { id: 'flex1', min: 11, resetStack: true }
  18533. ];
  18534. function CFFParser(file, properties) {
  18535. this.bytes = file.getBytes();
  18536. this.properties = properties;
  18537. }
  18538. CFFParser.prototype = {
  18539. parse: function CFFParser_parse() {
  18540. var properties = this.properties;
  18541. var cff = new CFF();
  18542. this.cff = cff;
  18543. // The first five sections must be in order, all the others are reached
  18544. // via offsets contained in one of the below.
  18545. var header = this.parseHeader();
  18546. var nameIndex = this.parseIndex(header.endPos);
  18547. var topDictIndex = this.parseIndex(nameIndex.endPos);
  18548. var stringIndex = this.parseIndex(topDictIndex.endPos);
  18549. var globalSubrIndex = this.parseIndex(stringIndex.endPos);
  18550. var topDictParsed = this.parseDict(topDictIndex.obj.get(0));
  18551. var topDict = this.createDict(CFFTopDict, topDictParsed, cff.strings);
  18552. cff.header = header.obj;
  18553. cff.names = this.parseNameIndex(nameIndex.obj);
  18554. cff.strings = this.parseStringIndex(stringIndex.obj);
  18555. cff.topDict = topDict;
  18556. cff.globalSubrIndex = globalSubrIndex.obj;
  18557. this.parsePrivateDict(cff.topDict);
  18558. cff.isCIDFont = topDict.hasName('ROS');
  18559. var charStringOffset = topDict.getByName('CharStrings');
  18560. var charStringsAndSeacs = this.parseCharStrings(charStringOffset);
  18561. cff.charStrings = charStringsAndSeacs.charStrings;
  18562. cff.seacs = charStringsAndSeacs.seacs;
  18563. cff.widths = charStringsAndSeacs.widths;
  18564. var fontMatrix = topDict.getByName('FontMatrix');
  18565. if (fontMatrix) {
  18566. properties.fontMatrix = fontMatrix;
  18567. }
  18568. var fontBBox = topDict.getByName('FontBBox');
  18569. if (fontBBox) {
  18570. // adjusting ascent/descent
  18571. properties.ascent = fontBBox[3];
  18572. properties.descent = fontBBox[1];
  18573. properties.ascentScaled = true;
  18574. }
  18575. var charset, encoding;
  18576. if (cff.isCIDFont) {
  18577. var fdArrayIndex = this.parseIndex(topDict.getByName('FDArray')).obj;
  18578. for (var i = 0, ii = fdArrayIndex.count; i < ii; ++i) {
  18579. var dictRaw = fdArrayIndex.get(i);
  18580. var fontDict = this.createDict(CFFTopDict, this.parseDict(dictRaw),
  18581. cff.strings);
  18582. this.parsePrivateDict(fontDict);
  18583. cff.fdArray.push(fontDict);
  18584. }
  18585. // cid fonts don't have an encoding
  18586. encoding = null;
  18587. charset = this.parseCharsets(topDict.getByName('charset'),
  18588. cff.charStrings.count, cff.strings, true);
  18589. cff.fdSelect = this.parseFDSelect(topDict.getByName('FDSelect'),
  18590. cff.charStrings.count);
  18591. } else {
  18592. charset = this.parseCharsets(topDict.getByName('charset'),
  18593. cff.charStrings.count, cff.strings, false);
  18594. encoding = this.parseEncoding(topDict.getByName('Encoding'),
  18595. properties,
  18596. cff.strings, charset.charset);
  18597. }
  18598. cff.charset = charset;
  18599. cff.encoding = encoding;
  18600. return cff;
  18601. },
  18602. parseHeader: function CFFParser_parseHeader() {
  18603. var bytes = this.bytes;
  18604. var bytesLength = bytes.length;
  18605. var offset = 0;
  18606. // Prevent an infinite loop, by checking that the offset is within the
  18607. // bounds of the bytes array. Necessary in empty, or invalid, font files.
  18608. while (offset < bytesLength && bytes[offset] !== 1) {
  18609. ++offset;
  18610. }
  18611. if (offset >= bytesLength) {
  18612. error('Invalid CFF header');
  18613. } else if (offset !== 0) {
  18614. info('cff data is shifted');
  18615. bytes = bytes.subarray(offset);
  18616. this.bytes = bytes;
  18617. }
  18618. var major = bytes[0];
  18619. var minor = bytes[1];
  18620. var hdrSize = bytes[2];
  18621. var offSize = bytes[3];
  18622. var header = new CFFHeader(major, minor, hdrSize, offSize);
  18623. return { obj: header, endPos: hdrSize };
  18624. },
  18625. parseDict: function CFFParser_parseDict(dict) {
  18626. var pos = 0;
  18627. function parseOperand() {
  18628. var value = dict[pos++];
  18629. if (value === 30) {
  18630. return parseFloatOperand(pos);
  18631. } else if (value === 28) {
  18632. value = dict[pos++];
  18633. value = ((value << 24) | (dict[pos++] << 16)) >> 16;
  18634. return value;
  18635. } else if (value === 29) {
  18636. value = dict[pos++];
  18637. value = (value << 8) | dict[pos++];
  18638. value = (value << 8) | dict[pos++];
  18639. value = (value << 8) | dict[pos++];
  18640. return value;
  18641. } else if (value >= 32 && value <= 246) {
  18642. return value - 139;
  18643. } else if (value >= 247 && value <= 250) {
  18644. return ((value - 247) * 256) + dict[pos++] + 108;
  18645. } else if (value >= 251 && value <= 254) {
  18646. return -((value - 251) * 256) - dict[pos++] - 108;
  18647. } else {
  18648. error('255 is not a valid DICT command');
  18649. }
  18650. return -1;
  18651. }
  18652. function parseFloatOperand() {
  18653. var str = '';
  18654. var eof = 15;
  18655. var lookup = ['0', '1', '2', '3', '4', '5', '6', '7', '8',
  18656. '9', '.', 'E', 'E-', null, '-'];
  18657. var length = dict.length;
  18658. while (pos < length) {
  18659. var b = dict[pos++];
  18660. var b1 = b >> 4;
  18661. var b2 = b & 15;
  18662. if (b1 === eof) {
  18663. break;
  18664. }
  18665. str += lookup[b1];
  18666. if (b2 === eof) {
  18667. break;
  18668. }
  18669. str += lookup[b2];
  18670. }
  18671. return parseFloat(str);
  18672. }
  18673. var operands = [];
  18674. var entries = [];
  18675. pos = 0;
  18676. var end = dict.length;
  18677. while (pos < end) {
  18678. var b = dict[pos];
  18679. if (b <= 21) {
  18680. if (b === 12) {
  18681. b = (b << 8) | dict[++pos];
  18682. }
  18683. entries.push([b, operands]);
  18684. operands = [];
  18685. ++pos;
  18686. } else {
  18687. operands.push(parseOperand());
  18688. }
  18689. }
  18690. return entries;
  18691. },
  18692. parseIndex: function CFFParser_parseIndex(pos) {
  18693. var cffIndex = new CFFIndex();
  18694. var bytes = this.bytes;
  18695. var count = (bytes[pos++] << 8) | bytes[pos++];
  18696. var offsets = [];
  18697. var end = pos;
  18698. var i, ii;
  18699. if (count !== 0) {
  18700. var offsetSize = bytes[pos++];
  18701. // add 1 for offset to determine size of last object
  18702. var startPos = pos + ((count + 1) * offsetSize) - 1;
  18703. for (i = 0, ii = count + 1; i < ii; ++i) {
  18704. var offset = 0;
  18705. for (var j = 0; j < offsetSize; ++j) {
  18706. offset <<= 8;
  18707. offset += bytes[pos++];
  18708. }
  18709. offsets.push(startPos + offset);
  18710. }
  18711. end = offsets[count];
  18712. }
  18713. for (i = 0, ii = offsets.length - 1; i < ii; ++i) {
  18714. var offsetStart = offsets[i];
  18715. var offsetEnd = offsets[i + 1];
  18716. cffIndex.add(bytes.subarray(offsetStart, offsetEnd));
  18717. }
  18718. return {obj: cffIndex, endPos: end};
  18719. },
  18720. parseNameIndex: function CFFParser_parseNameIndex(index) {
  18721. var names = [];
  18722. for (var i = 0, ii = index.count; i < ii; ++i) {
  18723. var name = index.get(i);
  18724. // OTS doesn't allow names to be over 127 characters.
  18725. var length = Math.min(name.length, 127);
  18726. var data = [];
  18727. // OTS also only permits certain characters in the name.
  18728. for (var j = 0; j < length; ++j) {
  18729. var c = name[j];
  18730. if (j === 0 && c === 0) {
  18731. data[j] = c;
  18732. continue;
  18733. }
  18734. if ((c < 33 || c > 126) || c === 91 /* [ */ || c === 93 /* ] */ ||
  18735. c === 40 /* ( */ || c === 41 /* ) */ || c === 123 /* { */ ||
  18736. c === 125 /* } */ || c === 60 /* < */ || c === 62 /* > */ ||
  18737. c === 47 /* / */ || c === 37 /* % */ || c === 35 /* # */) {
  18738. data[j] = 95;
  18739. continue;
  18740. }
  18741. data[j] = c;
  18742. }
  18743. names.push(bytesToString(data));
  18744. }
  18745. return names;
  18746. },
  18747. parseStringIndex: function CFFParser_parseStringIndex(index) {
  18748. var strings = new CFFStrings();
  18749. for (var i = 0, ii = index.count; i < ii; ++i) {
  18750. var data = index.get(i);
  18751. strings.add(bytesToString(data));
  18752. }
  18753. return strings;
  18754. },
  18755. createDict: function CFFParser_createDict(Type, dict, strings) {
  18756. var cffDict = new Type(strings);
  18757. for (var i = 0, ii = dict.length; i < ii; ++i) {
  18758. var pair = dict[i];
  18759. var key = pair[0];
  18760. var value = pair[1];
  18761. cffDict.setByKey(key, value);
  18762. }
  18763. return cffDict;
  18764. },
  18765. parseCharStrings: function CFFParser_parseCharStrings(charStringOffset) {
  18766. var charStrings = this.parseIndex(charStringOffset).obj;
  18767. var seacs = [];
  18768. var widths = [];
  18769. var count = charStrings.count;
  18770. for (var i = 0; i < count; i++) {
  18771. var charstring = charStrings.get(i);
  18772. var stackSize = 0;
  18773. var stack = [];
  18774. var undefStack = true;
  18775. var hints = 0;
  18776. var valid = true;
  18777. var data = charstring;
  18778. var length = data.length;
  18779. var firstStackClearing = true;
  18780. for (var j = 0; j < length;) {
  18781. var value = data[j++];
  18782. var validationCommand = null;
  18783. if (value === 12) {
  18784. var q = data[j++];
  18785. if (q === 0) {
  18786. // The CFF specification state that the 'dotsection' command
  18787. // (12, 0) is deprecated and treated as a no-op, but all Type2
  18788. // charstrings processors should support them. Unfortunately
  18789. // the font sanitizer don't. As a workaround the sequence (12, 0)
  18790. // is replaced by a useless (0, hmoveto).
  18791. data[j - 2] = 139;
  18792. data[j - 1] = 22;
  18793. stackSize = 0;
  18794. } else {
  18795. validationCommand = CharstringValidationData12[q];
  18796. }
  18797. } else if (value === 28) { // number (16 bit)
  18798. stack[stackSize] = ((data[j] << 24) | (data[j + 1] << 16)) >> 16;
  18799. j += 2;
  18800. stackSize++;
  18801. } else if (value === 14) {
  18802. if (stackSize >= 4) {
  18803. stackSize -= 4;
  18804. if (SEAC_ANALYSIS_ENABLED) {
  18805. seacs[i] = stack.slice(stackSize, stackSize + 4);
  18806. valid = false;
  18807. }
  18808. }
  18809. validationCommand = CharstringValidationData[value];
  18810. } else if (value >= 32 && value <= 246) { // number
  18811. stack[stackSize] = value - 139;
  18812. stackSize++;
  18813. } else if (value >= 247 && value <= 254) { // number (+1 bytes)
  18814. stack[stackSize] = (value < 251 ?
  18815. ((value - 247) << 8) + data[j] + 108 :
  18816. -((value - 251) << 8) - data[j] - 108);
  18817. j++;
  18818. stackSize++;
  18819. } else if (value === 255) { // number (32 bit)
  18820. stack[stackSize] = ((data[j] << 24) | (data[j + 1] << 16) |
  18821. (data[j + 2] << 8) | data[j + 3]) / 65536;
  18822. j += 4;
  18823. stackSize++;
  18824. } else if (value === 19 || value === 20) {
  18825. hints += stackSize >> 1;
  18826. j += (hints + 7) >> 3; // skipping right amount of hints flag data
  18827. stackSize %= 2;
  18828. validationCommand = CharstringValidationData[value];
  18829. } else {
  18830. validationCommand = CharstringValidationData[value];
  18831. }
  18832. if (validationCommand) {
  18833. if (validationCommand.stem) {
  18834. hints += stackSize >> 1;
  18835. }
  18836. if ('min' in validationCommand) {
  18837. if (!undefStack && stackSize < validationCommand.min) {
  18838. warn('Not enough parameters for ' + validationCommand.id +
  18839. '; actual: ' + stackSize +
  18840. ', expected: ' + validationCommand.min);
  18841. valid = false;
  18842. break;
  18843. }
  18844. }
  18845. if (firstStackClearing && validationCommand.stackClearing) {
  18846. firstStackClearing = false;
  18847. // the optional character width can be found before the first
  18848. // stack-clearing command arguments
  18849. stackSize -= validationCommand.min;
  18850. if (stackSize >= 2 && validationCommand.stem) {
  18851. // there are even amount of arguments for stem commands
  18852. stackSize %= 2;
  18853. } else if (stackSize > 1) {
  18854. warn('Found too many parameters for stack-clearing command');
  18855. }
  18856. if (stackSize > 0 && stack[stackSize - 1] >= 0) {
  18857. widths[i] = stack[stackSize - 1];
  18858. }
  18859. }
  18860. if ('stackDelta' in validationCommand) {
  18861. if ('stackFn' in validationCommand) {
  18862. validationCommand.stackFn(stack, stackSize);
  18863. }
  18864. stackSize += validationCommand.stackDelta;
  18865. } else if (validationCommand.stackClearing) {
  18866. stackSize = 0;
  18867. } else if (validationCommand.resetStack) {
  18868. stackSize = 0;
  18869. undefStack = false;
  18870. } else if (validationCommand.undefStack) {
  18871. stackSize = 0;
  18872. undefStack = true;
  18873. firstStackClearing = false;
  18874. }
  18875. }
  18876. }
  18877. if (!valid) {
  18878. // resetting invalid charstring to single 'endchar'
  18879. charStrings.set(i, new Uint8Array([14]));
  18880. }
  18881. }
  18882. return { charStrings: charStrings, seacs: seacs, widths: widths };
  18883. },
  18884. emptyPrivateDictionary:
  18885. function CFFParser_emptyPrivateDictionary(parentDict) {
  18886. var privateDict = this.createDict(CFFPrivateDict, [],
  18887. parentDict.strings);
  18888. parentDict.setByKey(18, [0, 0]);
  18889. parentDict.privateDict = privateDict;
  18890. },
  18891. parsePrivateDict: function CFFParser_parsePrivateDict(parentDict) {
  18892. // no private dict, do nothing
  18893. if (!parentDict.hasName('Private')) {
  18894. this.emptyPrivateDictionary(parentDict);
  18895. return;
  18896. }
  18897. var privateOffset = parentDict.getByName('Private');
  18898. // make sure the params are formatted correctly
  18899. if (!isArray(privateOffset) || privateOffset.length !== 2) {
  18900. parentDict.removeByName('Private');
  18901. return;
  18902. }
  18903. var size = privateOffset[0];
  18904. var offset = privateOffset[1];
  18905. // remove empty dicts or ones that refer to invalid location
  18906. if (size === 0 || offset >= this.bytes.length) {
  18907. this.emptyPrivateDictionary(parentDict);
  18908. return;
  18909. }
  18910. var privateDictEnd = offset + size;
  18911. var dictData = this.bytes.subarray(offset, privateDictEnd);
  18912. var dict = this.parseDict(dictData);
  18913. var privateDict = this.createDict(CFFPrivateDict, dict,
  18914. parentDict.strings);
  18915. parentDict.privateDict = privateDict;
  18916. // Parse the Subrs index also since it's relative to the private dict.
  18917. if (!privateDict.getByName('Subrs')) {
  18918. return;
  18919. }
  18920. var subrsOffset = privateDict.getByName('Subrs');
  18921. var relativeOffset = offset + subrsOffset;
  18922. // Validate the offset.
  18923. if (subrsOffset === 0 || relativeOffset >= this.bytes.length) {
  18924. this.emptyPrivateDictionary(parentDict);
  18925. return;
  18926. }
  18927. var subrsIndex = this.parseIndex(relativeOffset);
  18928. privateDict.subrsIndex = subrsIndex.obj;
  18929. },
  18930. parseCharsets: function CFFParser_parseCharsets(pos, length, strings, cid) {
  18931. if (pos === 0) {
  18932. return new CFFCharset(true, CFFCharsetPredefinedTypes.ISO_ADOBE,
  18933. ISOAdobeCharset);
  18934. } else if (pos === 1) {
  18935. return new CFFCharset(true, CFFCharsetPredefinedTypes.EXPERT,
  18936. ExpertCharset);
  18937. } else if (pos === 2) {
  18938. return new CFFCharset(true, CFFCharsetPredefinedTypes.EXPERT_SUBSET,
  18939. ExpertSubsetCharset);
  18940. }
  18941. var bytes = this.bytes;
  18942. var start = pos;
  18943. var format = bytes[pos++];
  18944. var charset = ['.notdef'];
  18945. var id, count, i;
  18946. // subtract 1 for the .notdef glyph
  18947. length -= 1;
  18948. switch (format) {
  18949. case 0:
  18950. for (i = 0; i < length; i++) {
  18951. id = (bytes[pos++] << 8) | bytes[pos++];
  18952. charset.push(cid ? id : strings.get(id));
  18953. }
  18954. break;
  18955. case 1:
  18956. while (charset.length <= length) {
  18957. id = (bytes[pos++] << 8) | bytes[pos++];
  18958. count = bytes[pos++];
  18959. for (i = 0; i <= count; i++) {
  18960. charset.push(cid ? id++ : strings.get(id++));
  18961. }
  18962. }
  18963. break;
  18964. case 2:
  18965. while (charset.length <= length) {
  18966. id = (bytes[pos++] << 8) | bytes[pos++];
  18967. count = (bytes[pos++] << 8) | bytes[pos++];
  18968. for (i = 0; i <= count; i++) {
  18969. charset.push(cid ? id++ : strings.get(id++));
  18970. }
  18971. }
  18972. break;
  18973. default:
  18974. error('Unknown charset format');
  18975. }
  18976. // Raw won't be needed if we actually compile the charset.
  18977. var end = pos;
  18978. var raw = bytes.subarray(start, end);
  18979. return new CFFCharset(false, format, charset, raw);
  18980. },
  18981. parseEncoding: function CFFParser_parseEncoding(pos,
  18982. properties,
  18983. strings,
  18984. charset) {
  18985. var encoding = {};
  18986. var bytes = this.bytes;
  18987. var predefined = false;
  18988. var hasSupplement = false;
  18989. var format, i, ii;
  18990. var raw = null;
  18991. function readSupplement() {
  18992. var supplementsCount = bytes[pos++];
  18993. for (i = 0; i < supplementsCount; i++) {
  18994. var code = bytes[pos++];
  18995. var sid = (bytes[pos++] << 8) + (bytes[pos++] & 0xff);
  18996. encoding[code] = charset.indexOf(strings.get(sid));
  18997. }
  18998. }
  18999. if (pos === 0 || pos === 1) {
  19000. predefined = true;
  19001. format = pos;
  19002. var baseEncoding = pos ? Encodings.ExpertEncoding :
  19003. Encodings.StandardEncoding;
  19004. for (i = 0, ii = charset.length; i < ii; i++) {
  19005. var index = baseEncoding.indexOf(charset[i]);
  19006. if (index !== -1) {
  19007. encoding[index] = i;
  19008. }
  19009. }
  19010. } else {
  19011. var dataStart = pos;
  19012. format = bytes[pos++];
  19013. switch (format & 0x7f) {
  19014. case 0:
  19015. var glyphsCount = bytes[pos++];
  19016. for (i = 1; i <= glyphsCount; i++) {
  19017. encoding[bytes[pos++]] = i;
  19018. }
  19019. break;
  19020. case 1:
  19021. var rangesCount = bytes[pos++];
  19022. var gid = 1;
  19023. for (i = 0; i < rangesCount; i++) {
  19024. var start = bytes[pos++];
  19025. var left = bytes[pos++];
  19026. for (var j = start; j <= start + left; j++) {
  19027. encoding[j] = gid++;
  19028. }
  19029. }
  19030. break;
  19031. default:
  19032. error('Unknow encoding format: ' + format + ' in CFF');
  19033. break;
  19034. }
  19035. var dataEnd = pos;
  19036. if (format & 0x80) {
  19037. // The font sanitizer does not support CFF encoding with a
  19038. // supplement, since the encoding is not really used to map
  19039. // between gid to glyph, let's overwrite what is declared in
  19040. // the top dictionary to let the sanitizer think the font use
  19041. // StandardEncoding, that's a lie but that's ok.
  19042. bytes[dataStart] &= 0x7f;
  19043. readSupplement();
  19044. hasSupplement = true;
  19045. }
  19046. raw = bytes.subarray(dataStart, dataEnd);
  19047. }
  19048. format = format & 0x7f;
  19049. return new CFFEncoding(predefined, format, encoding, raw);
  19050. },
  19051. parseFDSelect: function CFFParser_parseFDSelect(pos, length) {
  19052. var start = pos;
  19053. var bytes = this.bytes;
  19054. var format = bytes[pos++];
  19055. var fdSelect = [];
  19056. var i;
  19057. switch (format) {
  19058. case 0:
  19059. for (i = 0; i < length; ++i) {
  19060. var id = bytes[pos++];
  19061. fdSelect.push(id);
  19062. }
  19063. break;
  19064. case 3:
  19065. var rangesCount = (bytes[pos++] << 8) | bytes[pos++];
  19066. for (i = 0; i < rangesCount; ++i) {
  19067. var first = (bytes[pos++] << 8) | bytes[pos++];
  19068. var fdIndex = bytes[pos++];
  19069. var next = (bytes[pos] << 8) | bytes[pos + 1];
  19070. for (var j = first; j < next; ++j) {
  19071. fdSelect.push(fdIndex);
  19072. }
  19073. }
  19074. // Advance past the sentinel(next).
  19075. pos += 2;
  19076. break;
  19077. default:
  19078. error('Unknown fdselect format ' + format);
  19079. break;
  19080. }
  19081. var end = pos;
  19082. return new CFFFDSelect(fdSelect, bytes.subarray(start, end));
  19083. }
  19084. };
  19085. return CFFParser;
  19086. })();
  19087. // Compact Font Format
  19088. var CFF = (function CFFClosure() {
  19089. function CFF() {
  19090. this.header = null;
  19091. this.names = [];
  19092. this.topDict = null;
  19093. this.strings = new CFFStrings();
  19094. this.globalSubrIndex = null;
  19095. // The following could really be per font, but since we only have one font
  19096. // store them here.
  19097. this.encoding = null;
  19098. this.charset = null;
  19099. this.charStrings = null;
  19100. this.fdArray = [];
  19101. this.fdSelect = null;
  19102. this.isCIDFont = false;
  19103. }
  19104. return CFF;
  19105. })();
  19106. var CFFHeader = (function CFFHeaderClosure() {
  19107. function CFFHeader(major, minor, hdrSize, offSize) {
  19108. this.major = major;
  19109. this.minor = minor;
  19110. this.hdrSize = hdrSize;
  19111. this.offSize = offSize;
  19112. }
  19113. return CFFHeader;
  19114. })();
  19115. var CFFStrings = (function CFFStringsClosure() {
  19116. function CFFStrings() {
  19117. this.strings = [];
  19118. }
  19119. CFFStrings.prototype = {
  19120. get: function CFFStrings_get(index) {
  19121. if (index >= 0 && index <= 390) {
  19122. return CFFStandardStrings[index];
  19123. }
  19124. if (index - 391 <= this.strings.length) {
  19125. return this.strings[index - 391];
  19126. }
  19127. return CFFStandardStrings[0];
  19128. },
  19129. add: function CFFStrings_add(value) {
  19130. this.strings.push(value);
  19131. },
  19132. get count() {
  19133. return this.strings.length;
  19134. }
  19135. };
  19136. return CFFStrings;
  19137. })();
  19138. var CFFIndex = (function CFFIndexClosure() {
  19139. function CFFIndex() {
  19140. this.objects = [];
  19141. this.length = 0;
  19142. }
  19143. CFFIndex.prototype = {
  19144. add: function CFFIndex_add(data) {
  19145. this.length += data.length;
  19146. this.objects.push(data);
  19147. },
  19148. set: function CFFIndex_set(index, data) {
  19149. this.length += data.length - this.objects[index].length;
  19150. this.objects[index] = data;
  19151. },
  19152. get: function CFFIndex_get(index) {
  19153. return this.objects[index];
  19154. },
  19155. get count() {
  19156. return this.objects.length;
  19157. }
  19158. };
  19159. return CFFIndex;
  19160. })();
  19161. var CFFDict = (function CFFDictClosure() {
  19162. function CFFDict(tables, strings) {
  19163. this.keyToNameMap = tables.keyToNameMap;
  19164. this.nameToKeyMap = tables.nameToKeyMap;
  19165. this.defaults = tables.defaults;
  19166. this.types = tables.types;
  19167. this.opcodes = tables.opcodes;
  19168. this.order = tables.order;
  19169. this.strings = strings;
  19170. this.values = {};
  19171. }
  19172. CFFDict.prototype = {
  19173. // value should always be an array
  19174. setByKey: function CFFDict_setByKey(key, value) {
  19175. if (!(key in this.keyToNameMap)) {
  19176. return false;
  19177. }
  19178. // ignore empty values
  19179. if (value.length === 0) {
  19180. return true;
  19181. }
  19182. var type = this.types[key];
  19183. // remove the array wrapping these types of values
  19184. if (type === 'num' || type === 'sid' || type === 'offset') {
  19185. value = value[0];
  19186. }
  19187. this.values[key] = value;
  19188. return true;
  19189. },
  19190. setByName: function CFFDict_setByName(name, value) {
  19191. if (!(name in this.nameToKeyMap)) {
  19192. error('Invalid dictionary name "' + name + '"');
  19193. }
  19194. this.values[this.nameToKeyMap[name]] = value;
  19195. },
  19196. hasName: function CFFDict_hasName(name) {
  19197. return this.nameToKeyMap[name] in this.values;
  19198. },
  19199. getByName: function CFFDict_getByName(name) {
  19200. if (!(name in this.nameToKeyMap)) {
  19201. error('Invalid dictionary name "' + name + '"');
  19202. }
  19203. var key = this.nameToKeyMap[name];
  19204. if (!(key in this.values)) {
  19205. return this.defaults[key];
  19206. }
  19207. return this.values[key];
  19208. },
  19209. removeByName: function CFFDict_removeByName(name) {
  19210. delete this.values[this.nameToKeyMap[name]];
  19211. }
  19212. };
  19213. CFFDict.createTables = function CFFDict_createTables(layout) {
  19214. var tables = {
  19215. keyToNameMap: {},
  19216. nameToKeyMap: {},
  19217. defaults: {},
  19218. types: {},
  19219. opcodes: {},
  19220. order: []
  19221. };
  19222. for (var i = 0, ii = layout.length; i < ii; ++i) {
  19223. var entry = layout[i];
  19224. var key = isArray(entry[0]) ? (entry[0][0] << 8) + entry[0][1] : entry[0];
  19225. tables.keyToNameMap[key] = entry[1];
  19226. tables.nameToKeyMap[entry[1]] = key;
  19227. tables.types[key] = entry[2];
  19228. tables.defaults[key] = entry[3];
  19229. tables.opcodes[key] = isArray(entry[0]) ? entry[0] : [entry[0]];
  19230. tables.order.push(key);
  19231. }
  19232. return tables;
  19233. };
  19234. return CFFDict;
  19235. })();
  19236. var CFFTopDict = (function CFFTopDictClosure() {
  19237. var layout = [
  19238. [[12, 30], 'ROS', ['sid', 'sid', 'num'], null],
  19239. [[12, 20], 'SyntheticBase', 'num', null],
  19240. [0, 'version', 'sid', null],
  19241. [1, 'Notice', 'sid', null],
  19242. [[12, 0], 'Copyright', 'sid', null],
  19243. [2, 'FullName', 'sid', null],
  19244. [3, 'FamilyName', 'sid', null],
  19245. [4, 'Weight', 'sid', null],
  19246. [[12, 1], 'isFixedPitch', 'num', 0],
  19247. [[12, 2], 'ItalicAngle', 'num', 0],
  19248. [[12, 3], 'UnderlinePosition', 'num', -100],
  19249. [[12, 4], 'UnderlineThickness', 'num', 50],
  19250. [[12, 5], 'PaintType', 'num', 0],
  19251. [[12, 6], 'CharstringType', 'num', 2],
  19252. [[12, 7], 'FontMatrix', ['num', 'num', 'num', 'num', 'num', 'num'],
  19253. [0.001, 0, 0, 0.001, 0, 0]],
  19254. [13, 'UniqueID', 'num', null],
  19255. [5, 'FontBBox', ['num', 'num', 'num', 'num'], [0, 0, 0, 0]],
  19256. [[12, 8], 'StrokeWidth', 'num', 0],
  19257. [14, 'XUID', 'array', null],
  19258. [15, 'charset', 'offset', 0],
  19259. [16, 'Encoding', 'offset', 0],
  19260. [17, 'CharStrings', 'offset', 0],
  19261. [18, 'Private', ['offset', 'offset'], null],
  19262. [[12, 21], 'PostScript', 'sid', null],
  19263. [[12, 22], 'BaseFontName', 'sid', null],
  19264. [[12, 23], 'BaseFontBlend', 'delta', null],
  19265. [[12, 31], 'CIDFontVersion', 'num', 0],
  19266. [[12, 32], 'CIDFontRevision', 'num', 0],
  19267. [[12, 33], 'CIDFontType', 'num', 0],
  19268. [[12, 34], 'CIDCount', 'num', 8720],
  19269. [[12, 35], 'UIDBase', 'num', null],
  19270. // XXX: CID Fonts on DirectWrite 6.1 only seem to work if FDSelect comes
  19271. // before FDArray.
  19272. [[12, 37], 'FDSelect', 'offset', null],
  19273. [[12, 36], 'FDArray', 'offset', null],
  19274. [[12, 38], 'FontName', 'sid', null]
  19275. ];
  19276. var tables = null;
  19277. function CFFTopDict(strings) {
  19278. if (tables === null) {
  19279. tables = CFFDict.createTables(layout);
  19280. }
  19281. CFFDict.call(this, tables, strings);
  19282. this.privateDict = null;
  19283. }
  19284. CFFTopDict.prototype = Object.create(CFFDict.prototype);
  19285. return CFFTopDict;
  19286. })();
  19287. var CFFPrivateDict = (function CFFPrivateDictClosure() {
  19288. var layout = [
  19289. [6, 'BlueValues', 'delta', null],
  19290. [7, 'OtherBlues', 'delta', null],
  19291. [8, 'FamilyBlues', 'delta', null],
  19292. [9, 'FamilyOtherBlues', 'delta', null],
  19293. [[12, 9], 'BlueScale', 'num', 0.039625],
  19294. [[12, 10], 'BlueShift', 'num', 7],
  19295. [[12, 11], 'BlueFuzz', 'num', 1],
  19296. [10, 'StdHW', 'num', null],
  19297. [11, 'StdVW', 'num', null],
  19298. [[12, 12], 'StemSnapH', 'delta', null],
  19299. [[12, 13], 'StemSnapV', 'delta', null],
  19300. [[12, 14], 'ForceBold', 'num', 0],
  19301. [[12, 17], 'LanguageGroup', 'num', 0],
  19302. [[12, 18], 'ExpansionFactor', 'num', 0.06],
  19303. [[12, 19], 'initialRandomSeed', 'num', 0],
  19304. [20, 'defaultWidthX', 'num', 0],
  19305. [21, 'nominalWidthX', 'num', 0],
  19306. [19, 'Subrs', 'offset', null]
  19307. ];
  19308. var tables = null;
  19309. function CFFPrivateDict(strings) {
  19310. if (tables === null) {
  19311. tables = CFFDict.createTables(layout);
  19312. }
  19313. CFFDict.call(this, tables, strings);
  19314. this.subrsIndex = null;
  19315. }
  19316. CFFPrivateDict.prototype = Object.create(CFFDict.prototype);
  19317. return CFFPrivateDict;
  19318. })();
  19319. var CFFCharsetPredefinedTypes = {
  19320. ISO_ADOBE: 0,
  19321. EXPERT: 1,
  19322. EXPERT_SUBSET: 2
  19323. };
  19324. var CFFCharset = (function CFFCharsetClosure() {
  19325. function CFFCharset(predefined, format, charset, raw) {
  19326. this.predefined = predefined;
  19327. this.format = format;
  19328. this.charset = charset;
  19329. this.raw = raw;
  19330. }
  19331. return CFFCharset;
  19332. })();
  19333. var CFFEncoding = (function CFFEncodingClosure() {
  19334. function CFFEncoding(predefined, format, encoding, raw) {
  19335. this.predefined = predefined;
  19336. this.format = format;
  19337. this.encoding = encoding;
  19338. this.raw = raw;
  19339. }
  19340. return CFFEncoding;
  19341. })();
  19342. var CFFFDSelect = (function CFFFDSelectClosure() {
  19343. function CFFFDSelect(fdSelect, raw) {
  19344. this.fdSelect = fdSelect;
  19345. this.raw = raw;
  19346. }
  19347. return CFFFDSelect;
  19348. })();
  19349. // Helper class to keep track of where an offset is within the data and helps
  19350. // filling in that offset once it's known.
  19351. var CFFOffsetTracker = (function CFFOffsetTrackerClosure() {
  19352. function CFFOffsetTracker() {
  19353. this.offsets = {};
  19354. }
  19355. CFFOffsetTracker.prototype = {
  19356. isTracking: function CFFOffsetTracker_isTracking(key) {
  19357. return key in this.offsets;
  19358. },
  19359. track: function CFFOffsetTracker_track(key, location) {
  19360. if (key in this.offsets) {
  19361. error('Already tracking location of ' + key);
  19362. }
  19363. this.offsets[key] = location;
  19364. },
  19365. offset: function CFFOffsetTracker_offset(value) {
  19366. for (var key in this.offsets) {
  19367. this.offsets[key] += value;
  19368. }
  19369. },
  19370. setEntryLocation: function CFFOffsetTracker_setEntryLocation(key,
  19371. values,
  19372. output) {
  19373. if (!(key in this.offsets)) {
  19374. error('Not tracking location of ' + key);
  19375. }
  19376. var data = output.data;
  19377. var dataOffset = this.offsets[key];
  19378. var size = 5;
  19379. for (var i = 0, ii = values.length; i < ii; ++i) {
  19380. var offset0 = i * size + dataOffset;
  19381. var offset1 = offset0 + 1;
  19382. var offset2 = offset0 + 2;
  19383. var offset3 = offset0 + 3;
  19384. var offset4 = offset0 + 4;
  19385. // It's easy to screw up offsets so perform this sanity check.
  19386. if (data[offset0] !== 0x1d || data[offset1] !== 0 ||
  19387. data[offset2] !== 0 || data[offset3] !== 0 || data[offset4] !== 0) {
  19388. error('writing to an offset that is not empty');
  19389. }
  19390. var value = values[i];
  19391. data[offset0] = 0x1d;
  19392. data[offset1] = (value >> 24) & 0xFF;
  19393. data[offset2] = (value >> 16) & 0xFF;
  19394. data[offset3] = (value >> 8) & 0xFF;
  19395. data[offset4] = value & 0xFF;
  19396. }
  19397. }
  19398. };
  19399. return CFFOffsetTracker;
  19400. })();
  19401. // Takes a CFF and converts it to the binary representation.
  19402. var CFFCompiler = (function CFFCompilerClosure() {
  19403. function CFFCompiler(cff) {
  19404. this.cff = cff;
  19405. }
  19406. CFFCompiler.prototype = {
  19407. compile: function CFFCompiler_compile() {
  19408. var cff = this.cff;
  19409. var output = {
  19410. data: [],
  19411. length: 0,
  19412. add: function CFFCompiler_add(data) {
  19413. this.data = this.data.concat(data);
  19414. this.length = this.data.length;
  19415. }
  19416. };
  19417. // Compile the five entries that must be in order.
  19418. var header = this.compileHeader(cff.header);
  19419. output.add(header);
  19420. var nameIndex = this.compileNameIndex(cff.names);
  19421. output.add(nameIndex);
  19422. if (cff.isCIDFont) {
  19423. // The spec is unclear on how font matrices should relate to each other
  19424. // when there is one in the main top dict and the sub top dicts.
  19425. // Windows handles this differently than linux and osx so we have to
  19426. // normalize to work on all.
  19427. // Rules based off of some mailing list discussions:
  19428. // - If main font has a matrix and subfont doesn't, use the main matrix.
  19429. // - If no main font matrix and there is a subfont matrix, use the
  19430. // subfont matrix.
  19431. // - If both have matrices, concat together.
  19432. // - If neither have matrices, use default.
  19433. // To make this work on all platforms we move the top matrix into each
  19434. // sub top dict and concat if necessary.
  19435. if (cff.topDict.hasName('FontMatrix')) {
  19436. var base = cff.topDict.getByName('FontMatrix');
  19437. cff.topDict.removeByName('FontMatrix');
  19438. for (var i = 0, ii = cff.fdArray.length; i < ii; i++) {
  19439. var subDict = cff.fdArray[i];
  19440. var matrix = base.slice(0);
  19441. if (subDict.hasName('FontMatrix')) {
  19442. matrix = Util.transform(matrix, subDict.getByName('FontMatrix'));
  19443. }
  19444. subDict.setByName('FontMatrix', matrix);
  19445. }
  19446. }
  19447. }
  19448. var compiled = this.compileTopDicts([cff.topDict],
  19449. output.length,
  19450. cff.isCIDFont);
  19451. output.add(compiled.output);
  19452. var topDictTracker = compiled.trackers[0];
  19453. var stringIndex = this.compileStringIndex(cff.strings.strings);
  19454. output.add(stringIndex);
  19455. var globalSubrIndex = this.compileIndex(cff.globalSubrIndex);
  19456. output.add(globalSubrIndex);
  19457. // Now start on the other entries that have no specfic order.
  19458. if (cff.encoding && cff.topDict.hasName('Encoding')) {
  19459. if (cff.encoding.predefined) {
  19460. topDictTracker.setEntryLocation('Encoding', [cff.encoding.format],
  19461. output);
  19462. } else {
  19463. var encoding = this.compileEncoding(cff.encoding);
  19464. topDictTracker.setEntryLocation('Encoding', [output.length], output);
  19465. output.add(encoding);
  19466. }
  19467. }
  19468. if (cff.charset && cff.topDict.hasName('charset')) {
  19469. if (cff.charset.predefined) {
  19470. topDictTracker.setEntryLocation('charset', [cff.charset.format],
  19471. output);
  19472. } else {
  19473. var charset = this.compileCharset(cff.charset);
  19474. topDictTracker.setEntryLocation('charset', [output.length], output);
  19475. output.add(charset);
  19476. }
  19477. }
  19478. var charStrings = this.compileCharStrings(cff.charStrings);
  19479. topDictTracker.setEntryLocation('CharStrings', [output.length], output);
  19480. output.add(charStrings);
  19481. if (cff.isCIDFont) {
  19482. // For some reason FDSelect must be in front of FDArray on windows. OSX
  19483. // and linux don't seem to care.
  19484. topDictTracker.setEntryLocation('FDSelect', [output.length], output);
  19485. var fdSelect = this.compileFDSelect(cff.fdSelect.raw);
  19486. output.add(fdSelect);
  19487. // It is unclear if the sub font dictionary can have CID related
  19488. // dictionary keys, but the sanitizer doesn't like them so remove them.
  19489. compiled = this.compileTopDicts(cff.fdArray, output.length, true);
  19490. topDictTracker.setEntryLocation('FDArray', [output.length], output);
  19491. output.add(compiled.output);
  19492. var fontDictTrackers = compiled.trackers;
  19493. this.compilePrivateDicts(cff.fdArray, fontDictTrackers, output);
  19494. }
  19495. this.compilePrivateDicts([cff.topDict], [topDictTracker], output);
  19496. // If the font data ends with INDEX whose object data is zero-length,
  19497. // the sanitizer will bail out. Add a dummy byte to avoid that.
  19498. output.add([0]);
  19499. return output.data;
  19500. },
  19501. encodeNumber: function CFFCompiler_encodeNumber(value) {
  19502. if (parseFloat(value) === parseInt(value, 10) && !isNaN(value)) { // isInt
  19503. return this.encodeInteger(value);
  19504. } else {
  19505. return this.encodeFloat(value);
  19506. }
  19507. },
  19508. encodeFloat: function CFFCompiler_encodeFloat(num) {
  19509. var value = num.toString();
  19510. // rounding inaccurate doubles
  19511. var m = /\.(\d*?)(?:9{5,20}|0{5,20})\d{0,2}(?:e(.+)|$)/.exec(value);
  19512. if (m) {
  19513. var epsilon = parseFloat('1e' + ((m[2] ? +m[2] : 0) + m[1].length));
  19514. value = (Math.round(num * epsilon) / epsilon).toString();
  19515. }
  19516. var nibbles = '';
  19517. var i, ii;
  19518. for (i = 0, ii = value.length; i < ii; ++i) {
  19519. var a = value[i];
  19520. if (a === 'e') {
  19521. nibbles += value[++i] === '-' ? 'c' : 'b';
  19522. } else if (a === '.') {
  19523. nibbles += 'a';
  19524. } else if (a === '-') {
  19525. nibbles += 'e';
  19526. } else {
  19527. nibbles += a;
  19528. }
  19529. }
  19530. nibbles += (nibbles.length & 1) ? 'f' : 'ff';
  19531. var out = [30];
  19532. for (i = 0, ii = nibbles.length; i < ii; i += 2) {
  19533. out.push(parseInt(nibbles.substr(i, 2), 16));
  19534. }
  19535. return out;
  19536. },
  19537. encodeInteger: function CFFCompiler_encodeInteger(value) {
  19538. var code;
  19539. if (value >= -107 && value <= 107) {
  19540. code = [value + 139];
  19541. } else if (value >= 108 && value <= 1131) {
  19542. value = [value - 108];
  19543. code = [(value >> 8) + 247, value & 0xFF];
  19544. } else if (value >= -1131 && value <= -108) {
  19545. value = -value - 108;
  19546. code = [(value >> 8) + 251, value & 0xFF];
  19547. } else if (value >= -32768 && value <= 32767) {
  19548. code = [0x1c, (value >> 8) & 0xFF, value & 0xFF];
  19549. } else {
  19550. code = [0x1d,
  19551. (value >> 24) & 0xFF,
  19552. (value >> 16) & 0xFF,
  19553. (value >> 8) & 0xFF,
  19554. value & 0xFF];
  19555. }
  19556. return code;
  19557. },
  19558. compileHeader: function CFFCompiler_compileHeader(header) {
  19559. return [
  19560. header.major,
  19561. header.minor,
  19562. header.hdrSize,
  19563. header.offSize
  19564. ];
  19565. },
  19566. compileNameIndex: function CFFCompiler_compileNameIndex(names) {
  19567. var nameIndex = new CFFIndex();
  19568. for (var i = 0, ii = names.length; i < ii; ++i) {
  19569. nameIndex.add(stringToBytes(names[i]));
  19570. }
  19571. return this.compileIndex(nameIndex);
  19572. },
  19573. compileTopDicts: function CFFCompiler_compileTopDicts(dicts,
  19574. length,
  19575. removeCidKeys) {
  19576. var fontDictTrackers = [];
  19577. var fdArrayIndex = new CFFIndex();
  19578. for (var i = 0, ii = dicts.length; i < ii; ++i) {
  19579. var fontDict = dicts[i];
  19580. if (removeCidKeys) {
  19581. fontDict.removeByName('CIDFontVersion');
  19582. fontDict.removeByName('CIDFontRevision');
  19583. fontDict.removeByName('CIDFontType');
  19584. fontDict.removeByName('CIDCount');
  19585. fontDict.removeByName('UIDBase');
  19586. }
  19587. var fontDictTracker = new CFFOffsetTracker();
  19588. var fontDictData = this.compileDict(fontDict, fontDictTracker);
  19589. fontDictTrackers.push(fontDictTracker);
  19590. fdArrayIndex.add(fontDictData);
  19591. fontDictTracker.offset(length);
  19592. }
  19593. fdArrayIndex = this.compileIndex(fdArrayIndex, fontDictTrackers);
  19594. return {
  19595. trackers: fontDictTrackers,
  19596. output: fdArrayIndex
  19597. };
  19598. },
  19599. compilePrivateDicts: function CFFCompiler_compilePrivateDicts(dicts,
  19600. trackers,
  19601. output) {
  19602. for (var i = 0, ii = dicts.length; i < ii; ++i) {
  19603. var fontDict = dicts[i];
  19604. assert(fontDict.privateDict && fontDict.hasName('Private'),
  19605. 'There must be an private dictionary.');
  19606. var privateDict = fontDict.privateDict;
  19607. var privateDictTracker = new CFFOffsetTracker();
  19608. var privateDictData = this.compileDict(privateDict, privateDictTracker);
  19609. var outputLength = output.length;
  19610. privateDictTracker.offset(outputLength);
  19611. if (!privateDictData.length) {
  19612. // The private dictionary was empty, set the output length to zero to
  19613. // ensure the offset length isn't out of bounds in the eyes of the
  19614. // sanitizer.
  19615. outputLength = 0;
  19616. }
  19617. trackers[i].setEntryLocation('Private',
  19618. [privateDictData.length, outputLength],
  19619. output);
  19620. output.add(privateDictData);
  19621. if (privateDict.subrsIndex && privateDict.hasName('Subrs')) {
  19622. var subrs = this.compileIndex(privateDict.subrsIndex);
  19623. privateDictTracker.setEntryLocation('Subrs', [privateDictData.length],
  19624. output);
  19625. output.add(subrs);
  19626. }
  19627. }
  19628. },
  19629. compileDict: function CFFCompiler_compileDict(dict, offsetTracker) {
  19630. var out = [];
  19631. // The dictionary keys must be in a certain order.
  19632. var order = dict.order;
  19633. for (var i = 0; i < order.length; ++i) {
  19634. var key = order[i];
  19635. if (!(key in dict.values)) {
  19636. continue;
  19637. }
  19638. var values = dict.values[key];
  19639. var types = dict.types[key];
  19640. if (!isArray(types)) {
  19641. types = [types];
  19642. }
  19643. if (!isArray(values)) {
  19644. values = [values];
  19645. }
  19646. // Remove any empty dict values.
  19647. if (values.length === 0) {
  19648. continue;
  19649. }
  19650. for (var j = 0, jj = types.length; j < jj; ++j) {
  19651. var type = types[j];
  19652. var value = values[j];
  19653. switch (type) {
  19654. case 'num':
  19655. case 'sid':
  19656. out = out.concat(this.encodeNumber(value));
  19657. break;
  19658. case 'offset':
  19659. // For offsets we just insert a 32bit integer so we don't have to
  19660. // deal with figuring out the length of the offset when it gets
  19661. // replaced later on by the compiler.
  19662. var name = dict.keyToNameMap[key];
  19663. // Some offsets have the offset and the length, so just record the
  19664. // position of the first one.
  19665. if (!offsetTracker.isTracking(name)) {
  19666. offsetTracker.track(name, out.length);
  19667. }
  19668. out = out.concat([0x1d, 0, 0, 0, 0]);
  19669. break;
  19670. case 'array':
  19671. case 'delta':
  19672. out = out.concat(this.encodeNumber(value));
  19673. for (var k = 1, kk = values.length; k < kk; ++k) {
  19674. out = out.concat(this.encodeNumber(values[k]));
  19675. }
  19676. break;
  19677. default:
  19678. error('Unknown data type of ' + type);
  19679. break;
  19680. }
  19681. }
  19682. out = out.concat(dict.opcodes[key]);
  19683. }
  19684. return out;
  19685. },
  19686. compileStringIndex: function CFFCompiler_compileStringIndex(strings) {
  19687. var stringIndex = new CFFIndex();
  19688. for (var i = 0, ii = strings.length; i < ii; ++i) {
  19689. stringIndex.add(stringToBytes(strings[i]));
  19690. }
  19691. return this.compileIndex(stringIndex);
  19692. },
  19693. compileGlobalSubrIndex: function CFFCompiler_compileGlobalSubrIndex() {
  19694. var globalSubrIndex = this.cff.globalSubrIndex;
  19695. this.out.writeByteArray(this.compileIndex(globalSubrIndex));
  19696. },
  19697. compileCharStrings: function CFFCompiler_compileCharStrings(charStrings) {
  19698. return this.compileIndex(charStrings);
  19699. },
  19700. compileCharset: function CFFCompiler_compileCharset(charset) {
  19701. return this.compileTypedArray(charset.raw);
  19702. },
  19703. compileEncoding: function CFFCompiler_compileEncoding(encoding) {
  19704. return this.compileTypedArray(encoding.raw);
  19705. },
  19706. compileFDSelect: function CFFCompiler_compileFDSelect(fdSelect) {
  19707. return this.compileTypedArray(fdSelect);
  19708. },
  19709. compileTypedArray: function CFFCompiler_compileTypedArray(data) {
  19710. var out = [];
  19711. for (var i = 0, ii = data.length; i < ii; ++i) {
  19712. out[i] = data[i];
  19713. }
  19714. return out;
  19715. },
  19716. compileIndex: function CFFCompiler_compileIndex(index, trackers) {
  19717. trackers = trackers || [];
  19718. var objects = index.objects;
  19719. // First 2 bytes contains the number of objects contained into this index
  19720. var count = objects.length;
  19721. // If there is no object, just create an index. This technically
  19722. // should just be [0, 0] but OTS has an issue with that.
  19723. if (count === 0) {
  19724. return [0, 0, 0];
  19725. }
  19726. var data = [(count >> 8) & 0xFF, count & 0xff];
  19727. var lastOffset = 1, i;
  19728. for (i = 0; i < count; ++i) {
  19729. lastOffset += objects[i].length;
  19730. }
  19731. var offsetSize;
  19732. if (lastOffset < 0x100) {
  19733. offsetSize = 1;
  19734. } else if (lastOffset < 0x10000) {
  19735. offsetSize = 2;
  19736. } else if (lastOffset < 0x1000000) {
  19737. offsetSize = 3;
  19738. } else {
  19739. offsetSize = 4;
  19740. }
  19741. // Next byte contains the offset size use to reference object in the file
  19742. data.push(offsetSize);
  19743. // Add another offset after this one because we need a new offset
  19744. var relativeOffset = 1;
  19745. for (i = 0; i < count + 1; i++) {
  19746. if (offsetSize === 1) {
  19747. data.push(relativeOffset & 0xFF);
  19748. } else if (offsetSize === 2) {
  19749. data.push((relativeOffset >> 8) & 0xFF,
  19750. relativeOffset & 0xFF);
  19751. } else if (offsetSize === 3) {
  19752. data.push((relativeOffset >> 16) & 0xFF,
  19753. (relativeOffset >> 8) & 0xFF,
  19754. relativeOffset & 0xFF);
  19755. } else {
  19756. data.push((relativeOffset >>> 24) & 0xFF,
  19757. (relativeOffset >> 16) & 0xFF,
  19758. (relativeOffset >> 8) & 0xFF,
  19759. relativeOffset & 0xFF);
  19760. }
  19761. if (objects[i]) {
  19762. relativeOffset += objects[i].length;
  19763. }
  19764. }
  19765. for (i = 0; i < count; i++) {
  19766. // Notify the tracker where the object will be offset in the data.
  19767. if (trackers[i]) {
  19768. trackers[i].offset(data.length);
  19769. }
  19770. for (var j = 0, jj = objects[i].length; j < jj; j++) {
  19771. data.push(objects[i][j]);
  19772. }
  19773. }
  19774. return data;
  19775. }
  19776. };
  19777. return CFFCompiler;
  19778. })();
  19779. // Workaround for seac on Windows.
  19780. (function checkSeacSupport() {
  19781. if (/Windows/.test(navigator.userAgent)) {
  19782. SEAC_ANALYSIS_ENABLED = true;
  19783. }
  19784. })();
  19785. // Workaround for Private Use Area characters in Chrome on Windows
  19786. // http://code.google.com/p/chromium/issues/detail?id=122465
  19787. // https://github.com/mozilla/pdf.js/issues/1689
  19788. (function checkChromeWindows() {
  19789. if (/Windows.*Chrome/.test(navigator.userAgent)) {
  19790. SKIP_PRIVATE_USE_RANGE_F000_TO_F01F = true;
  19791. }
  19792. })();
  19793. var FontRendererFactory = (function FontRendererFactoryClosure() {
  19794. function getLong(data, offset) {
  19795. return (data[offset] << 24) | (data[offset + 1] << 16) |
  19796. (data[offset + 2] << 8) | data[offset + 3];
  19797. }
  19798. function getUshort(data, offset) {
  19799. return (data[offset] << 8) | data[offset + 1];
  19800. }
  19801. function parseCmap(data, start, end) {
  19802. var offset = (getUshort(data, start + 2) === 1 ?
  19803. getLong(data, start + 8) : getLong(data, start + 16));
  19804. var format = getUshort(data, start + offset);
  19805. var length, ranges, p, i;
  19806. if (format === 4) {
  19807. length = getUshort(data, start + offset + 2);
  19808. var segCount = getUshort(data, start + offset + 6) >> 1;
  19809. p = start + offset + 14;
  19810. ranges = [];
  19811. for (i = 0; i < segCount; i++, p += 2) {
  19812. ranges[i] = {end: getUshort(data, p)};
  19813. }
  19814. p += 2;
  19815. for (i = 0; i < segCount; i++, p += 2) {
  19816. ranges[i].start = getUshort(data, p);
  19817. }
  19818. for (i = 0; i < segCount; i++, p += 2) {
  19819. ranges[i].idDelta = getUshort(data, p);
  19820. }
  19821. for (i = 0; i < segCount; i++, p += 2) {
  19822. var idOffset = getUshort(data, p);
  19823. if (idOffset === 0) {
  19824. continue;
  19825. }
  19826. ranges[i].ids = [];
  19827. for (var j = 0, jj = ranges[i].end - ranges[i].start + 1; j < jj; j++) {
  19828. ranges[i].ids[j] = getUshort(data, p + idOffset);
  19829. idOffset += 2;
  19830. }
  19831. }
  19832. return ranges;
  19833. } else if (format === 12) {
  19834. length = getLong(data, start + offset + 4);
  19835. var groups = getLong(data, start + offset + 12);
  19836. p = start + offset + 16;
  19837. ranges = [];
  19838. for (i = 0; i < groups; i++) {
  19839. ranges.push({
  19840. start: getLong(data, p),
  19841. end: getLong(data, p + 4),
  19842. idDelta: getLong(data, p + 8) - getLong(data, p)
  19843. });
  19844. p += 12;
  19845. }
  19846. return ranges;
  19847. }
  19848. error('not supported cmap: ' + format);
  19849. }
  19850. function parseCff(data, start, end) {
  19851. var properties = {};
  19852. var parser = new CFFParser(new Stream(data, start, end - start),
  19853. properties);
  19854. var cff = parser.parse();
  19855. return {
  19856. glyphs: cff.charStrings.objects,
  19857. subrs: (cff.topDict.privateDict && cff.topDict.privateDict.subrsIndex &&
  19858. cff.topDict.privateDict.subrsIndex.objects),
  19859. gsubrs: cff.globalSubrIndex && cff.globalSubrIndex.objects
  19860. };
  19861. }
  19862. function parseGlyfTable(glyf, loca, isGlyphLocationsLong) {
  19863. var itemSize, itemDecode;
  19864. if (isGlyphLocationsLong) {
  19865. itemSize = 4;
  19866. itemDecode = function fontItemDecodeLong(data, offset) {
  19867. return (data[offset] << 24) | (data[offset + 1] << 16) |
  19868. (data[offset + 2] << 8) | data[offset + 3];
  19869. };
  19870. } else {
  19871. itemSize = 2;
  19872. itemDecode = function fontItemDecode(data, offset) {
  19873. return (data[offset] << 9) | (data[offset + 1] << 1);
  19874. };
  19875. }
  19876. var glyphs = [];
  19877. var startOffset = itemDecode(loca, 0);
  19878. for (var j = itemSize; j < loca.length; j += itemSize) {
  19879. var endOffset = itemDecode(loca, j);
  19880. glyphs.push(glyf.subarray(startOffset, endOffset));
  19881. startOffset = endOffset;
  19882. }
  19883. return glyphs;
  19884. }
  19885. function lookupCmap(ranges, unicode) {
  19886. var code = unicode.charCodeAt(0);
  19887. var l = 0, r = ranges.length - 1;
  19888. while (l < r) {
  19889. var c = (l + r + 1) >> 1;
  19890. if (code < ranges[c].start) {
  19891. r = c - 1;
  19892. } else {
  19893. l = c;
  19894. }
  19895. }
  19896. if (ranges[l].start <= code && code <= ranges[l].end) {
  19897. return (ranges[l].idDelta + (ranges[l].ids ?
  19898. ranges[l].ids[code - ranges[l].start] : code)) & 0xFFFF;
  19899. }
  19900. return 0;
  19901. }
  19902. function compileGlyf(code, js, font) {
  19903. function moveTo(x, y) {
  19904. js.push('c.moveTo(' + x + ',' + y + ');');
  19905. }
  19906. function lineTo(x, y) {
  19907. js.push('c.lineTo(' + x + ',' + y + ');');
  19908. }
  19909. function quadraticCurveTo(xa, ya, x, y) {
  19910. js.push('c.quadraticCurveTo(' + xa + ',' + ya + ',' +
  19911. x + ',' + y + ');');
  19912. }
  19913. var i = 0;
  19914. var numberOfContours = ((code[i] << 24) | (code[i + 1] << 16)) >> 16;
  19915. var flags;
  19916. var x = 0, y = 0;
  19917. i += 10;
  19918. if (numberOfContours < 0) {
  19919. // composite glyph
  19920. do {
  19921. flags = (code[i] << 8) | code[i + 1];
  19922. var glyphIndex = (code[i + 2] << 8) | code[i + 3];
  19923. i += 4;
  19924. var arg1, arg2;
  19925. if ((flags & 0x01)) {
  19926. arg1 = ((code[i] << 24) | (code[i + 1] << 16)) >> 16;
  19927. arg2 = ((code[i + 2] << 24) | (code[i + 3] << 16)) >> 16;
  19928. i += 4;
  19929. } else {
  19930. arg1 = code[i++]; arg2 = code[i++];
  19931. }
  19932. if ((flags & 0x02)) {
  19933. x = arg1;
  19934. y = arg2;
  19935. } else {
  19936. x = 0; y = 0; // TODO "they are points" ?
  19937. }
  19938. var scaleX = 1, scaleY = 1, scale01 = 0, scale10 = 0;
  19939. if ((flags & 0x08)) {
  19940. scaleX =
  19941. scaleY = ((code[i] << 24) | (code[i + 1] << 16)) / 1073741824;
  19942. i += 2;
  19943. } else if ((flags & 0x40)) {
  19944. scaleX = ((code[i] << 24) | (code[i + 1] << 16)) / 1073741824;
  19945. scaleY = ((code[i + 2] << 24) | (code[i + 3] << 16)) / 1073741824;
  19946. i += 4;
  19947. } else if ((flags & 0x80)) {
  19948. scaleX = ((code[i] << 24) | (code[i + 1] << 16)) / 1073741824;
  19949. scale01 = ((code[i + 2] << 24) | (code[i + 3] << 16)) / 1073741824;
  19950. scale10 = ((code[i + 4] << 24) | (code[i + 5] << 16)) / 1073741824;
  19951. scaleY = ((code[i + 6] << 24) | (code[i + 7] << 16)) / 1073741824;
  19952. i += 8;
  19953. }
  19954. var subglyph = font.glyphs[glyphIndex];
  19955. if (subglyph) {
  19956. js.push('c.save();');
  19957. js.push('c.transform(' + scaleX + ',' + scale01 + ',' +
  19958. scale10 + ',' + scaleY + ',' + x + ',' + y + ');');
  19959. compileGlyf(subglyph, js, font);
  19960. js.push('c.restore();');
  19961. }
  19962. } while ((flags & 0x20));
  19963. } else {
  19964. // simple glyph
  19965. var endPtsOfContours = [];
  19966. var j, jj;
  19967. for (j = 0; j < numberOfContours; j++) {
  19968. endPtsOfContours.push((code[i] << 8) | code[i + 1]);
  19969. i += 2;
  19970. }
  19971. var instructionLength = (code[i] << 8) | code[i + 1];
  19972. i += 2 + instructionLength; // skipping the instructions
  19973. var numberOfPoints = endPtsOfContours[endPtsOfContours.length - 1] + 1;
  19974. var points = [];
  19975. while (points.length < numberOfPoints) {
  19976. flags = code[i++];
  19977. var repeat = 1;
  19978. if ((flags & 0x08)) {
  19979. repeat += code[i++];
  19980. }
  19981. while (repeat-- > 0) {
  19982. points.push({flags: flags});
  19983. }
  19984. }
  19985. for (j = 0; j < numberOfPoints; j++) {
  19986. switch (points[j].flags & 0x12) {
  19987. case 0x00:
  19988. x += ((code[i] << 24) | (code[i + 1] << 16)) >> 16;
  19989. i += 2;
  19990. break;
  19991. case 0x02:
  19992. x -= code[i++];
  19993. break;
  19994. case 0x12:
  19995. x += code[i++];
  19996. break;
  19997. }
  19998. points[j].x = x;
  19999. }
  20000. for (j = 0; j < numberOfPoints; j++) {
  20001. switch (points[j].flags & 0x24) {
  20002. case 0x00:
  20003. y += ((code[i] << 24) | (code[i + 1] << 16)) >> 16;
  20004. i += 2;
  20005. break;
  20006. case 0x04:
  20007. y -= code[i++];
  20008. break;
  20009. case 0x24:
  20010. y += code[i++];
  20011. break;
  20012. }
  20013. points[j].y = y;
  20014. }
  20015. var startPoint = 0;
  20016. for (i = 0; i < numberOfContours; i++) {
  20017. var endPoint = endPtsOfContours[i];
  20018. // contours might have implicit points, which is located in the middle
  20019. // between two neighboring off-curve points
  20020. var contour = points.slice(startPoint, endPoint + 1);
  20021. if ((contour[0].flags & 1)) {
  20022. contour.push(contour[0]); // using start point at the contour end
  20023. } else if ((contour[contour.length - 1].flags & 1)) {
  20024. // first is off-curve point, trying to use one from the end
  20025. contour.unshift(contour[contour.length - 1]);
  20026. } else {
  20027. // start and end are off-curve points, creating implicit one
  20028. var p = {
  20029. flags: 1,
  20030. x: (contour[0].x + contour[contour.length - 1].x) / 2,
  20031. y: (contour[0].y + contour[contour.length - 1].y) / 2
  20032. };
  20033. contour.unshift(p);
  20034. contour.push(p);
  20035. }
  20036. moveTo(contour[0].x, contour[0].y);
  20037. for (j = 1, jj = contour.length; j < jj; j++) {
  20038. if ((contour[j].flags & 1)) {
  20039. lineTo(contour[j].x, contour[j].y);
  20040. } else if ((contour[j + 1].flags & 1)){
  20041. quadraticCurveTo(contour[j].x, contour[j].y,
  20042. contour[j + 1].x, contour[j + 1].y);
  20043. j++;
  20044. } else {
  20045. quadraticCurveTo(contour[j].x, contour[j].y,
  20046. (contour[j].x + contour[j + 1].x) / 2,
  20047. (contour[j].y + contour[j + 1].y) / 2);
  20048. }
  20049. }
  20050. startPoint = endPoint + 1;
  20051. }
  20052. }
  20053. }
  20054. function compileCharString(code, js, font) {
  20055. var stack = [];
  20056. var x = 0, y = 0;
  20057. var stems = 0;
  20058. function moveTo(x, y) {
  20059. js.push('c.moveTo(' + x + ',' + y + ');');
  20060. }
  20061. function lineTo(x, y) {
  20062. js.push('c.lineTo(' + x + ',' + y + ');');
  20063. }
  20064. function bezierCurveTo(x1, y1, x2, y2, x, y) {
  20065. js.push('c.bezierCurveTo(' + x1 + ',' + y1 + ',' + x2 + ',' + y2 + ',' +
  20066. x + ',' + y + ');');
  20067. }
  20068. function parse(code) {
  20069. var i = 0;
  20070. while (i < code.length) {
  20071. var stackClean = false;
  20072. var v = code[i++];
  20073. var xa, xb, ya, yb, y1, y2, y3, n, subrCode;
  20074. switch (v) {
  20075. case 1: // hstem
  20076. stems += stack.length >> 1;
  20077. stackClean = true;
  20078. break;
  20079. case 3: // vstem
  20080. stems += stack.length >> 1;
  20081. stackClean = true;
  20082. break;
  20083. case 4: // vmoveto
  20084. y += stack.pop();
  20085. moveTo(x, y);
  20086. stackClean = true;
  20087. break;
  20088. case 5: // rlineto
  20089. while (stack.length > 0) {
  20090. x += stack.shift();
  20091. y += stack.shift();
  20092. lineTo(x, y);
  20093. }
  20094. break;
  20095. case 6: // hlineto
  20096. while (stack.length > 0) {
  20097. x += stack.shift();
  20098. lineTo(x, y);
  20099. if (stack.length === 0) {
  20100. break;
  20101. }
  20102. y += stack.shift();
  20103. lineTo(x, y);
  20104. }
  20105. break;
  20106. case 7: // vlineto
  20107. while (stack.length > 0) {
  20108. y += stack.shift();
  20109. lineTo(x, y);
  20110. if (stack.length === 0) {
  20111. break;
  20112. }
  20113. x += stack.shift();
  20114. lineTo(x, y);
  20115. }
  20116. break;
  20117. case 8: // rrcurveto
  20118. while (stack.length > 0) {
  20119. xa = x + stack.shift(); ya = y + stack.shift();
  20120. xb = xa + stack.shift(); yb = ya + stack.shift();
  20121. x = xb + stack.shift(); y = yb + stack.shift();
  20122. bezierCurveTo(xa, ya, xb, yb, x, y);
  20123. }
  20124. break;
  20125. case 10: // callsubr
  20126. n = stack.pop() + font.subrsBias;
  20127. subrCode = font.subrs[n];
  20128. if (subrCode) {
  20129. parse(subrCode);
  20130. }
  20131. break;
  20132. case 11: // return
  20133. return;
  20134. case 12:
  20135. v = code[i++];
  20136. switch (v) {
  20137. case 34: // flex
  20138. xa = x + stack.shift();
  20139. xb = xa + stack.shift(); y1 = y + stack.shift();
  20140. x = xb + stack.shift();
  20141. bezierCurveTo(xa, y, xb, y1, x, y1);
  20142. xa = x + stack.shift();
  20143. xb = xa + stack.shift();
  20144. x = xb + stack.shift();
  20145. bezierCurveTo(xa, y1, xb, y, x, y);
  20146. break;
  20147. case 35: // flex
  20148. xa = x + stack.shift(); ya = y + stack.shift();
  20149. xb = xa + stack.shift(); yb = ya + stack.shift();
  20150. x = xb + stack.shift(); y = yb + stack.shift();
  20151. bezierCurveTo(xa, ya, xb, yb, x, y);
  20152. xa = x + stack.shift(); ya = y + stack.shift();
  20153. xb = xa + stack.shift(); yb = ya + stack.shift();
  20154. x = xb + stack.shift(); y = yb + stack.shift();
  20155. bezierCurveTo(xa, ya, xb, yb, x, y);
  20156. stack.pop(); // fd
  20157. break;
  20158. case 36: // hflex1
  20159. xa = x + stack.shift(); y1 = y + stack.shift();
  20160. xb = xa + stack.shift(); y2 = y1 + stack.shift();
  20161. x = xb + stack.shift();
  20162. bezierCurveTo(xa, y1, xb, y2, x, y2);
  20163. xa = x + stack.shift();
  20164. xb = xa + stack.shift(); y3 = y2 + stack.shift();
  20165. x = xb + stack.shift();
  20166. bezierCurveTo(xa, y2, xb, y3, x, y);
  20167. break;
  20168. case 37: // flex1
  20169. var x0 = x, y0 = y;
  20170. xa = x + stack.shift(); ya = y + stack.shift();
  20171. xb = xa + stack.shift(); yb = ya + stack.shift();
  20172. x = xb + stack.shift(); y = yb + stack.shift();
  20173. bezierCurveTo(xa, ya, xb, yb, x, y);
  20174. xa = x + stack.shift(); ya = y + stack.shift();
  20175. xb = xa + stack.shift(); yb = ya + stack.shift();
  20176. x = xb; y = yb;
  20177. if (Math.abs(x - x0) > Math.abs(y - y0)) {
  20178. x += stack.shift();
  20179. } else {
  20180. y += stack.shift();
  20181. }
  20182. bezierCurveTo(xa, ya, xb, yb, x, y);
  20183. break;
  20184. default:
  20185. error('unknown operator: 12 ' + v);
  20186. }
  20187. break;
  20188. case 14: // endchar
  20189. if (stack.length >= 4) {
  20190. var achar = stack.pop();
  20191. var bchar = stack.pop();
  20192. y = stack.pop();
  20193. x = stack.pop();
  20194. js.push('c.save();');
  20195. js.push('c.translate('+ x + ',' + y + ');');
  20196. var gid = lookupCmap(font.cmap, String.fromCharCode(
  20197. font.glyphNameMap[Encodings.StandardEncoding[achar]]));
  20198. compileCharString(font.glyphs[gid], js, font);
  20199. js.push('c.restore();');
  20200. gid = lookupCmap(font.cmap, String.fromCharCode(
  20201. font.glyphNameMap[Encodings.StandardEncoding[bchar]]));
  20202. compileCharString(font.glyphs[gid], js, font);
  20203. }
  20204. return;
  20205. case 18: // hstemhm
  20206. stems += stack.length >> 1;
  20207. stackClean = true;
  20208. break;
  20209. case 19: // hintmask
  20210. stems += stack.length >> 1;
  20211. i += (stems + 7) >> 3;
  20212. stackClean = true;
  20213. break;
  20214. case 20: // cntrmask
  20215. stems += stack.length >> 1;
  20216. i += (stems + 7) >> 3;
  20217. stackClean = true;
  20218. break;
  20219. case 21: // rmoveto
  20220. y += stack.pop();
  20221. x += stack.pop();
  20222. moveTo(x, y);
  20223. stackClean = true;
  20224. break;
  20225. case 22: // hmoveto
  20226. x += stack.pop();
  20227. moveTo(x, y);
  20228. stackClean = true;
  20229. break;
  20230. case 23: // vstemhm
  20231. stems += stack.length >> 1;
  20232. stackClean = true;
  20233. break;
  20234. case 24: // rcurveline
  20235. while (stack.length > 2) {
  20236. xa = x + stack.shift(); ya = y + stack.shift();
  20237. xb = xa + stack.shift(); yb = ya + stack.shift();
  20238. x = xb + stack.shift(); y = yb + stack.shift();
  20239. bezierCurveTo(xa, ya, xb, yb, x, y);
  20240. }
  20241. x += stack.shift();
  20242. y += stack.shift();
  20243. lineTo(x, y);
  20244. break;
  20245. case 25: // rlinecurve
  20246. while (stack.length > 6) {
  20247. x += stack.shift();
  20248. y += stack.shift();
  20249. lineTo(x, y);
  20250. }
  20251. xa = x + stack.shift(); ya = y + stack.shift();
  20252. xb = xa + stack.shift(); yb = ya + stack.shift();
  20253. x = xb + stack.shift(); y = yb + stack.shift();
  20254. bezierCurveTo(xa, ya, xb, yb, x, y);
  20255. break;
  20256. case 26: // vvcurveto
  20257. if (stack.length % 2) {
  20258. x += stack.shift();
  20259. }
  20260. while (stack.length > 0) {
  20261. xa = x; ya = y + stack.shift();
  20262. xb = xa + stack.shift(); yb = ya + stack.shift();
  20263. x = xb; y = yb + stack.shift();
  20264. bezierCurveTo(xa, ya, xb, yb, x, y);
  20265. }
  20266. break;
  20267. case 27: // hhcurveto
  20268. if (stack.length % 2) {
  20269. y += stack.shift();
  20270. }
  20271. while (stack.length > 0) {
  20272. xa = x + stack.shift(); ya = y;
  20273. xb = xa + stack.shift(); yb = ya + stack.shift();
  20274. x = xb + stack.shift(); y = yb;
  20275. bezierCurveTo(xa, ya, xb, yb, x, y);
  20276. }
  20277. break;
  20278. case 28:
  20279. stack.push(((code[i] << 24) | (code[i + 1] << 16)) >> 16);
  20280. i += 2;
  20281. break;
  20282. case 29: // callgsubr
  20283. n = stack.pop() + font.gsubrsBias;
  20284. subrCode = font.gsubrs[n];
  20285. if (subrCode) {
  20286. parse(subrCode);
  20287. }
  20288. break;
  20289. case 30: // vhcurveto
  20290. while (stack.length > 0) {
  20291. xa = x; ya = y + stack.shift();
  20292. xb = xa + stack.shift(); yb = ya + stack.shift();
  20293. x = xb + stack.shift();
  20294. y = yb + (stack.length === 1 ? stack.shift() : 0);
  20295. bezierCurveTo(xa, ya, xb, yb, x, y);
  20296. if (stack.length === 0) {
  20297. break;
  20298. }
  20299. xa = x + stack.shift(); ya = y;
  20300. xb = xa + stack.shift(); yb = ya + stack.shift();
  20301. y = yb + stack.shift();
  20302. x = xb + (stack.length === 1 ? stack.shift() : 0);
  20303. bezierCurveTo(xa, ya, xb, yb, x, y);
  20304. }
  20305. break;
  20306. case 31: // hvcurveto
  20307. while (stack.length > 0) {
  20308. xa = x + stack.shift(); ya = y;
  20309. xb = xa + stack.shift(); yb = ya + stack.shift();
  20310. y = yb + stack.shift();
  20311. x = xb + (stack.length === 1 ? stack.shift() : 0);
  20312. bezierCurveTo(xa, ya, xb, yb, x, y);
  20313. if (stack.length === 0) {
  20314. break;
  20315. }
  20316. xa = x; ya = y + stack.shift();
  20317. xb = xa + stack.shift(); yb = ya + stack.shift();
  20318. x = xb + stack.shift();
  20319. y = yb + (stack.length === 1 ? stack.shift() : 0);
  20320. bezierCurveTo(xa, ya, xb, yb, x, y);
  20321. }
  20322. break;
  20323. default:
  20324. if (v < 32) {
  20325. error('unknown operator: ' + v);
  20326. }
  20327. if (v < 247) {
  20328. stack.push(v - 139);
  20329. } else if (v < 251) {
  20330. stack.push((v - 247) * 256 + code[i++] + 108);
  20331. } else if (v < 255) {
  20332. stack.push(-(v - 251) * 256 - code[i++] - 108);
  20333. } else {
  20334. stack.push(((code[i] << 24) | (code[i + 1] << 16) |
  20335. (code[i + 2] << 8) | code[i + 3]) / 65536);
  20336. i += 4;
  20337. }
  20338. break;
  20339. }
  20340. if (stackClean) {
  20341. stack.length = 0;
  20342. }
  20343. }
  20344. }
  20345. parse(code);
  20346. }
  20347. var noop = '';
  20348. function CompiledFont(fontMatrix) {
  20349. this.compiledGlyphs = {};
  20350. this.fontMatrix = fontMatrix;
  20351. }
  20352. CompiledFont.prototype = {
  20353. getPathJs: function (unicode) {
  20354. var gid = lookupCmap(this.cmap, unicode);
  20355. var fn = this.compiledGlyphs[gid];
  20356. if (!fn) {
  20357. this.compiledGlyphs[gid] = fn = this.compileGlyph(this.glyphs[gid]);
  20358. }
  20359. return fn;
  20360. },
  20361. compileGlyph: function (code) {
  20362. if (!code || code.length === 0 || code[0] === 14) {
  20363. return noop;
  20364. }
  20365. var js = [];
  20366. js.push('c.save();');
  20367. js.push('c.transform(' + this.fontMatrix.join(',') + ');');
  20368. js.push('c.scale(size, -size);');
  20369. this.compileGlyphImpl(code, js);
  20370. js.push('c.restore();');
  20371. return js.join('\n');
  20372. },
  20373. compileGlyphImpl: function () {
  20374. error('Children classes should implement this.');
  20375. },
  20376. hasBuiltPath: function (unicode) {
  20377. var gid = lookupCmap(this.cmap, unicode);
  20378. return gid in this.compiledGlyphs;
  20379. }
  20380. };
  20381. function TrueTypeCompiled(glyphs, cmap, fontMatrix) {
  20382. fontMatrix = fontMatrix || [0.000488, 0, 0, 0.000488, 0, 0];
  20383. CompiledFont.call(this, fontMatrix);
  20384. this.glyphs = glyphs;
  20385. this.cmap = cmap;
  20386. this.compiledGlyphs = [];
  20387. }
  20388. Util.inherit(TrueTypeCompiled, CompiledFont, {
  20389. compileGlyphImpl: function (code, js) {
  20390. compileGlyf(code, js, this);
  20391. }
  20392. });
  20393. function Type2Compiled(cffInfo, cmap, fontMatrix, glyphNameMap) {
  20394. fontMatrix = fontMatrix || [0.001, 0, 0, 0.001, 0, 0];
  20395. CompiledFont.call(this, fontMatrix);
  20396. this.glyphs = cffInfo.glyphs;
  20397. this.gsubrs = cffInfo.gsubrs || [];
  20398. this.subrs = cffInfo.subrs || [];
  20399. this.cmap = cmap;
  20400. this.glyphNameMap = glyphNameMap || GlyphsUnicode;
  20401. this.compiledGlyphs = [];
  20402. this.gsubrsBias = (this.gsubrs.length < 1240 ?
  20403. 107 : (this.gsubrs.length < 33900 ? 1131 : 32768));
  20404. this.subrsBias = (this.subrs.length < 1240 ?
  20405. 107 : (this.subrs.length < 33900 ? 1131 : 32768));
  20406. }
  20407. Util.inherit(Type2Compiled, CompiledFont, {
  20408. compileGlyphImpl: function (code, js) {
  20409. compileCharString(code, js, this);
  20410. }
  20411. });
  20412. return {
  20413. create: function FontRendererFactory_create(font) {
  20414. var data = new Uint8Array(font.data);
  20415. var cmap, glyf, loca, cff, indexToLocFormat, unitsPerEm;
  20416. var numTables = getUshort(data, 4);
  20417. for (var i = 0, p = 12; i < numTables; i++, p += 16) {
  20418. var tag = bytesToString(data.subarray(p, p + 4));
  20419. var offset = getLong(data, p + 8);
  20420. var length = getLong(data, p + 12);
  20421. switch (tag) {
  20422. case 'cmap':
  20423. cmap = parseCmap(data, offset, offset + length);
  20424. break;
  20425. case 'glyf':
  20426. glyf = data.subarray(offset, offset + length);
  20427. break;
  20428. case 'loca':
  20429. loca = data.subarray(offset, offset + length);
  20430. break;
  20431. case 'head':
  20432. unitsPerEm = getUshort(data, offset + 18);
  20433. indexToLocFormat = getUshort(data, offset + 50);
  20434. break;
  20435. case 'CFF ':
  20436. cff = parseCff(data, offset, offset + length);
  20437. break;
  20438. }
  20439. }
  20440. if (glyf) {
  20441. var fontMatrix = (!unitsPerEm ? font.fontMatrix :
  20442. [1 / unitsPerEm, 0, 0, 1 / unitsPerEm, 0, 0]);
  20443. return new TrueTypeCompiled(
  20444. parseGlyfTable(glyf, loca, indexToLocFormat), cmap, fontMatrix);
  20445. } else {
  20446. return new Type2Compiled(cff, cmap, font.fontMatrix, font.glyphNameMap);
  20447. }
  20448. }
  20449. };
  20450. })();
  20451. var GlyphsUnicode = {
  20452. A: 0x0041,
  20453. AE: 0x00C6,
  20454. AEacute: 0x01FC,
  20455. AEmacron: 0x01E2,
  20456. AEsmall: 0xF7E6,
  20457. Aacute: 0x00C1,
  20458. Aacutesmall: 0xF7E1,
  20459. Abreve: 0x0102,
  20460. Abreveacute: 0x1EAE,
  20461. Abrevecyrillic: 0x04D0,
  20462. Abrevedotbelow: 0x1EB6,
  20463. Abrevegrave: 0x1EB0,
  20464. Abrevehookabove: 0x1EB2,
  20465. Abrevetilde: 0x1EB4,
  20466. Acaron: 0x01CD,
  20467. Acircle: 0x24B6,
  20468. Acircumflex: 0x00C2,
  20469. Acircumflexacute: 0x1EA4,
  20470. Acircumflexdotbelow: 0x1EAC,
  20471. Acircumflexgrave: 0x1EA6,
  20472. Acircumflexhookabove: 0x1EA8,
  20473. Acircumflexsmall: 0xF7E2,
  20474. Acircumflextilde: 0x1EAA,
  20475. Acute: 0xF6C9,
  20476. Acutesmall: 0xF7B4,
  20477. Acyrillic: 0x0410,
  20478. Adblgrave: 0x0200,
  20479. Adieresis: 0x00C4,
  20480. Adieresiscyrillic: 0x04D2,
  20481. Adieresismacron: 0x01DE,
  20482. Adieresissmall: 0xF7E4,
  20483. Adotbelow: 0x1EA0,
  20484. Adotmacron: 0x01E0,
  20485. Agrave: 0x00C0,
  20486. Agravesmall: 0xF7E0,
  20487. Ahookabove: 0x1EA2,
  20488. Aiecyrillic: 0x04D4,
  20489. Ainvertedbreve: 0x0202,
  20490. Alpha: 0x0391,
  20491. Alphatonos: 0x0386,
  20492. Amacron: 0x0100,
  20493. Amonospace: 0xFF21,
  20494. Aogonek: 0x0104,
  20495. Aring: 0x00C5,
  20496. Aringacute: 0x01FA,
  20497. Aringbelow: 0x1E00,
  20498. Aringsmall: 0xF7E5,
  20499. Asmall: 0xF761,
  20500. Atilde: 0x00C3,
  20501. Atildesmall: 0xF7E3,
  20502. Aybarmenian: 0x0531,
  20503. B: 0x0042,
  20504. Bcircle: 0x24B7,
  20505. Bdotaccent: 0x1E02,
  20506. Bdotbelow: 0x1E04,
  20507. Becyrillic: 0x0411,
  20508. Benarmenian: 0x0532,
  20509. Beta: 0x0392,
  20510. Bhook: 0x0181,
  20511. Blinebelow: 0x1E06,
  20512. Bmonospace: 0xFF22,
  20513. Brevesmall: 0xF6F4,
  20514. Bsmall: 0xF762,
  20515. Btopbar: 0x0182,
  20516. C: 0x0043,
  20517. Caarmenian: 0x053E,
  20518. Cacute: 0x0106,
  20519. Caron: 0xF6CA,
  20520. Caronsmall: 0xF6F5,
  20521. Ccaron: 0x010C,
  20522. Ccedilla: 0x00C7,
  20523. Ccedillaacute: 0x1E08,
  20524. Ccedillasmall: 0xF7E7,
  20525. Ccircle: 0x24B8,
  20526. Ccircumflex: 0x0108,
  20527. Cdot: 0x010A,
  20528. Cdotaccent: 0x010A,
  20529. Cedillasmall: 0xF7B8,
  20530. Chaarmenian: 0x0549,
  20531. Cheabkhasiancyrillic: 0x04BC,
  20532. Checyrillic: 0x0427,
  20533. Chedescenderabkhasiancyrillic: 0x04BE,
  20534. Chedescendercyrillic: 0x04B6,
  20535. Chedieresiscyrillic: 0x04F4,
  20536. Cheharmenian: 0x0543,
  20537. Chekhakassiancyrillic: 0x04CB,
  20538. Cheverticalstrokecyrillic: 0x04B8,
  20539. Chi: 0x03A7,
  20540. Chook: 0x0187,
  20541. Circumflexsmall: 0xF6F6,
  20542. Cmonospace: 0xFF23,
  20543. Coarmenian: 0x0551,
  20544. Csmall: 0xF763,
  20545. D: 0x0044,
  20546. DZ: 0x01F1,
  20547. DZcaron: 0x01C4,
  20548. Daarmenian: 0x0534,
  20549. Dafrican: 0x0189,
  20550. Dcaron: 0x010E,
  20551. Dcedilla: 0x1E10,
  20552. Dcircle: 0x24B9,
  20553. Dcircumflexbelow: 0x1E12,
  20554. Dcroat: 0x0110,
  20555. Ddotaccent: 0x1E0A,
  20556. Ddotbelow: 0x1E0C,
  20557. Decyrillic: 0x0414,
  20558. Deicoptic: 0x03EE,
  20559. Delta: 0x2206,
  20560. Deltagreek: 0x0394,
  20561. Dhook: 0x018A,
  20562. Dieresis: 0xF6CB,
  20563. DieresisAcute: 0xF6CC,
  20564. DieresisGrave: 0xF6CD,
  20565. Dieresissmall: 0xF7A8,
  20566. Digammagreek: 0x03DC,
  20567. Djecyrillic: 0x0402,
  20568. Dlinebelow: 0x1E0E,
  20569. Dmonospace: 0xFF24,
  20570. Dotaccentsmall: 0xF6F7,
  20571. Dslash: 0x0110,
  20572. Dsmall: 0xF764,
  20573. Dtopbar: 0x018B,
  20574. Dz: 0x01F2,
  20575. Dzcaron: 0x01C5,
  20576. Dzeabkhasiancyrillic: 0x04E0,
  20577. Dzecyrillic: 0x0405,
  20578. Dzhecyrillic: 0x040F,
  20579. E: 0x0045,
  20580. Eacute: 0x00C9,
  20581. Eacutesmall: 0xF7E9,
  20582. Ebreve: 0x0114,
  20583. Ecaron: 0x011A,
  20584. Ecedillabreve: 0x1E1C,
  20585. Echarmenian: 0x0535,
  20586. Ecircle: 0x24BA,
  20587. Ecircumflex: 0x00CA,
  20588. Ecircumflexacute: 0x1EBE,
  20589. Ecircumflexbelow: 0x1E18,
  20590. Ecircumflexdotbelow: 0x1EC6,
  20591. Ecircumflexgrave: 0x1EC0,
  20592. Ecircumflexhookabove: 0x1EC2,
  20593. Ecircumflexsmall: 0xF7EA,
  20594. Ecircumflextilde: 0x1EC4,
  20595. Ecyrillic: 0x0404,
  20596. Edblgrave: 0x0204,
  20597. Edieresis: 0x00CB,
  20598. Edieresissmall: 0xF7EB,
  20599. Edot: 0x0116,
  20600. Edotaccent: 0x0116,
  20601. Edotbelow: 0x1EB8,
  20602. Efcyrillic: 0x0424,
  20603. Egrave: 0x00C8,
  20604. Egravesmall: 0xF7E8,
  20605. Eharmenian: 0x0537,
  20606. Ehookabove: 0x1EBA,
  20607. Eightroman: 0x2167,
  20608. Einvertedbreve: 0x0206,
  20609. Eiotifiedcyrillic: 0x0464,
  20610. Elcyrillic: 0x041B,
  20611. Elevenroman: 0x216A,
  20612. Emacron: 0x0112,
  20613. Emacronacute: 0x1E16,
  20614. Emacrongrave: 0x1E14,
  20615. Emcyrillic: 0x041C,
  20616. Emonospace: 0xFF25,
  20617. Encyrillic: 0x041D,
  20618. Endescendercyrillic: 0x04A2,
  20619. Eng: 0x014A,
  20620. Enghecyrillic: 0x04A4,
  20621. Enhookcyrillic: 0x04C7,
  20622. Eogonek: 0x0118,
  20623. Eopen: 0x0190,
  20624. Epsilon: 0x0395,
  20625. Epsilontonos: 0x0388,
  20626. Ercyrillic: 0x0420,
  20627. Ereversed: 0x018E,
  20628. Ereversedcyrillic: 0x042D,
  20629. Escyrillic: 0x0421,
  20630. Esdescendercyrillic: 0x04AA,
  20631. Esh: 0x01A9,
  20632. Esmall: 0xF765,
  20633. Eta: 0x0397,
  20634. Etarmenian: 0x0538,
  20635. Etatonos: 0x0389,
  20636. Eth: 0x00D0,
  20637. Ethsmall: 0xF7F0,
  20638. Etilde: 0x1EBC,
  20639. Etildebelow: 0x1E1A,
  20640. Euro: 0x20AC,
  20641. Ezh: 0x01B7,
  20642. Ezhcaron: 0x01EE,
  20643. Ezhreversed: 0x01B8,
  20644. F: 0x0046,
  20645. Fcircle: 0x24BB,
  20646. Fdotaccent: 0x1E1E,
  20647. Feharmenian: 0x0556,
  20648. Feicoptic: 0x03E4,
  20649. Fhook: 0x0191,
  20650. Fitacyrillic: 0x0472,
  20651. Fiveroman: 0x2164,
  20652. Fmonospace: 0xFF26,
  20653. Fourroman: 0x2163,
  20654. Fsmall: 0xF766,
  20655. G: 0x0047,
  20656. GBsquare: 0x3387,
  20657. Gacute: 0x01F4,
  20658. Gamma: 0x0393,
  20659. Gammaafrican: 0x0194,
  20660. Gangiacoptic: 0x03EA,
  20661. Gbreve: 0x011E,
  20662. Gcaron: 0x01E6,
  20663. Gcedilla: 0x0122,
  20664. Gcircle: 0x24BC,
  20665. Gcircumflex: 0x011C,
  20666. Gcommaaccent: 0x0122,
  20667. Gdot: 0x0120,
  20668. Gdotaccent: 0x0120,
  20669. Gecyrillic: 0x0413,
  20670. Ghadarmenian: 0x0542,
  20671. Ghemiddlehookcyrillic: 0x0494,
  20672. Ghestrokecyrillic: 0x0492,
  20673. Gheupturncyrillic: 0x0490,
  20674. Ghook: 0x0193,
  20675. Gimarmenian: 0x0533,
  20676. Gjecyrillic: 0x0403,
  20677. Gmacron: 0x1E20,
  20678. Gmonospace: 0xFF27,
  20679. Grave: 0xF6CE,
  20680. Gravesmall: 0xF760,
  20681. Gsmall: 0xF767,
  20682. Gsmallhook: 0x029B,
  20683. Gstroke: 0x01E4,
  20684. H: 0x0048,
  20685. H18533: 0x25CF,
  20686. H18543: 0x25AA,
  20687. H18551: 0x25AB,
  20688. H22073: 0x25A1,
  20689. HPsquare: 0x33CB,
  20690. Haabkhasiancyrillic: 0x04A8,
  20691. Hadescendercyrillic: 0x04B2,
  20692. Hardsigncyrillic: 0x042A,
  20693. Hbar: 0x0126,
  20694. Hbrevebelow: 0x1E2A,
  20695. Hcedilla: 0x1E28,
  20696. Hcircle: 0x24BD,
  20697. Hcircumflex: 0x0124,
  20698. Hdieresis: 0x1E26,
  20699. Hdotaccent: 0x1E22,
  20700. Hdotbelow: 0x1E24,
  20701. Hmonospace: 0xFF28,
  20702. Hoarmenian: 0x0540,
  20703. Horicoptic: 0x03E8,
  20704. Hsmall: 0xF768,
  20705. Hungarumlaut: 0xF6CF,
  20706. Hungarumlautsmall: 0xF6F8,
  20707. Hzsquare: 0x3390,
  20708. I: 0x0049,
  20709. IAcyrillic: 0x042F,
  20710. IJ: 0x0132,
  20711. IUcyrillic: 0x042E,
  20712. Iacute: 0x00CD,
  20713. Iacutesmall: 0xF7ED,
  20714. Ibreve: 0x012C,
  20715. Icaron: 0x01CF,
  20716. Icircle: 0x24BE,
  20717. Icircumflex: 0x00CE,
  20718. Icircumflexsmall: 0xF7EE,
  20719. Icyrillic: 0x0406,
  20720. Idblgrave: 0x0208,
  20721. Idieresis: 0x00CF,
  20722. Idieresisacute: 0x1E2E,
  20723. Idieresiscyrillic: 0x04E4,
  20724. Idieresissmall: 0xF7EF,
  20725. Idot: 0x0130,
  20726. Idotaccent: 0x0130,
  20727. Idotbelow: 0x1ECA,
  20728. Iebrevecyrillic: 0x04D6,
  20729. Iecyrillic: 0x0415,
  20730. Ifraktur: 0x2111,
  20731. Igrave: 0x00CC,
  20732. Igravesmall: 0xF7EC,
  20733. Ihookabove: 0x1EC8,
  20734. Iicyrillic: 0x0418,
  20735. Iinvertedbreve: 0x020A,
  20736. Iishortcyrillic: 0x0419,
  20737. Imacron: 0x012A,
  20738. Imacroncyrillic: 0x04E2,
  20739. Imonospace: 0xFF29,
  20740. Iniarmenian: 0x053B,
  20741. Iocyrillic: 0x0401,
  20742. Iogonek: 0x012E,
  20743. Iota: 0x0399,
  20744. Iotaafrican: 0x0196,
  20745. Iotadieresis: 0x03AA,
  20746. Iotatonos: 0x038A,
  20747. Ismall: 0xF769,
  20748. Istroke: 0x0197,
  20749. Itilde: 0x0128,
  20750. Itildebelow: 0x1E2C,
  20751. Izhitsacyrillic: 0x0474,
  20752. Izhitsadblgravecyrillic: 0x0476,
  20753. J: 0x004A,
  20754. Jaarmenian: 0x0541,
  20755. Jcircle: 0x24BF,
  20756. Jcircumflex: 0x0134,
  20757. Jecyrillic: 0x0408,
  20758. Jheharmenian: 0x054B,
  20759. Jmonospace: 0xFF2A,
  20760. Jsmall: 0xF76A,
  20761. K: 0x004B,
  20762. KBsquare: 0x3385,
  20763. KKsquare: 0x33CD,
  20764. Kabashkircyrillic: 0x04A0,
  20765. Kacute: 0x1E30,
  20766. Kacyrillic: 0x041A,
  20767. Kadescendercyrillic: 0x049A,
  20768. Kahookcyrillic: 0x04C3,
  20769. Kappa: 0x039A,
  20770. Kastrokecyrillic: 0x049E,
  20771. Kaverticalstrokecyrillic: 0x049C,
  20772. Kcaron: 0x01E8,
  20773. Kcedilla: 0x0136,
  20774. Kcircle: 0x24C0,
  20775. Kcommaaccent: 0x0136,
  20776. Kdotbelow: 0x1E32,
  20777. Keharmenian: 0x0554,
  20778. Kenarmenian: 0x053F,
  20779. Khacyrillic: 0x0425,
  20780. Kheicoptic: 0x03E6,
  20781. Khook: 0x0198,
  20782. Kjecyrillic: 0x040C,
  20783. Klinebelow: 0x1E34,
  20784. Kmonospace: 0xFF2B,
  20785. Koppacyrillic: 0x0480,
  20786. Koppagreek: 0x03DE,
  20787. Ksicyrillic: 0x046E,
  20788. Ksmall: 0xF76B,
  20789. L: 0x004C,
  20790. LJ: 0x01C7,
  20791. LL: 0xF6BF,
  20792. Lacute: 0x0139,
  20793. Lambda: 0x039B,
  20794. Lcaron: 0x013D,
  20795. Lcedilla: 0x013B,
  20796. Lcircle: 0x24C1,
  20797. Lcircumflexbelow: 0x1E3C,
  20798. Lcommaaccent: 0x013B,
  20799. Ldot: 0x013F,
  20800. Ldotaccent: 0x013F,
  20801. Ldotbelow: 0x1E36,
  20802. Ldotbelowmacron: 0x1E38,
  20803. Liwnarmenian: 0x053C,
  20804. Lj: 0x01C8,
  20805. Ljecyrillic: 0x0409,
  20806. Llinebelow: 0x1E3A,
  20807. Lmonospace: 0xFF2C,
  20808. Lslash: 0x0141,
  20809. Lslashsmall: 0xF6F9,
  20810. Lsmall: 0xF76C,
  20811. M: 0x004D,
  20812. MBsquare: 0x3386,
  20813. Macron: 0xF6D0,
  20814. Macronsmall: 0xF7AF,
  20815. Macute: 0x1E3E,
  20816. Mcircle: 0x24C2,
  20817. Mdotaccent: 0x1E40,
  20818. Mdotbelow: 0x1E42,
  20819. Menarmenian: 0x0544,
  20820. Mmonospace: 0xFF2D,
  20821. Msmall: 0xF76D,
  20822. Mturned: 0x019C,
  20823. Mu: 0x039C,
  20824. N: 0x004E,
  20825. NJ: 0x01CA,
  20826. Nacute: 0x0143,
  20827. Ncaron: 0x0147,
  20828. Ncedilla: 0x0145,
  20829. Ncircle: 0x24C3,
  20830. Ncircumflexbelow: 0x1E4A,
  20831. Ncommaaccent: 0x0145,
  20832. Ndotaccent: 0x1E44,
  20833. Ndotbelow: 0x1E46,
  20834. Nhookleft: 0x019D,
  20835. Nineroman: 0x2168,
  20836. Nj: 0x01CB,
  20837. Njecyrillic: 0x040A,
  20838. Nlinebelow: 0x1E48,
  20839. Nmonospace: 0xFF2E,
  20840. Nowarmenian: 0x0546,
  20841. Nsmall: 0xF76E,
  20842. Ntilde: 0x00D1,
  20843. Ntildesmall: 0xF7F1,
  20844. Nu: 0x039D,
  20845. O: 0x004F,
  20846. OE: 0x0152,
  20847. OEsmall: 0xF6FA,
  20848. Oacute: 0x00D3,
  20849. Oacutesmall: 0xF7F3,
  20850. Obarredcyrillic: 0x04E8,
  20851. Obarreddieresiscyrillic: 0x04EA,
  20852. Obreve: 0x014E,
  20853. Ocaron: 0x01D1,
  20854. Ocenteredtilde: 0x019F,
  20855. Ocircle: 0x24C4,
  20856. Ocircumflex: 0x00D4,
  20857. Ocircumflexacute: 0x1ED0,
  20858. Ocircumflexdotbelow: 0x1ED8,
  20859. Ocircumflexgrave: 0x1ED2,
  20860. Ocircumflexhookabove: 0x1ED4,
  20861. Ocircumflexsmall: 0xF7F4,
  20862. Ocircumflextilde: 0x1ED6,
  20863. Ocyrillic: 0x041E,
  20864. Odblacute: 0x0150,
  20865. Odblgrave: 0x020C,
  20866. Odieresis: 0x00D6,
  20867. Odieresiscyrillic: 0x04E6,
  20868. Odieresissmall: 0xF7F6,
  20869. Odotbelow: 0x1ECC,
  20870. Ogoneksmall: 0xF6FB,
  20871. Ograve: 0x00D2,
  20872. Ogravesmall: 0xF7F2,
  20873. Oharmenian: 0x0555,
  20874. Ohm: 0x2126,
  20875. Ohookabove: 0x1ECE,
  20876. Ohorn: 0x01A0,
  20877. Ohornacute: 0x1EDA,
  20878. Ohorndotbelow: 0x1EE2,
  20879. Ohorngrave: 0x1EDC,
  20880. Ohornhookabove: 0x1EDE,
  20881. Ohorntilde: 0x1EE0,
  20882. Ohungarumlaut: 0x0150,
  20883. Oi: 0x01A2,
  20884. Oinvertedbreve: 0x020E,
  20885. Omacron: 0x014C,
  20886. Omacronacute: 0x1E52,
  20887. Omacrongrave: 0x1E50,
  20888. Omega: 0x2126,
  20889. Omegacyrillic: 0x0460,
  20890. Omegagreek: 0x03A9,
  20891. Omegaroundcyrillic: 0x047A,
  20892. Omegatitlocyrillic: 0x047C,
  20893. Omegatonos: 0x038F,
  20894. Omicron: 0x039F,
  20895. Omicrontonos: 0x038C,
  20896. Omonospace: 0xFF2F,
  20897. Oneroman: 0x2160,
  20898. Oogonek: 0x01EA,
  20899. Oogonekmacron: 0x01EC,
  20900. Oopen: 0x0186,
  20901. Oslash: 0x00D8,
  20902. Oslashacute: 0x01FE,
  20903. Oslashsmall: 0xF7F8,
  20904. Osmall: 0xF76F,
  20905. Ostrokeacute: 0x01FE,
  20906. Otcyrillic: 0x047E,
  20907. Otilde: 0x00D5,
  20908. Otildeacute: 0x1E4C,
  20909. Otildedieresis: 0x1E4E,
  20910. Otildesmall: 0xF7F5,
  20911. P: 0x0050,
  20912. Pacute: 0x1E54,
  20913. Pcircle: 0x24C5,
  20914. Pdotaccent: 0x1E56,
  20915. Pecyrillic: 0x041F,
  20916. Peharmenian: 0x054A,
  20917. Pemiddlehookcyrillic: 0x04A6,
  20918. Phi: 0x03A6,
  20919. Phook: 0x01A4,
  20920. Pi: 0x03A0,
  20921. Piwrarmenian: 0x0553,
  20922. Pmonospace: 0xFF30,
  20923. Psi: 0x03A8,
  20924. Psicyrillic: 0x0470,
  20925. Psmall: 0xF770,
  20926. Q: 0x0051,
  20927. Qcircle: 0x24C6,
  20928. Qmonospace: 0xFF31,
  20929. Qsmall: 0xF771,
  20930. R: 0x0052,
  20931. Raarmenian: 0x054C,
  20932. Racute: 0x0154,
  20933. Rcaron: 0x0158,
  20934. Rcedilla: 0x0156,
  20935. Rcircle: 0x24C7,
  20936. Rcommaaccent: 0x0156,
  20937. Rdblgrave: 0x0210,
  20938. Rdotaccent: 0x1E58,
  20939. Rdotbelow: 0x1E5A,
  20940. Rdotbelowmacron: 0x1E5C,
  20941. Reharmenian: 0x0550,
  20942. Rfraktur: 0x211C,
  20943. Rho: 0x03A1,
  20944. Ringsmall: 0xF6FC,
  20945. Rinvertedbreve: 0x0212,
  20946. Rlinebelow: 0x1E5E,
  20947. Rmonospace: 0xFF32,
  20948. Rsmall: 0xF772,
  20949. Rsmallinverted: 0x0281,
  20950. Rsmallinvertedsuperior: 0x02B6,
  20951. S: 0x0053,
  20952. SF010000: 0x250C,
  20953. SF020000: 0x2514,
  20954. SF030000: 0x2510,
  20955. SF040000: 0x2518,
  20956. SF050000: 0x253C,
  20957. SF060000: 0x252C,
  20958. SF070000: 0x2534,
  20959. SF080000: 0x251C,
  20960. SF090000: 0x2524,
  20961. SF100000: 0x2500,
  20962. SF110000: 0x2502,
  20963. SF190000: 0x2561,
  20964. SF200000: 0x2562,
  20965. SF210000: 0x2556,
  20966. SF220000: 0x2555,
  20967. SF230000: 0x2563,
  20968. SF240000: 0x2551,
  20969. SF250000: 0x2557,
  20970. SF260000: 0x255D,
  20971. SF270000: 0x255C,
  20972. SF280000: 0x255B,
  20973. SF360000: 0x255E,
  20974. SF370000: 0x255F,
  20975. SF380000: 0x255A,
  20976. SF390000: 0x2554,
  20977. SF400000: 0x2569,
  20978. SF410000: 0x2566,
  20979. SF420000: 0x2560,
  20980. SF430000: 0x2550,
  20981. SF440000: 0x256C,
  20982. SF450000: 0x2567,
  20983. SF460000: 0x2568,
  20984. SF470000: 0x2564,
  20985. SF480000: 0x2565,
  20986. SF490000: 0x2559,
  20987. SF500000: 0x2558,
  20988. SF510000: 0x2552,
  20989. SF520000: 0x2553,
  20990. SF530000: 0x256B,
  20991. SF540000: 0x256A,
  20992. Sacute: 0x015A,
  20993. Sacutedotaccent: 0x1E64,
  20994. Sampigreek: 0x03E0,
  20995. Scaron: 0x0160,
  20996. Scarondotaccent: 0x1E66,
  20997. Scaronsmall: 0xF6FD,
  20998. Scedilla: 0x015E,
  20999. Schwa: 0x018F,
  21000. Schwacyrillic: 0x04D8,
  21001. Schwadieresiscyrillic: 0x04DA,
  21002. Scircle: 0x24C8,
  21003. Scircumflex: 0x015C,
  21004. Scommaaccent: 0x0218,
  21005. Sdotaccent: 0x1E60,
  21006. Sdotbelow: 0x1E62,
  21007. Sdotbelowdotaccent: 0x1E68,
  21008. Seharmenian: 0x054D,
  21009. Sevenroman: 0x2166,
  21010. Shaarmenian: 0x0547,
  21011. Shacyrillic: 0x0428,
  21012. Shchacyrillic: 0x0429,
  21013. Sheicoptic: 0x03E2,
  21014. Shhacyrillic: 0x04BA,
  21015. Shimacoptic: 0x03EC,
  21016. Sigma: 0x03A3,
  21017. Sixroman: 0x2165,
  21018. Smonospace: 0xFF33,
  21019. Softsigncyrillic: 0x042C,
  21020. Ssmall: 0xF773,
  21021. Stigmagreek: 0x03DA,
  21022. T: 0x0054,
  21023. Tau: 0x03A4,
  21024. Tbar: 0x0166,
  21025. Tcaron: 0x0164,
  21026. Tcedilla: 0x0162,
  21027. Tcircle: 0x24C9,
  21028. Tcircumflexbelow: 0x1E70,
  21029. Tcommaaccent: 0x0162,
  21030. Tdotaccent: 0x1E6A,
  21031. Tdotbelow: 0x1E6C,
  21032. Tecyrillic: 0x0422,
  21033. Tedescendercyrillic: 0x04AC,
  21034. Tenroman: 0x2169,
  21035. Tetsecyrillic: 0x04B4,
  21036. Theta: 0x0398,
  21037. Thook: 0x01AC,
  21038. Thorn: 0x00DE,
  21039. Thornsmall: 0xF7FE,
  21040. Threeroman: 0x2162,
  21041. Tildesmall: 0xF6FE,
  21042. Tiwnarmenian: 0x054F,
  21043. Tlinebelow: 0x1E6E,
  21044. Tmonospace: 0xFF34,
  21045. Toarmenian: 0x0539,
  21046. Tonefive: 0x01BC,
  21047. Tonesix: 0x0184,
  21048. Tonetwo: 0x01A7,
  21049. Tretroflexhook: 0x01AE,
  21050. Tsecyrillic: 0x0426,
  21051. Tshecyrillic: 0x040B,
  21052. Tsmall: 0xF774,
  21053. Twelveroman: 0x216B,
  21054. Tworoman: 0x2161,
  21055. U: 0x0055,
  21056. Uacute: 0x00DA,
  21057. Uacutesmall: 0xF7FA,
  21058. Ubreve: 0x016C,
  21059. Ucaron: 0x01D3,
  21060. Ucircle: 0x24CA,
  21061. Ucircumflex: 0x00DB,
  21062. Ucircumflexbelow: 0x1E76,
  21063. Ucircumflexsmall: 0xF7FB,
  21064. Ucyrillic: 0x0423,
  21065. Udblacute: 0x0170,
  21066. Udblgrave: 0x0214,
  21067. Udieresis: 0x00DC,
  21068. Udieresisacute: 0x01D7,
  21069. Udieresisbelow: 0x1E72,
  21070. Udieresiscaron: 0x01D9,
  21071. Udieresiscyrillic: 0x04F0,
  21072. Udieresisgrave: 0x01DB,
  21073. Udieresismacron: 0x01D5,
  21074. Udieresissmall: 0xF7FC,
  21075. Udotbelow: 0x1EE4,
  21076. Ugrave: 0x00D9,
  21077. Ugravesmall: 0xF7F9,
  21078. Uhookabove: 0x1EE6,
  21079. Uhorn: 0x01AF,
  21080. Uhornacute: 0x1EE8,
  21081. Uhorndotbelow: 0x1EF0,
  21082. Uhorngrave: 0x1EEA,
  21083. Uhornhookabove: 0x1EEC,
  21084. Uhorntilde: 0x1EEE,
  21085. Uhungarumlaut: 0x0170,
  21086. Uhungarumlautcyrillic: 0x04F2,
  21087. Uinvertedbreve: 0x0216,
  21088. Ukcyrillic: 0x0478,
  21089. Umacron: 0x016A,
  21090. Umacroncyrillic: 0x04EE,
  21091. Umacrondieresis: 0x1E7A,
  21092. Umonospace: 0xFF35,
  21093. Uogonek: 0x0172,
  21094. Upsilon: 0x03A5,
  21095. Upsilon1: 0x03D2,
  21096. Upsilonacutehooksymbolgreek: 0x03D3,
  21097. Upsilonafrican: 0x01B1,
  21098. Upsilondieresis: 0x03AB,
  21099. Upsilondieresishooksymbolgreek: 0x03D4,
  21100. Upsilonhooksymbol: 0x03D2,
  21101. Upsilontonos: 0x038E,
  21102. Uring: 0x016E,
  21103. Ushortcyrillic: 0x040E,
  21104. Usmall: 0xF775,
  21105. Ustraightcyrillic: 0x04AE,
  21106. Ustraightstrokecyrillic: 0x04B0,
  21107. Utilde: 0x0168,
  21108. Utildeacute: 0x1E78,
  21109. Utildebelow: 0x1E74,
  21110. V: 0x0056,
  21111. Vcircle: 0x24CB,
  21112. Vdotbelow: 0x1E7E,
  21113. Vecyrillic: 0x0412,
  21114. Vewarmenian: 0x054E,
  21115. Vhook: 0x01B2,
  21116. Vmonospace: 0xFF36,
  21117. Voarmenian: 0x0548,
  21118. Vsmall: 0xF776,
  21119. Vtilde: 0x1E7C,
  21120. W: 0x0057,
  21121. Wacute: 0x1E82,
  21122. Wcircle: 0x24CC,
  21123. Wcircumflex: 0x0174,
  21124. Wdieresis: 0x1E84,
  21125. Wdotaccent: 0x1E86,
  21126. Wdotbelow: 0x1E88,
  21127. Wgrave: 0x1E80,
  21128. Wmonospace: 0xFF37,
  21129. Wsmall: 0xF777,
  21130. X: 0x0058,
  21131. Xcircle: 0x24CD,
  21132. Xdieresis: 0x1E8C,
  21133. Xdotaccent: 0x1E8A,
  21134. Xeharmenian: 0x053D,
  21135. Xi: 0x039E,
  21136. Xmonospace: 0xFF38,
  21137. Xsmall: 0xF778,
  21138. Y: 0x0059,
  21139. Yacute: 0x00DD,
  21140. Yacutesmall: 0xF7FD,
  21141. Yatcyrillic: 0x0462,
  21142. Ycircle: 0x24CE,
  21143. Ycircumflex: 0x0176,
  21144. Ydieresis: 0x0178,
  21145. Ydieresissmall: 0xF7FF,
  21146. Ydotaccent: 0x1E8E,
  21147. Ydotbelow: 0x1EF4,
  21148. Yericyrillic: 0x042B,
  21149. Yerudieresiscyrillic: 0x04F8,
  21150. Ygrave: 0x1EF2,
  21151. Yhook: 0x01B3,
  21152. Yhookabove: 0x1EF6,
  21153. Yiarmenian: 0x0545,
  21154. Yicyrillic: 0x0407,
  21155. Yiwnarmenian: 0x0552,
  21156. Ymonospace: 0xFF39,
  21157. Ysmall: 0xF779,
  21158. Ytilde: 0x1EF8,
  21159. Yusbigcyrillic: 0x046A,
  21160. Yusbigiotifiedcyrillic: 0x046C,
  21161. Yuslittlecyrillic: 0x0466,
  21162. Yuslittleiotifiedcyrillic: 0x0468,
  21163. Z: 0x005A,
  21164. Zaarmenian: 0x0536,
  21165. Zacute: 0x0179,
  21166. Zcaron: 0x017D,
  21167. Zcaronsmall: 0xF6FF,
  21168. Zcircle: 0x24CF,
  21169. Zcircumflex: 0x1E90,
  21170. Zdot: 0x017B,
  21171. Zdotaccent: 0x017B,
  21172. Zdotbelow: 0x1E92,
  21173. Zecyrillic: 0x0417,
  21174. Zedescendercyrillic: 0x0498,
  21175. Zedieresiscyrillic: 0x04DE,
  21176. Zeta: 0x0396,
  21177. Zhearmenian: 0x053A,
  21178. Zhebrevecyrillic: 0x04C1,
  21179. Zhecyrillic: 0x0416,
  21180. Zhedescendercyrillic: 0x0496,
  21181. Zhedieresiscyrillic: 0x04DC,
  21182. Zlinebelow: 0x1E94,
  21183. Zmonospace: 0xFF3A,
  21184. Zsmall: 0xF77A,
  21185. Zstroke: 0x01B5,
  21186. a: 0x0061,
  21187. aabengali: 0x0986,
  21188. aacute: 0x00E1,
  21189. aadeva: 0x0906,
  21190. aagujarati: 0x0A86,
  21191. aagurmukhi: 0x0A06,
  21192. aamatragurmukhi: 0x0A3E,
  21193. aarusquare: 0x3303,
  21194. aavowelsignbengali: 0x09BE,
  21195. aavowelsigndeva: 0x093E,
  21196. aavowelsigngujarati: 0x0ABE,
  21197. abbreviationmarkarmenian: 0x055F,
  21198. abbreviationsigndeva: 0x0970,
  21199. abengali: 0x0985,
  21200. abopomofo: 0x311A,
  21201. abreve: 0x0103,
  21202. abreveacute: 0x1EAF,
  21203. abrevecyrillic: 0x04D1,
  21204. abrevedotbelow: 0x1EB7,
  21205. abrevegrave: 0x1EB1,
  21206. abrevehookabove: 0x1EB3,
  21207. abrevetilde: 0x1EB5,
  21208. acaron: 0x01CE,
  21209. acircle: 0x24D0,
  21210. acircumflex: 0x00E2,
  21211. acircumflexacute: 0x1EA5,
  21212. acircumflexdotbelow: 0x1EAD,
  21213. acircumflexgrave: 0x1EA7,
  21214. acircumflexhookabove: 0x1EA9,
  21215. acircumflextilde: 0x1EAB,
  21216. acute: 0x00B4,
  21217. acutebelowcmb: 0x0317,
  21218. acutecmb: 0x0301,
  21219. acutecomb: 0x0301,
  21220. acutedeva: 0x0954,
  21221. acutelowmod: 0x02CF,
  21222. acutetonecmb: 0x0341,
  21223. acyrillic: 0x0430,
  21224. adblgrave: 0x0201,
  21225. addakgurmukhi: 0x0A71,
  21226. adeva: 0x0905,
  21227. adieresis: 0x00E4,
  21228. adieresiscyrillic: 0x04D3,
  21229. adieresismacron: 0x01DF,
  21230. adotbelow: 0x1EA1,
  21231. adotmacron: 0x01E1,
  21232. ae: 0x00E6,
  21233. aeacute: 0x01FD,
  21234. aekorean: 0x3150,
  21235. aemacron: 0x01E3,
  21236. afii00208: 0x2015,
  21237. afii08941: 0x20A4,
  21238. afii10017: 0x0410,
  21239. afii10018: 0x0411,
  21240. afii10019: 0x0412,
  21241. afii10020: 0x0413,
  21242. afii10021: 0x0414,
  21243. afii10022: 0x0415,
  21244. afii10023: 0x0401,
  21245. afii10024: 0x0416,
  21246. afii10025: 0x0417,
  21247. afii10026: 0x0418,
  21248. afii10027: 0x0419,
  21249. afii10028: 0x041A,
  21250. afii10029: 0x041B,
  21251. afii10030: 0x041C,
  21252. afii10031: 0x041D,
  21253. afii10032: 0x041E,
  21254. afii10033: 0x041F,
  21255. afii10034: 0x0420,
  21256. afii10035: 0x0421,
  21257. afii10036: 0x0422,
  21258. afii10037: 0x0423,
  21259. afii10038: 0x0424,
  21260. afii10039: 0x0425,
  21261. afii10040: 0x0426,
  21262. afii10041: 0x0427,
  21263. afii10042: 0x0428,
  21264. afii10043: 0x0429,
  21265. afii10044: 0x042A,
  21266. afii10045: 0x042B,
  21267. afii10046: 0x042C,
  21268. afii10047: 0x042D,
  21269. afii10048: 0x042E,
  21270. afii10049: 0x042F,
  21271. afii10050: 0x0490,
  21272. afii10051: 0x0402,
  21273. afii10052: 0x0403,
  21274. afii10053: 0x0404,
  21275. afii10054: 0x0405,
  21276. afii10055: 0x0406,
  21277. afii10056: 0x0407,
  21278. afii10057: 0x0408,
  21279. afii10058: 0x0409,
  21280. afii10059: 0x040A,
  21281. afii10060: 0x040B,
  21282. afii10061: 0x040C,
  21283. afii10062: 0x040E,
  21284. afii10063: 0xF6C4,
  21285. afii10064: 0xF6C5,
  21286. afii10065: 0x0430,
  21287. afii10066: 0x0431,
  21288. afii10067: 0x0432,
  21289. afii10068: 0x0433,
  21290. afii10069: 0x0434,
  21291. afii10070: 0x0435,
  21292. afii10071: 0x0451,
  21293. afii10072: 0x0436,
  21294. afii10073: 0x0437,
  21295. afii10074: 0x0438,
  21296. afii10075: 0x0439,
  21297. afii10076: 0x043A,
  21298. afii10077: 0x043B,
  21299. afii10078: 0x043C,
  21300. afii10079: 0x043D,
  21301. afii10080: 0x043E,
  21302. afii10081: 0x043F,
  21303. afii10082: 0x0440,
  21304. afii10083: 0x0441,
  21305. afii10084: 0x0442,
  21306. afii10085: 0x0443,
  21307. afii10086: 0x0444,
  21308. afii10087: 0x0445,
  21309. afii10088: 0x0446,
  21310. afii10089: 0x0447,
  21311. afii10090: 0x0448,
  21312. afii10091: 0x0449,
  21313. afii10092: 0x044A,
  21314. afii10093: 0x044B,
  21315. afii10094: 0x044C,
  21316. afii10095: 0x044D,
  21317. afii10096: 0x044E,
  21318. afii10097: 0x044F,
  21319. afii10098: 0x0491,
  21320. afii10099: 0x0452,
  21321. afii10100: 0x0453,
  21322. afii10101: 0x0454,
  21323. afii10102: 0x0455,
  21324. afii10103: 0x0456,
  21325. afii10104: 0x0457,
  21326. afii10105: 0x0458,
  21327. afii10106: 0x0459,
  21328. afii10107: 0x045A,
  21329. afii10108: 0x045B,
  21330. afii10109: 0x045C,
  21331. afii10110: 0x045E,
  21332. afii10145: 0x040F,
  21333. afii10146: 0x0462,
  21334. afii10147: 0x0472,
  21335. afii10148: 0x0474,
  21336. afii10192: 0xF6C6,
  21337. afii10193: 0x045F,
  21338. afii10194: 0x0463,
  21339. afii10195: 0x0473,
  21340. afii10196: 0x0475,
  21341. afii10831: 0xF6C7,
  21342. afii10832: 0xF6C8,
  21343. afii10846: 0x04D9,
  21344. afii299: 0x200E,
  21345. afii300: 0x200F,
  21346. afii301: 0x200D,
  21347. afii57381: 0x066A,
  21348. afii57388: 0x060C,
  21349. afii57392: 0x0660,
  21350. afii57393: 0x0661,
  21351. afii57394: 0x0662,
  21352. afii57395: 0x0663,
  21353. afii57396: 0x0664,
  21354. afii57397: 0x0665,
  21355. afii57398: 0x0666,
  21356. afii57399: 0x0667,
  21357. afii57400: 0x0668,
  21358. afii57401: 0x0669,
  21359. afii57403: 0x061B,
  21360. afii57407: 0x061F,
  21361. afii57409: 0x0621,
  21362. afii57410: 0x0622,
  21363. afii57411: 0x0623,
  21364. afii57412: 0x0624,
  21365. afii57413: 0x0625,
  21366. afii57414: 0x0626,
  21367. afii57415: 0x0627,
  21368. afii57416: 0x0628,
  21369. afii57417: 0x0629,
  21370. afii57418: 0x062A,
  21371. afii57419: 0x062B,
  21372. afii57420: 0x062C,
  21373. afii57421: 0x062D,
  21374. afii57422: 0x062E,
  21375. afii57423: 0x062F,
  21376. afii57424: 0x0630,
  21377. afii57425: 0x0631,
  21378. afii57426: 0x0632,
  21379. afii57427: 0x0633,
  21380. afii57428: 0x0634,
  21381. afii57429: 0x0635,
  21382. afii57430: 0x0636,
  21383. afii57431: 0x0637,
  21384. afii57432: 0x0638,
  21385. afii57433: 0x0639,
  21386. afii57434: 0x063A,
  21387. afii57440: 0x0640,
  21388. afii57441: 0x0641,
  21389. afii57442: 0x0642,
  21390. afii57443: 0x0643,
  21391. afii57444: 0x0644,
  21392. afii57445: 0x0645,
  21393. afii57446: 0x0646,
  21394. afii57448: 0x0648,
  21395. afii57449: 0x0649,
  21396. afii57450: 0x064A,
  21397. afii57451: 0x064B,
  21398. afii57452: 0x064C,
  21399. afii57453: 0x064D,
  21400. afii57454: 0x064E,
  21401. afii57455: 0x064F,
  21402. afii57456: 0x0650,
  21403. afii57457: 0x0651,
  21404. afii57458: 0x0652,
  21405. afii57470: 0x0647,
  21406. afii57505: 0x06A4,
  21407. afii57506: 0x067E,
  21408. afii57507: 0x0686,
  21409. afii57508: 0x0698,
  21410. afii57509: 0x06AF,
  21411. afii57511: 0x0679,
  21412. afii57512: 0x0688,
  21413. afii57513: 0x0691,
  21414. afii57514: 0x06BA,
  21415. afii57519: 0x06D2,
  21416. afii57534: 0x06D5,
  21417. afii57636: 0x20AA,
  21418. afii57645: 0x05BE,
  21419. afii57658: 0x05C3,
  21420. afii57664: 0x05D0,
  21421. afii57665: 0x05D1,
  21422. afii57666: 0x05D2,
  21423. afii57667: 0x05D3,
  21424. afii57668: 0x05D4,
  21425. afii57669: 0x05D5,
  21426. afii57670: 0x05D6,
  21427. afii57671: 0x05D7,
  21428. afii57672: 0x05D8,
  21429. afii57673: 0x05D9,
  21430. afii57674: 0x05DA,
  21431. afii57675: 0x05DB,
  21432. afii57676: 0x05DC,
  21433. afii57677: 0x05DD,
  21434. afii57678: 0x05DE,
  21435. afii57679: 0x05DF,
  21436. afii57680: 0x05E0,
  21437. afii57681: 0x05E1,
  21438. afii57682: 0x05E2,
  21439. afii57683: 0x05E3,
  21440. afii57684: 0x05E4,
  21441. afii57685: 0x05E5,
  21442. afii57686: 0x05E6,
  21443. afii57687: 0x05E7,
  21444. afii57688: 0x05E8,
  21445. afii57689: 0x05E9,
  21446. afii57690: 0x05EA,
  21447. afii57694: 0xFB2A,
  21448. afii57695: 0xFB2B,
  21449. afii57700: 0xFB4B,
  21450. afii57705: 0xFB1F,
  21451. afii57716: 0x05F0,
  21452. afii57717: 0x05F1,
  21453. afii57718: 0x05F2,
  21454. afii57723: 0xFB35,
  21455. afii57793: 0x05B4,
  21456. afii57794: 0x05B5,
  21457. afii57795: 0x05B6,
  21458. afii57796: 0x05BB,
  21459. afii57797: 0x05B8,
  21460. afii57798: 0x05B7,
  21461. afii57799: 0x05B0,
  21462. afii57800: 0x05B2,
  21463. afii57801: 0x05B1,
  21464. afii57802: 0x05B3,
  21465. afii57803: 0x05C2,
  21466. afii57804: 0x05C1,
  21467. afii57806: 0x05B9,
  21468. afii57807: 0x05BC,
  21469. afii57839: 0x05BD,
  21470. afii57841: 0x05BF,
  21471. afii57842: 0x05C0,
  21472. afii57929: 0x02BC,
  21473. afii61248: 0x2105,
  21474. afii61289: 0x2113,
  21475. afii61352: 0x2116,
  21476. afii61573: 0x202C,
  21477. afii61574: 0x202D,
  21478. afii61575: 0x202E,
  21479. afii61664: 0x200C,
  21480. afii63167: 0x066D,
  21481. afii64937: 0x02BD,
  21482. agrave: 0x00E0,
  21483. agujarati: 0x0A85,
  21484. agurmukhi: 0x0A05,
  21485. ahiragana: 0x3042,
  21486. ahookabove: 0x1EA3,
  21487. aibengali: 0x0990,
  21488. aibopomofo: 0x311E,
  21489. aideva: 0x0910,
  21490. aiecyrillic: 0x04D5,
  21491. aigujarati: 0x0A90,
  21492. aigurmukhi: 0x0A10,
  21493. aimatragurmukhi: 0x0A48,
  21494. ainarabic: 0x0639,
  21495. ainfinalarabic: 0xFECA,
  21496. aininitialarabic: 0xFECB,
  21497. ainmedialarabic: 0xFECC,
  21498. ainvertedbreve: 0x0203,
  21499. aivowelsignbengali: 0x09C8,
  21500. aivowelsigndeva: 0x0948,
  21501. aivowelsigngujarati: 0x0AC8,
  21502. akatakana: 0x30A2,
  21503. akatakanahalfwidth: 0xFF71,
  21504. akorean: 0x314F,
  21505. alef: 0x05D0,
  21506. alefarabic: 0x0627,
  21507. alefdageshhebrew: 0xFB30,
  21508. aleffinalarabic: 0xFE8E,
  21509. alefhamzaabovearabic: 0x0623,
  21510. alefhamzaabovefinalarabic: 0xFE84,
  21511. alefhamzabelowarabic: 0x0625,
  21512. alefhamzabelowfinalarabic: 0xFE88,
  21513. alefhebrew: 0x05D0,
  21514. aleflamedhebrew: 0xFB4F,
  21515. alefmaddaabovearabic: 0x0622,
  21516. alefmaddaabovefinalarabic: 0xFE82,
  21517. alefmaksuraarabic: 0x0649,
  21518. alefmaksurafinalarabic: 0xFEF0,
  21519. alefmaksurainitialarabic: 0xFEF3,
  21520. alefmaksuramedialarabic: 0xFEF4,
  21521. alefpatahhebrew: 0xFB2E,
  21522. alefqamatshebrew: 0xFB2F,
  21523. aleph: 0x2135,
  21524. allequal: 0x224C,
  21525. alpha: 0x03B1,
  21526. alphatonos: 0x03AC,
  21527. amacron: 0x0101,
  21528. amonospace: 0xFF41,
  21529. ampersand: 0x0026,
  21530. ampersandmonospace: 0xFF06,
  21531. ampersandsmall: 0xF726,
  21532. amsquare: 0x33C2,
  21533. anbopomofo: 0x3122,
  21534. angbopomofo: 0x3124,
  21535. angbracketleft: 0x3008, // This glyph is missing from Adobe's original list.
  21536. angbracketright: 0x3009, // This glyph is missing from Adobe's original list.
  21537. angkhankhuthai: 0x0E5A,
  21538. angle: 0x2220,
  21539. anglebracketleft: 0x3008,
  21540. anglebracketleftvertical: 0xFE3F,
  21541. anglebracketright: 0x3009,
  21542. anglebracketrightvertical: 0xFE40,
  21543. angleleft: 0x2329,
  21544. angleright: 0x232A,
  21545. angstrom: 0x212B,
  21546. anoteleia: 0x0387,
  21547. anudattadeva: 0x0952,
  21548. anusvarabengali: 0x0982,
  21549. anusvaradeva: 0x0902,
  21550. anusvaragujarati: 0x0A82,
  21551. aogonek: 0x0105,
  21552. apaatosquare: 0x3300,
  21553. aparen: 0x249C,
  21554. apostrophearmenian: 0x055A,
  21555. apostrophemod: 0x02BC,
  21556. apple: 0xF8FF,
  21557. approaches: 0x2250,
  21558. approxequal: 0x2248,
  21559. approxequalorimage: 0x2252,
  21560. approximatelyequal: 0x2245,
  21561. araeaekorean: 0x318E,
  21562. araeakorean: 0x318D,
  21563. arc: 0x2312,
  21564. arighthalfring: 0x1E9A,
  21565. aring: 0x00E5,
  21566. aringacute: 0x01FB,
  21567. aringbelow: 0x1E01,
  21568. arrowboth: 0x2194,
  21569. arrowdashdown: 0x21E3,
  21570. arrowdashleft: 0x21E0,
  21571. arrowdashright: 0x21E2,
  21572. arrowdashup: 0x21E1,
  21573. arrowdblboth: 0x21D4,
  21574. arrowdbldown: 0x21D3,
  21575. arrowdblleft: 0x21D0,
  21576. arrowdblright: 0x21D2,
  21577. arrowdblup: 0x21D1,
  21578. arrowdown: 0x2193,
  21579. arrowdownleft: 0x2199,
  21580. arrowdownright: 0x2198,
  21581. arrowdownwhite: 0x21E9,
  21582. arrowheaddownmod: 0x02C5,
  21583. arrowheadleftmod: 0x02C2,
  21584. arrowheadrightmod: 0x02C3,
  21585. arrowheadupmod: 0x02C4,
  21586. arrowhorizex: 0xF8E7,
  21587. arrowleft: 0x2190,
  21588. arrowleftdbl: 0x21D0,
  21589. arrowleftdblstroke: 0x21CD,
  21590. arrowleftoverright: 0x21C6,
  21591. arrowleftwhite: 0x21E6,
  21592. arrowright: 0x2192,
  21593. arrowrightdblstroke: 0x21CF,
  21594. arrowrightheavy: 0x279E,
  21595. arrowrightoverleft: 0x21C4,
  21596. arrowrightwhite: 0x21E8,
  21597. arrowtableft: 0x21E4,
  21598. arrowtabright: 0x21E5,
  21599. arrowup: 0x2191,
  21600. arrowupdn: 0x2195,
  21601. arrowupdnbse: 0x21A8,
  21602. arrowupdownbase: 0x21A8,
  21603. arrowupleft: 0x2196,
  21604. arrowupleftofdown: 0x21C5,
  21605. arrowupright: 0x2197,
  21606. arrowupwhite: 0x21E7,
  21607. arrowvertex: 0xF8E6,
  21608. asciicircum: 0x005E,
  21609. asciicircummonospace: 0xFF3E,
  21610. asciitilde: 0x007E,
  21611. asciitildemonospace: 0xFF5E,
  21612. ascript: 0x0251,
  21613. ascriptturned: 0x0252,
  21614. asmallhiragana: 0x3041,
  21615. asmallkatakana: 0x30A1,
  21616. asmallkatakanahalfwidth: 0xFF67,
  21617. asterisk: 0x002A,
  21618. asteriskaltonearabic: 0x066D,
  21619. asteriskarabic: 0x066D,
  21620. asteriskmath: 0x2217,
  21621. asteriskmonospace: 0xFF0A,
  21622. asterisksmall: 0xFE61,
  21623. asterism: 0x2042,
  21624. asuperior: 0xF6E9,
  21625. asymptoticallyequal: 0x2243,
  21626. at: 0x0040,
  21627. atilde: 0x00E3,
  21628. atmonospace: 0xFF20,
  21629. atsmall: 0xFE6B,
  21630. aturned: 0x0250,
  21631. aubengali: 0x0994,
  21632. aubopomofo: 0x3120,
  21633. audeva: 0x0914,
  21634. augujarati: 0x0A94,
  21635. augurmukhi: 0x0A14,
  21636. aulengthmarkbengali: 0x09D7,
  21637. aumatragurmukhi: 0x0A4C,
  21638. auvowelsignbengali: 0x09CC,
  21639. auvowelsigndeva: 0x094C,
  21640. auvowelsigngujarati: 0x0ACC,
  21641. avagrahadeva: 0x093D,
  21642. aybarmenian: 0x0561,
  21643. ayin: 0x05E2,
  21644. ayinaltonehebrew: 0xFB20,
  21645. ayinhebrew: 0x05E2,
  21646. b: 0x0062,
  21647. babengali: 0x09AC,
  21648. backslash: 0x005C,
  21649. backslashmonospace: 0xFF3C,
  21650. badeva: 0x092C,
  21651. bagujarati: 0x0AAC,
  21652. bagurmukhi: 0x0A2C,
  21653. bahiragana: 0x3070,
  21654. bahtthai: 0x0E3F,
  21655. bakatakana: 0x30D0,
  21656. bar: 0x007C,
  21657. barmonospace: 0xFF5C,
  21658. bbopomofo: 0x3105,
  21659. bcircle: 0x24D1,
  21660. bdotaccent: 0x1E03,
  21661. bdotbelow: 0x1E05,
  21662. beamedsixteenthnotes: 0x266C,
  21663. because: 0x2235,
  21664. becyrillic: 0x0431,
  21665. beharabic: 0x0628,
  21666. behfinalarabic: 0xFE90,
  21667. behinitialarabic: 0xFE91,
  21668. behiragana: 0x3079,
  21669. behmedialarabic: 0xFE92,
  21670. behmeeminitialarabic: 0xFC9F,
  21671. behmeemisolatedarabic: 0xFC08,
  21672. behnoonfinalarabic: 0xFC6D,
  21673. bekatakana: 0x30D9,
  21674. benarmenian: 0x0562,
  21675. bet: 0x05D1,
  21676. beta: 0x03B2,
  21677. betasymbolgreek: 0x03D0,
  21678. betdagesh: 0xFB31,
  21679. betdageshhebrew: 0xFB31,
  21680. bethebrew: 0x05D1,
  21681. betrafehebrew: 0xFB4C,
  21682. bhabengali: 0x09AD,
  21683. bhadeva: 0x092D,
  21684. bhagujarati: 0x0AAD,
  21685. bhagurmukhi: 0x0A2D,
  21686. bhook: 0x0253,
  21687. bihiragana: 0x3073,
  21688. bikatakana: 0x30D3,
  21689. bilabialclick: 0x0298,
  21690. bindigurmukhi: 0x0A02,
  21691. birusquare: 0x3331,
  21692. blackcircle: 0x25CF,
  21693. blackdiamond: 0x25C6,
  21694. blackdownpointingtriangle: 0x25BC,
  21695. blackleftpointingpointer: 0x25C4,
  21696. blackleftpointingtriangle: 0x25C0,
  21697. blacklenticularbracketleft: 0x3010,
  21698. blacklenticularbracketleftvertical: 0xFE3B,
  21699. blacklenticularbracketright: 0x3011,
  21700. blacklenticularbracketrightvertical: 0xFE3C,
  21701. blacklowerlefttriangle: 0x25E3,
  21702. blacklowerrighttriangle: 0x25E2,
  21703. blackrectangle: 0x25AC,
  21704. blackrightpointingpointer: 0x25BA,
  21705. blackrightpointingtriangle: 0x25B6,
  21706. blacksmallsquare: 0x25AA,
  21707. blacksmilingface: 0x263B,
  21708. blacksquare: 0x25A0,
  21709. blackstar: 0x2605,
  21710. blackupperlefttriangle: 0x25E4,
  21711. blackupperrighttriangle: 0x25E5,
  21712. blackuppointingsmalltriangle: 0x25B4,
  21713. blackuppointingtriangle: 0x25B2,
  21714. blank: 0x2423,
  21715. blinebelow: 0x1E07,
  21716. block: 0x2588,
  21717. bmonospace: 0xFF42,
  21718. bobaimaithai: 0x0E1A,
  21719. bohiragana: 0x307C,
  21720. bokatakana: 0x30DC,
  21721. bparen: 0x249D,
  21722. bqsquare: 0x33C3,
  21723. braceex: 0xF8F4,
  21724. braceleft: 0x007B,
  21725. braceleftbt: 0xF8F3,
  21726. braceleftmid: 0xF8F2,
  21727. braceleftmonospace: 0xFF5B,
  21728. braceleftsmall: 0xFE5B,
  21729. bracelefttp: 0xF8F1,
  21730. braceleftvertical: 0xFE37,
  21731. braceright: 0x007D,
  21732. bracerightbt: 0xF8FE,
  21733. bracerightmid: 0xF8FD,
  21734. bracerightmonospace: 0xFF5D,
  21735. bracerightsmall: 0xFE5C,
  21736. bracerighttp: 0xF8FC,
  21737. bracerightvertical: 0xFE38,
  21738. bracketleft: 0x005B,
  21739. bracketleftbt: 0xF8F0,
  21740. bracketleftex: 0xF8EF,
  21741. bracketleftmonospace: 0xFF3B,
  21742. bracketlefttp: 0xF8EE,
  21743. bracketright: 0x005D,
  21744. bracketrightbt: 0xF8FB,
  21745. bracketrightex: 0xF8FA,
  21746. bracketrightmonospace: 0xFF3D,
  21747. bracketrighttp: 0xF8F9,
  21748. breve: 0x02D8,
  21749. brevebelowcmb: 0x032E,
  21750. brevecmb: 0x0306,
  21751. breveinvertedbelowcmb: 0x032F,
  21752. breveinvertedcmb: 0x0311,
  21753. breveinverteddoublecmb: 0x0361,
  21754. bridgebelowcmb: 0x032A,
  21755. bridgeinvertedbelowcmb: 0x033A,
  21756. brokenbar: 0x00A6,
  21757. bstroke: 0x0180,
  21758. bsuperior: 0xF6EA,
  21759. btopbar: 0x0183,
  21760. buhiragana: 0x3076,
  21761. bukatakana: 0x30D6,
  21762. bullet: 0x2022,
  21763. bulletinverse: 0x25D8,
  21764. bulletoperator: 0x2219,
  21765. bullseye: 0x25CE,
  21766. c: 0x0063,
  21767. caarmenian: 0x056E,
  21768. cabengali: 0x099A,
  21769. cacute: 0x0107,
  21770. cadeva: 0x091A,
  21771. cagujarati: 0x0A9A,
  21772. cagurmukhi: 0x0A1A,
  21773. calsquare: 0x3388,
  21774. candrabindubengali: 0x0981,
  21775. candrabinducmb: 0x0310,
  21776. candrabindudeva: 0x0901,
  21777. candrabindugujarati: 0x0A81,
  21778. capslock: 0x21EA,
  21779. careof: 0x2105,
  21780. caron: 0x02C7,
  21781. caronbelowcmb: 0x032C,
  21782. caroncmb: 0x030C,
  21783. carriagereturn: 0x21B5,
  21784. cbopomofo: 0x3118,
  21785. ccaron: 0x010D,
  21786. ccedilla: 0x00E7,
  21787. ccedillaacute: 0x1E09,
  21788. ccircle: 0x24D2,
  21789. ccircumflex: 0x0109,
  21790. ccurl: 0x0255,
  21791. cdot: 0x010B,
  21792. cdotaccent: 0x010B,
  21793. cdsquare: 0x33C5,
  21794. cedilla: 0x00B8,
  21795. cedillacmb: 0x0327,
  21796. cent: 0x00A2,
  21797. centigrade: 0x2103,
  21798. centinferior: 0xF6DF,
  21799. centmonospace: 0xFFE0,
  21800. centoldstyle: 0xF7A2,
  21801. centsuperior: 0xF6E0,
  21802. chaarmenian: 0x0579,
  21803. chabengali: 0x099B,
  21804. chadeva: 0x091B,
  21805. chagujarati: 0x0A9B,
  21806. chagurmukhi: 0x0A1B,
  21807. chbopomofo: 0x3114,
  21808. cheabkhasiancyrillic: 0x04BD,
  21809. checkmark: 0x2713,
  21810. checyrillic: 0x0447,
  21811. chedescenderabkhasiancyrillic: 0x04BF,
  21812. chedescendercyrillic: 0x04B7,
  21813. chedieresiscyrillic: 0x04F5,
  21814. cheharmenian: 0x0573,
  21815. chekhakassiancyrillic: 0x04CC,
  21816. cheverticalstrokecyrillic: 0x04B9,
  21817. chi: 0x03C7,
  21818. chieuchacirclekorean: 0x3277,
  21819. chieuchaparenkorean: 0x3217,
  21820. chieuchcirclekorean: 0x3269,
  21821. chieuchkorean: 0x314A,
  21822. chieuchparenkorean: 0x3209,
  21823. chochangthai: 0x0E0A,
  21824. chochanthai: 0x0E08,
  21825. chochingthai: 0x0E09,
  21826. chochoethai: 0x0E0C,
  21827. chook: 0x0188,
  21828. cieucacirclekorean: 0x3276,
  21829. cieucaparenkorean: 0x3216,
  21830. cieuccirclekorean: 0x3268,
  21831. cieuckorean: 0x3148,
  21832. cieucparenkorean: 0x3208,
  21833. cieucuparenkorean: 0x321C,
  21834. circle: 0x25CB,
  21835. circlecopyrt: 0x00A9, // This glyph is missing from Adobe's original list.
  21836. circlemultiply: 0x2297,
  21837. circleot: 0x2299,
  21838. circleplus: 0x2295,
  21839. circlepostalmark: 0x3036,
  21840. circlewithlefthalfblack: 0x25D0,
  21841. circlewithrighthalfblack: 0x25D1,
  21842. circumflex: 0x02C6,
  21843. circumflexbelowcmb: 0x032D,
  21844. circumflexcmb: 0x0302,
  21845. clear: 0x2327,
  21846. clickalveolar: 0x01C2,
  21847. clickdental: 0x01C0,
  21848. clicklateral: 0x01C1,
  21849. clickretroflex: 0x01C3,
  21850. club: 0x2663,
  21851. clubsuitblack: 0x2663,
  21852. clubsuitwhite: 0x2667,
  21853. cmcubedsquare: 0x33A4,
  21854. cmonospace: 0xFF43,
  21855. cmsquaredsquare: 0x33A0,
  21856. coarmenian: 0x0581,
  21857. colon: 0x003A,
  21858. colonmonetary: 0x20A1,
  21859. colonmonospace: 0xFF1A,
  21860. colonsign: 0x20A1,
  21861. colonsmall: 0xFE55,
  21862. colontriangularhalfmod: 0x02D1,
  21863. colontriangularmod: 0x02D0,
  21864. comma: 0x002C,
  21865. commaabovecmb: 0x0313,
  21866. commaaboverightcmb: 0x0315,
  21867. commaaccent: 0xF6C3,
  21868. commaarabic: 0x060C,
  21869. commaarmenian: 0x055D,
  21870. commainferior: 0xF6E1,
  21871. commamonospace: 0xFF0C,
  21872. commareversedabovecmb: 0x0314,
  21873. commareversedmod: 0x02BD,
  21874. commasmall: 0xFE50,
  21875. commasuperior: 0xF6E2,
  21876. commaturnedabovecmb: 0x0312,
  21877. commaturnedmod: 0x02BB,
  21878. compass: 0x263C,
  21879. congruent: 0x2245,
  21880. contourintegral: 0x222E,
  21881. control: 0x2303,
  21882. controlACK: 0x0006,
  21883. controlBEL: 0x0007,
  21884. controlBS: 0x0008,
  21885. controlCAN: 0x0018,
  21886. controlCR: 0x000D,
  21887. controlDC1: 0x0011,
  21888. controlDC2: 0x0012,
  21889. controlDC3: 0x0013,
  21890. controlDC4: 0x0014,
  21891. controlDEL: 0x007F,
  21892. controlDLE: 0x0010,
  21893. controlEM: 0x0019,
  21894. controlENQ: 0x0005,
  21895. controlEOT: 0x0004,
  21896. controlESC: 0x001B,
  21897. controlETB: 0x0017,
  21898. controlETX: 0x0003,
  21899. controlFF: 0x000C,
  21900. controlFS: 0x001C,
  21901. controlGS: 0x001D,
  21902. controlHT: 0x0009,
  21903. controlLF: 0x000A,
  21904. controlNAK: 0x0015,
  21905. controlRS: 0x001E,
  21906. controlSI: 0x000F,
  21907. controlSO: 0x000E,
  21908. controlSOT: 0x0002,
  21909. controlSTX: 0x0001,
  21910. controlSUB: 0x001A,
  21911. controlSYN: 0x0016,
  21912. controlUS: 0x001F,
  21913. controlVT: 0x000B,
  21914. copyright: 0x00A9,
  21915. copyrightsans: 0xF8E9,
  21916. copyrightserif: 0xF6D9,
  21917. cornerbracketleft: 0x300C,
  21918. cornerbracketlefthalfwidth: 0xFF62,
  21919. cornerbracketleftvertical: 0xFE41,
  21920. cornerbracketright: 0x300D,
  21921. cornerbracketrighthalfwidth: 0xFF63,
  21922. cornerbracketrightvertical: 0xFE42,
  21923. corporationsquare: 0x337F,
  21924. cosquare: 0x33C7,
  21925. coverkgsquare: 0x33C6,
  21926. cparen: 0x249E,
  21927. cruzeiro: 0x20A2,
  21928. cstretched: 0x0297,
  21929. curlyand: 0x22CF,
  21930. curlyor: 0x22CE,
  21931. currency: 0x00A4,
  21932. cyrBreve: 0xF6D1,
  21933. cyrFlex: 0xF6D2,
  21934. cyrbreve: 0xF6D4,
  21935. cyrflex: 0xF6D5,
  21936. d: 0x0064,
  21937. daarmenian: 0x0564,
  21938. dabengali: 0x09A6,
  21939. dadarabic: 0x0636,
  21940. dadeva: 0x0926,
  21941. dadfinalarabic: 0xFEBE,
  21942. dadinitialarabic: 0xFEBF,
  21943. dadmedialarabic: 0xFEC0,
  21944. dagesh: 0x05BC,
  21945. dageshhebrew: 0x05BC,
  21946. dagger: 0x2020,
  21947. daggerdbl: 0x2021,
  21948. dagujarati: 0x0AA6,
  21949. dagurmukhi: 0x0A26,
  21950. dahiragana: 0x3060,
  21951. dakatakana: 0x30C0,
  21952. dalarabic: 0x062F,
  21953. dalet: 0x05D3,
  21954. daletdagesh: 0xFB33,
  21955. daletdageshhebrew: 0xFB33,
  21956. dalethebrew: 0x05D3,
  21957. dalfinalarabic: 0xFEAA,
  21958. dammaarabic: 0x064F,
  21959. dammalowarabic: 0x064F,
  21960. dammatanaltonearabic: 0x064C,
  21961. dammatanarabic: 0x064C,
  21962. danda: 0x0964,
  21963. dargahebrew: 0x05A7,
  21964. dargalefthebrew: 0x05A7,
  21965. dasiapneumatacyrilliccmb: 0x0485,
  21966. dblGrave: 0xF6D3,
  21967. dblanglebracketleft: 0x300A,
  21968. dblanglebracketleftvertical: 0xFE3D,
  21969. dblanglebracketright: 0x300B,
  21970. dblanglebracketrightvertical: 0xFE3E,
  21971. dblarchinvertedbelowcmb: 0x032B,
  21972. dblarrowleft: 0x21D4,
  21973. dblarrowright: 0x21D2,
  21974. dbldanda: 0x0965,
  21975. dblgrave: 0xF6D6,
  21976. dblgravecmb: 0x030F,
  21977. dblintegral: 0x222C,
  21978. dbllowline: 0x2017,
  21979. dbllowlinecmb: 0x0333,
  21980. dbloverlinecmb: 0x033F,
  21981. dblprimemod: 0x02BA,
  21982. dblverticalbar: 0x2016,
  21983. dblverticallineabovecmb: 0x030E,
  21984. dbopomofo: 0x3109,
  21985. dbsquare: 0x33C8,
  21986. dcaron: 0x010F,
  21987. dcedilla: 0x1E11,
  21988. dcircle: 0x24D3,
  21989. dcircumflexbelow: 0x1E13,
  21990. dcroat: 0x0111,
  21991. ddabengali: 0x09A1,
  21992. ddadeva: 0x0921,
  21993. ddagujarati: 0x0AA1,
  21994. ddagurmukhi: 0x0A21,
  21995. ddalarabic: 0x0688,
  21996. ddalfinalarabic: 0xFB89,
  21997. dddhadeva: 0x095C,
  21998. ddhabengali: 0x09A2,
  21999. ddhadeva: 0x0922,
  22000. ddhagujarati: 0x0AA2,
  22001. ddhagurmukhi: 0x0A22,
  22002. ddotaccent: 0x1E0B,
  22003. ddotbelow: 0x1E0D,
  22004. decimalseparatorarabic: 0x066B,
  22005. decimalseparatorpersian: 0x066B,
  22006. decyrillic: 0x0434,
  22007. degree: 0x00B0,
  22008. dehihebrew: 0x05AD,
  22009. dehiragana: 0x3067,
  22010. deicoptic: 0x03EF,
  22011. dekatakana: 0x30C7,
  22012. deleteleft: 0x232B,
  22013. deleteright: 0x2326,
  22014. delta: 0x03B4,
  22015. deltaturned: 0x018D,
  22016. denominatorminusonenumeratorbengali: 0x09F8,
  22017. dezh: 0x02A4,
  22018. dhabengali: 0x09A7,
  22019. dhadeva: 0x0927,
  22020. dhagujarati: 0x0AA7,
  22021. dhagurmukhi: 0x0A27,
  22022. dhook: 0x0257,
  22023. dialytikatonos: 0x0385,
  22024. dialytikatonoscmb: 0x0344,
  22025. diamond: 0x2666,
  22026. diamondsuitwhite: 0x2662,
  22027. dieresis: 0x00A8,
  22028. dieresisacute: 0xF6D7,
  22029. dieresisbelowcmb: 0x0324,
  22030. dieresiscmb: 0x0308,
  22031. dieresisgrave: 0xF6D8,
  22032. dieresistonos: 0x0385,
  22033. dihiragana: 0x3062,
  22034. dikatakana: 0x30C2,
  22035. dittomark: 0x3003,
  22036. divide: 0x00F7,
  22037. divides: 0x2223,
  22038. divisionslash: 0x2215,
  22039. djecyrillic: 0x0452,
  22040. dkshade: 0x2593,
  22041. dlinebelow: 0x1E0F,
  22042. dlsquare: 0x3397,
  22043. dmacron: 0x0111,
  22044. dmonospace: 0xFF44,
  22045. dnblock: 0x2584,
  22046. dochadathai: 0x0E0E,
  22047. dodekthai: 0x0E14,
  22048. dohiragana: 0x3069,
  22049. dokatakana: 0x30C9,
  22050. dollar: 0x0024,
  22051. dollarinferior: 0xF6E3,
  22052. dollarmonospace: 0xFF04,
  22053. dollaroldstyle: 0xF724,
  22054. dollarsmall: 0xFE69,
  22055. dollarsuperior: 0xF6E4,
  22056. dong: 0x20AB,
  22057. dorusquare: 0x3326,
  22058. dotaccent: 0x02D9,
  22059. dotaccentcmb: 0x0307,
  22060. dotbelowcmb: 0x0323,
  22061. dotbelowcomb: 0x0323,
  22062. dotkatakana: 0x30FB,
  22063. dotlessi: 0x0131,
  22064. dotlessj: 0xF6BE,
  22065. dotlessjstrokehook: 0x0284,
  22066. dotmath: 0x22C5,
  22067. dottedcircle: 0x25CC,
  22068. doubleyodpatah: 0xFB1F,
  22069. doubleyodpatahhebrew: 0xFB1F,
  22070. downtackbelowcmb: 0x031E,
  22071. downtackmod: 0x02D5,
  22072. dparen: 0x249F,
  22073. dsuperior: 0xF6EB,
  22074. dtail: 0x0256,
  22075. dtopbar: 0x018C,
  22076. duhiragana: 0x3065,
  22077. dukatakana: 0x30C5,
  22078. dz: 0x01F3,
  22079. dzaltone: 0x02A3,
  22080. dzcaron: 0x01C6,
  22081. dzcurl: 0x02A5,
  22082. dzeabkhasiancyrillic: 0x04E1,
  22083. dzecyrillic: 0x0455,
  22084. dzhecyrillic: 0x045F,
  22085. e: 0x0065,
  22086. eacute: 0x00E9,
  22087. earth: 0x2641,
  22088. ebengali: 0x098F,
  22089. ebopomofo: 0x311C,
  22090. ebreve: 0x0115,
  22091. ecandradeva: 0x090D,
  22092. ecandragujarati: 0x0A8D,
  22093. ecandravowelsigndeva: 0x0945,
  22094. ecandravowelsigngujarati: 0x0AC5,
  22095. ecaron: 0x011B,
  22096. ecedillabreve: 0x1E1D,
  22097. echarmenian: 0x0565,
  22098. echyiwnarmenian: 0x0587,
  22099. ecircle: 0x24D4,
  22100. ecircumflex: 0x00EA,
  22101. ecircumflexacute: 0x1EBF,
  22102. ecircumflexbelow: 0x1E19,
  22103. ecircumflexdotbelow: 0x1EC7,
  22104. ecircumflexgrave: 0x1EC1,
  22105. ecircumflexhookabove: 0x1EC3,
  22106. ecircumflextilde: 0x1EC5,
  22107. ecyrillic: 0x0454,
  22108. edblgrave: 0x0205,
  22109. edeva: 0x090F,
  22110. edieresis: 0x00EB,
  22111. edot: 0x0117,
  22112. edotaccent: 0x0117,
  22113. edotbelow: 0x1EB9,
  22114. eegurmukhi: 0x0A0F,
  22115. eematragurmukhi: 0x0A47,
  22116. efcyrillic: 0x0444,
  22117. egrave: 0x00E8,
  22118. egujarati: 0x0A8F,
  22119. eharmenian: 0x0567,
  22120. ehbopomofo: 0x311D,
  22121. ehiragana: 0x3048,
  22122. ehookabove: 0x1EBB,
  22123. eibopomofo: 0x311F,
  22124. eight: 0x0038,
  22125. eightarabic: 0x0668,
  22126. eightbengali: 0x09EE,
  22127. eightcircle: 0x2467,
  22128. eightcircleinversesansserif: 0x2791,
  22129. eightdeva: 0x096E,
  22130. eighteencircle: 0x2471,
  22131. eighteenparen: 0x2485,
  22132. eighteenperiod: 0x2499,
  22133. eightgujarati: 0x0AEE,
  22134. eightgurmukhi: 0x0A6E,
  22135. eighthackarabic: 0x0668,
  22136. eighthangzhou: 0x3028,
  22137. eighthnotebeamed: 0x266B,
  22138. eightideographicparen: 0x3227,
  22139. eightinferior: 0x2088,
  22140. eightmonospace: 0xFF18,
  22141. eightoldstyle: 0xF738,
  22142. eightparen: 0x247B,
  22143. eightperiod: 0x248F,
  22144. eightpersian: 0x06F8,
  22145. eightroman: 0x2177,
  22146. eightsuperior: 0x2078,
  22147. eightthai: 0x0E58,
  22148. einvertedbreve: 0x0207,
  22149. eiotifiedcyrillic: 0x0465,
  22150. ekatakana: 0x30A8,
  22151. ekatakanahalfwidth: 0xFF74,
  22152. ekonkargurmukhi: 0x0A74,
  22153. ekorean: 0x3154,
  22154. elcyrillic: 0x043B,
  22155. element: 0x2208,
  22156. elevencircle: 0x246A,
  22157. elevenparen: 0x247E,
  22158. elevenperiod: 0x2492,
  22159. elevenroman: 0x217A,
  22160. ellipsis: 0x2026,
  22161. ellipsisvertical: 0x22EE,
  22162. emacron: 0x0113,
  22163. emacronacute: 0x1E17,
  22164. emacrongrave: 0x1E15,
  22165. emcyrillic: 0x043C,
  22166. emdash: 0x2014,
  22167. emdashvertical: 0xFE31,
  22168. emonospace: 0xFF45,
  22169. emphasismarkarmenian: 0x055B,
  22170. emptyset: 0x2205,
  22171. enbopomofo: 0x3123,
  22172. encyrillic: 0x043D,
  22173. endash: 0x2013,
  22174. endashvertical: 0xFE32,
  22175. endescendercyrillic: 0x04A3,
  22176. eng: 0x014B,
  22177. engbopomofo: 0x3125,
  22178. enghecyrillic: 0x04A5,
  22179. enhookcyrillic: 0x04C8,
  22180. enspace: 0x2002,
  22181. eogonek: 0x0119,
  22182. eokorean: 0x3153,
  22183. eopen: 0x025B,
  22184. eopenclosed: 0x029A,
  22185. eopenreversed: 0x025C,
  22186. eopenreversedclosed: 0x025E,
  22187. eopenreversedhook: 0x025D,
  22188. eparen: 0x24A0,
  22189. epsilon: 0x03B5,
  22190. epsilontonos: 0x03AD,
  22191. equal: 0x003D,
  22192. equalmonospace: 0xFF1D,
  22193. equalsmall: 0xFE66,
  22194. equalsuperior: 0x207C,
  22195. equivalence: 0x2261,
  22196. erbopomofo: 0x3126,
  22197. ercyrillic: 0x0440,
  22198. ereversed: 0x0258,
  22199. ereversedcyrillic: 0x044D,
  22200. escyrillic: 0x0441,
  22201. esdescendercyrillic: 0x04AB,
  22202. esh: 0x0283,
  22203. eshcurl: 0x0286,
  22204. eshortdeva: 0x090E,
  22205. eshortvowelsigndeva: 0x0946,
  22206. eshreversedloop: 0x01AA,
  22207. eshsquatreversed: 0x0285,
  22208. esmallhiragana: 0x3047,
  22209. esmallkatakana: 0x30A7,
  22210. esmallkatakanahalfwidth: 0xFF6A,
  22211. estimated: 0x212E,
  22212. esuperior: 0xF6EC,
  22213. eta: 0x03B7,
  22214. etarmenian: 0x0568,
  22215. etatonos: 0x03AE,
  22216. eth: 0x00F0,
  22217. etilde: 0x1EBD,
  22218. etildebelow: 0x1E1B,
  22219. etnahtafoukhhebrew: 0x0591,
  22220. etnahtafoukhlefthebrew: 0x0591,
  22221. etnahtahebrew: 0x0591,
  22222. etnahtalefthebrew: 0x0591,
  22223. eturned: 0x01DD,
  22224. eukorean: 0x3161,
  22225. euro: 0x20AC,
  22226. evowelsignbengali: 0x09C7,
  22227. evowelsigndeva: 0x0947,
  22228. evowelsigngujarati: 0x0AC7,
  22229. exclam: 0x0021,
  22230. exclamarmenian: 0x055C,
  22231. exclamdbl: 0x203C,
  22232. exclamdown: 0x00A1,
  22233. exclamdownsmall: 0xF7A1,
  22234. exclammonospace: 0xFF01,
  22235. exclamsmall: 0xF721,
  22236. existential: 0x2203,
  22237. ezh: 0x0292,
  22238. ezhcaron: 0x01EF,
  22239. ezhcurl: 0x0293,
  22240. ezhreversed: 0x01B9,
  22241. ezhtail: 0x01BA,
  22242. f: 0x0066,
  22243. fadeva: 0x095E,
  22244. fagurmukhi: 0x0A5E,
  22245. fahrenheit: 0x2109,
  22246. fathaarabic: 0x064E,
  22247. fathalowarabic: 0x064E,
  22248. fathatanarabic: 0x064B,
  22249. fbopomofo: 0x3108,
  22250. fcircle: 0x24D5,
  22251. fdotaccent: 0x1E1F,
  22252. feharabic: 0x0641,
  22253. feharmenian: 0x0586,
  22254. fehfinalarabic: 0xFED2,
  22255. fehinitialarabic: 0xFED3,
  22256. fehmedialarabic: 0xFED4,
  22257. feicoptic: 0x03E5,
  22258. female: 0x2640,
  22259. ff: 0xFB00,
  22260. ffi: 0xFB03,
  22261. ffl: 0xFB04,
  22262. fi: 0xFB01,
  22263. fifteencircle: 0x246E,
  22264. fifteenparen: 0x2482,
  22265. fifteenperiod: 0x2496,
  22266. figuredash: 0x2012,
  22267. filledbox: 0x25A0,
  22268. filledrect: 0x25AC,
  22269. finalkaf: 0x05DA,
  22270. finalkafdagesh: 0xFB3A,
  22271. finalkafdageshhebrew: 0xFB3A,
  22272. finalkafhebrew: 0x05DA,
  22273. finalmem: 0x05DD,
  22274. finalmemhebrew: 0x05DD,
  22275. finalnun: 0x05DF,
  22276. finalnunhebrew: 0x05DF,
  22277. finalpe: 0x05E3,
  22278. finalpehebrew: 0x05E3,
  22279. finaltsadi: 0x05E5,
  22280. finaltsadihebrew: 0x05E5,
  22281. firsttonechinese: 0x02C9,
  22282. fisheye: 0x25C9,
  22283. fitacyrillic: 0x0473,
  22284. five: 0x0035,
  22285. fivearabic: 0x0665,
  22286. fivebengali: 0x09EB,
  22287. fivecircle: 0x2464,
  22288. fivecircleinversesansserif: 0x278E,
  22289. fivedeva: 0x096B,
  22290. fiveeighths: 0x215D,
  22291. fivegujarati: 0x0AEB,
  22292. fivegurmukhi: 0x0A6B,
  22293. fivehackarabic: 0x0665,
  22294. fivehangzhou: 0x3025,
  22295. fiveideographicparen: 0x3224,
  22296. fiveinferior: 0x2085,
  22297. fivemonospace: 0xFF15,
  22298. fiveoldstyle: 0xF735,
  22299. fiveparen: 0x2478,
  22300. fiveperiod: 0x248C,
  22301. fivepersian: 0x06F5,
  22302. fiveroman: 0x2174,
  22303. fivesuperior: 0x2075,
  22304. fivethai: 0x0E55,
  22305. fl: 0xFB02,
  22306. florin: 0x0192,
  22307. fmonospace: 0xFF46,
  22308. fmsquare: 0x3399,
  22309. fofanthai: 0x0E1F,
  22310. fofathai: 0x0E1D,
  22311. fongmanthai: 0x0E4F,
  22312. forall: 0x2200,
  22313. four: 0x0034,
  22314. fourarabic: 0x0664,
  22315. fourbengali: 0x09EA,
  22316. fourcircle: 0x2463,
  22317. fourcircleinversesansserif: 0x278D,
  22318. fourdeva: 0x096A,
  22319. fourgujarati: 0x0AEA,
  22320. fourgurmukhi: 0x0A6A,
  22321. fourhackarabic: 0x0664,
  22322. fourhangzhou: 0x3024,
  22323. fourideographicparen: 0x3223,
  22324. fourinferior: 0x2084,
  22325. fourmonospace: 0xFF14,
  22326. fournumeratorbengali: 0x09F7,
  22327. fouroldstyle: 0xF734,
  22328. fourparen: 0x2477,
  22329. fourperiod: 0x248B,
  22330. fourpersian: 0x06F4,
  22331. fourroman: 0x2173,
  22332. foursuperior: 0x2074,
  22333. fourteencircle: 0x246D,
  22334. fourteenparen: 0x2481,
  22335. fourteenperiod: 0x2495,
  22336. fourthai: 0x0E54,
  22337. fourthtonechinese: 0x02CB,
  22338. fparen: 0x24A1,
  22339. fraction: 0x2044,
  22340. franc: 0x20A3,
  22341. g: 0x0067,
  22342. gabengali: 0x0997,
  22343. gacute: 0x01F5,
  22344. gadeva: 0x0917,
  22345. gafarabic: 0x06AF,
  22346. gaffinalarabic: 0xFB93,
  22347. gafinitialarabic: 0xFB94,
  22348. gafmedialarabic: 0xFB95,
  22349. gagujarati: 0x0A97,
  22350. gagurmukhi: 0x0A17,
  22351. gahiragana: 0x304C,
  22352. gakatakana: 0x30AC,
  22353. gamma: 0x03B3,
  22354. gammalatinsmall: 0x0263,
  22355. gammasuperior: 0x02E0,
  22356. gangiacoptic: 0x03EB,
  22357. gbopomofo: 0x310D,
  22358. gbreve: 0x011F,
  22359. gcaron: 0x01E7,
  22360. gcedilla: 0x0123,
  22361. gcircle: 0x24D6,
  22362. gcircumflex: 0x011D,
  22363. gcommaaccent: 0x0123,
  22364. gdot: 0x0121,
  22365. gdotaccent: 0x0121,
  22366. gecyrillic: 0x0433,
  22367. gehiragana: 0x3052,
  22368. gekatakana: 0x30B2,
  22369. geometricallyequal: 0x2251,
  22370. gereshaccenthebrew: 0x059C,
  22371. gereshhebrew: 0x05F3,
  22372. gereshmuqdamhebrew: 0x059D,
  22373. germandbls: 0x00DF,
  22374. gershayimaccenthebrew: 0x059E,
  22375. gershayimhebrew: 0x05F4,
  22376. getamark: 0x3013,
  22377. ghabengali: 0x0998,
  22378. ghadarmenian: 0x0572,
  22379. ghadeva: 0x0918,
  22380. ghagujarati: 0x0A98,
  22381. ghagurmukhi: 0x0A18,
  22382. ghainarabic: 0x063A,
  22383. ghainfinalarabic: 0xFECE,
  22384. ghaininitialarabic: 0xFECF,
  22385. ghainmedialarabic: 0xFED0,
  22386. ghemiddlehookcyrillic: 0x0495,
  22387. ghestrokecyrillic: 0x0493,
  22388. gheupturncyrillic: 0x0491,
  22389. ghhadeva: 0x095A,
  22390. ghhagurmukhi: 0x0A5A,
  22391. ghook: 0x0260,
  22392. ghzsquare: 0x3393,
  22393. gihiragana: 0x304E,
  22394. gikatakana: 0x30AE,
  22395. gimarmenian: 0x0563,
  22396. gimel: 0x05D2,
  22397. gimeldagesh: 0xFB32,
  22398. gimeldageshhebrew: 0xFB32,
  22399. gimelhebrew: 0x05D2,
  22400. gjecyrillic: 0x0453,
  22401. glottalinvertedstroke: 0x01BE,
  22402. glottalstop: 0x0294,
  22403. glottalstopinverted: 0x0296,
  22404. glottalstopmod: 0x02C0,
  22405. glottalstopreversed: 0x0295,
  22406. glottalstopreversedmod: 0x02C1,
  22407. glottalstopreversedsuperior: 0x02E4,
  22408. glottalstopstroke: 0x02A1,
  22409. glottalstopstrokereversed: 0x02A2,
  22410. gmacron: 0x1E21,
  22411. gmonospace: 0xFF47,
  22412. gohiragana: 0x3054,
  22413. gokatakana: 0x30B4,
  22414. gparen: 0x24A2,
  22415. gpasquare: 0x33AC,
  22416. gradient: 0x2207,
  22417. grave: 0x0060,
  22418. gravebelowcmb: 0x0316,
  22419. gravecmb: 0x0300,
  22420. gravecomb: 0x0300,
  22421. gravedeva: 0x0953,
  22422. gravelowmod: 0x02CE,
  22423. gravemonospace: 0xFF40,
  22424. gravetonecmb: 0x0340,
  22425. greater: 0x003E,
  22426. greaterequal: 0x2265,
  22427. greaterequalorless: 0x22DB,
  22428. greatermonospace: 0xFF1E,
  22429. greaterorequivalent: 0x2273,
  22430. greaterorless: 0x2277,
  22431. greateroverequal: 0x2267,
  22432. greatersmall: 0xFE65,
  22433. gscript: 0x0261,
  22434. gstroke: 0x01E5,
  22435. guhiragana: 0x3050,
  22436. guillemotleft: 0x00AB,
  22437. guillemotright: 0x00BB,
  22438. guilsinglleft: 0x2039,
  22439. guilsinglright: 0x203A,
  22440. gukatakana: 0x30B0,
  22441. guramusquare: 0x3318,
  22442. gysquare: 0x33C9,
  22443. h: 0x0068,
  22444. haabkhasiancyrillic: 0x04A9,
  22445. haaltonearabic: 0x06C1,
  22446. habengali: 0x09B9,
  22447. hadescendercyrillic: 0x04B3,
  22448. hadeva: 0x0939,
  22449. hagujarati: 0x0AB9,
  22450. hagurmukhi: 0x0A39,
  22451. haharabic: 0x062D,
  22452. hahfinalarabic: 0xFEA2,
  22453. hahinitialarabic: 0xFEA3,
  22454. hahiragana: 0x306F,
  22455. hahmedialarabic: 0xFEA4,
  22456. haitusquare: 0x332A,
  22457. hakatakana: 0x30CF,
  22458. hakatakanahalfwidth: 0xFF8A,
  22459. halantgurmukhi: 0x0A4D,
  22460. hamzaarabic: 0x0621,
  22461. hamzalowarabic: 0x0621,
  22462. hangulfiller: 0x3164,
  22463. hardsigncyrillic: 0x044A,
  22464. harpoonleftbarbup: 0x21BC,
  22465. harpoonrightbarbup: 0x21C0,
  22466. hasquare: 0x33CA,
  22467. hatafpatah: 0x05B2,
  22468. hatafpatah16: 0x05B2,
  22469. hatafpatah23: 0x05B2,
  22470. hatafpatah2f: 0x05B2,
  22471. hatafpatahhebrew: 0x05B2,
  22472. hatafpatahnarrowhebrew: 0x05B2,
  22473. hatafpatahquarterhebrew: 0x05B2,
  22474. hatafpatahwidehebrew: 0x05B2,
  22475. hatafqamats: 0x05B3,
  22476. hatafqamats1b: 0x05B3,
  22477. hatafqamats28: 0x05B3,
  22478. hatafqamats34: 0x05B3,
  22479. hatafqamatshebrew: 0x05B3,
  22480. hatafqamatsnarrowhebrew: 0x05B3,
  22481. hatafqamatsquarterhebrew: 0x05B3,
  22482. hatafqamatswidehebrew: 0x05B3,
  22483. hatafsegol: 0x05B1,
  22484. hatafsegol17: 0x05B1,
  22485. hatafsegol24: 0x05B1,
  22486. hatafsegol30: 0x05B1,
  22487. hatafsegolhebrew: 0x05B1,
  22488. hatafsegolnarrowhebrew: 0x05B1,
  22489. hatafsegolquarterhebrew: 0x05B1,
  22490. hatafsegolwidehebrew: 0x05B1,
  22491. hbar: 0x0127,
  22492. hbopomofo: 0x310F,
  22493. hbrevebelow: 0x1E2B,
  22494. hcedilla: 0x1E29,
  22495. hcircle: 0x24D7,
  22496. hcircumflex: 0x0125,
  22497. hdieresis: 0x1E27,
  22498. hdotaccent: 0x1E23,
  22499. hdotbelow: 0x1E25,
  22500. he: 0x05D4,
  22501. heart: 0x2665,
  22502. heartsuitblack: 0x2665,
  22503. heartsuitwhite: 0x2661,
  22504. hedagesh: 0xFB34,
  22505. hedageshhebrew: 0xFB34,
  22506. hehaltonearabic: 0x06C1,
  22507. heharabic: 0x0647,
  22508. hehebrew: 0x05D4,
  22509. hehfinalaltonearabic: 0xFBA7,
  22510. hehfinalalttwoarabic: 0xFEEA,
  22511. hehfinalarabic: 0xFEEA,
  22512. hehhamzaabovefinalarabic: 0xFBA5,
  22513. hehhamzaaboveisolatedarabic: 0xFBA4,
  22514. hehinitialaltonearabic: 0xFBA8,
  22515. hehinitialarabic: 0xFEEB,
  22516. hehiragana: 0x3078,
  22517. hehmedialaltonearabic: 0xFBA9,
  22518. hehmedialarabic: 0xFEEC,
  22519. heiseierasquare: 0x337B,
  22520. hekatakana: 0x30D8,
  22521. hekatakanahalfwidth: 0xFF8D,
  22522. hekutaarusquare: 0x3336,
  22523. henghook: 0x0267,
  22524. herutusquare: 0x3339,
  22525. het: 0x05D7,
  22526. hethebrew: 0x05D7,
  22527. hhook: 0x0266,
  22528. hhooksuperior: 0x02B1,
  22529. hieuhacirclekorean: 0x327B,
  22530. hieuhaparenkorean: 0x321B,
  22531. hieuhcirclekorean: 0x326D,
  22532. hieuhkorean: 0x314E,
  22533. hieuhparenkorean: 0x320D,
  22534. hihiragana: 0x3072,
  22535. hikatakana: 0x30D2,
  22536. hikatakanahalfwidth: 0xFF8B,
  22537. hiriq: 0x05B4,
  22538. hiriq14: 0x05B4,
  22539. hiriq21: 0x05B4,
  22540. hiriq2d: 0x05B4,
  22541. hiriqhebrew: 0x05B4,
  22542. hiriqnarrowhebrew: 0x05B4,
  22543. hiriqquarterhebrew: 0x05B4,
  22544. hiriqwidehebrew: 0x05B4,
  22545. hlinebelow: 0x1E96,
  22546. hmonospace: 0xFF48,
  22547. hoarmenian: 0x0570,
  22548. hohipthai: 0x0E2B,
  22549. hohiragana: 0x307B,
  22550. hokatakana: 0x30DB,
  22551. hokatakanahalfwidth: 0xFF8E,
  22552. holam: 0x05B9,
  22553. holam19: 0x05B9,
  22554. holam26: 0x05B9,
  22555. holam32: 0x05B9,
  22556. holamhebrew: 0x05B9,
  22557. holamnarrowhebrew: 0x05B9,
  22558. holamquarterhebrew: 0x05B9,
  22559. holamwidehebrew: 0x05B9,
  22560. honokhukthai: 0x0E2E,
  22561. hookabovecomb: 0x0309,
  22562. hookcmb: 0x0309,
  22563. hookpalatalizedbelowcmb: 0x0321,
  22564. hookretroflexbelowcmb: 0x0322,
  22565. hoonsquare: 0x3342,
  22566. horicoptic: 0x03E9,
  22567. horizontalbar: 0x2015,
  22568. horncmb: 0x031B,
  22569. hotsprings: 0x2668,
  22570. house: 0x2302,
  22571. hparen: 0x24A3,
  22572. hsuperior: 0x02B0,
  22573. hturned: 0x0265,
  22574. huhiragana: 0x3075,
  22575. huiitosquare: 0x3333,
  22576. hukatakana: 0x30D5,
  22577. hukatakanahalfwidth: 0xFF8C,
  22578. hungarumlaut: 0x02DD,
  22579. hungarumlautcmb: 0x030B,
  22580. hv: 0x0195,
  22581. hyphen: 0x002D,
  22582. hypheninferior: 0xF6E5,
  22583. hyphenmonospace: 0xFF0D,
  22584. hyphensmall: 0xFE63,
  22585. hyphensuperior: 0xF6E6,
  22586. hyphentwo: 0x2010,
  22587. i: 0x0069,
  22588. iacute: 0x00ED,
  22589. iacyrillic: 0x044F,
  22590. ibengali: 0x0987,
  22591. ibopomofo: 0x3127,
  22592. ibreve: 0x012D,
  22593. icaron: 0x01D0,
  22594. icircle: 0x24D8,
  22595. icircumflex: 0x00EE,
  22596. icyrillic: 0x0456,
  22597. idblgrave: 0x0209,
  22598. ideographearthcircle: 0x328F,
  22599. ideographfirecircle: 0x328B,
  22600. ideographicallianceparen: 0x323F,
  22601. ideographiccallparen: 0x323A,
  22602. ideographiccentrecircle: 0x32A5,
  22603. ideographicclose: 0x3006,
  22604. ideographiccomma: 0x3001,
  22605. ideographiccommaleft: 0xFF64,
  22606. ideographiccongratulationparen: 0x3237,
  22607. ideographiccorrectcircle: 0x32A3,
  22608. ideographicearthparen: 0x322F,
  22609. ideographicenterpriseparen: 0x323D,
  22610. ideographicexcellentcircle: 0x329D,
  22611. ideographicfestivalparen: 0x3240,
  22612. ideographicfinancialcircle: 0x3296,
  22613. ideographicfinancialparen: 0x3236,
  22614. ideographicfireparen: 0x322B,
  22615. ideographichaveparen: 0x3232,
  22616. ideographichighcircle: 0x32A4,
  22617. ideographiciterationmark: 0x3005,
  22618. ideographiclaborcircle: 0x3298,
  22619. ideographiclaborparen: 0x3238,
  22620. ideographicleftcircle: 0x32A7,
  22621. ideographiclowcircle: 0x32A6,
  22622. ideographicmedicinecircle: 0x32A9,
  22623. ideographicmetalparen: 0x322E,
  22624. ideographicmoonparen: 0x322A,
  22625. ideographicnameparen: 0x3234,
  22626. ideographicperiod: 0x3002,
  22627. ideographicprintcircle: 0x329E,
  22628. ideographicreachparen: 0x3243,
  22629. ideographicrepresentparen: 0x3239,
  22630. ideographicresourceparen: 0x323E,
  22631. ideographicrightcircle: 0x32A8,
  22632. ideographicsecretcircle: 0x3299,
  22633. ideographicselfparen: 0x3242,
  22634. ideographicsocietyparen: 0x3233,
  22635. ideographicspace: 0x3000,
  22636. ideographicspecialparen: 0x3235,
  22637. ideographicstockparen: 0x3231,
  22638. ideographicstudyparen: 0x323B,
  22639. ideographicsunparen: 0x3230,
  22640. ideographicsuperviseparen: 0x323C,
  22641. ideographicwaterparen: 0x322C,
  22642. ideographicwoodparen: 0x322D,
  22643. ideographiczero: 0x3007,
  22644. ideographmetalcircle: 0x328E,
  22645. ideographmooncircle: 0x328A,
  22646. ideographnamecircle: 0x3294,
  22647. ideographsuncircle: 0x3290,
  22648. ideographwatercircle: 0x328C,
  22649. ideographwoodcircle: 0x328D,
  22650. ideva: 0x0907,
  22651. idieresis: 0x00EF,
  22652. idieresisacute: 0x1E2F,
  22653. idieresiscyrillic: 0x04E5,
  22654. idotbelow: 0x1ECB,
  22655. iebrevecyrillic: 0x04D7,
  22656. iecyrillic: 0x0435,
  22657. ieungacirclekorean: 0x3275,
  22658. ieungaparenkorean: 0x3215,
  22659. ieungcirclekorean: 0x3267,
  22660. ieungkorean: 0x3147,
  22661. ieungparenkorean: 0x3207,
  22662. igrave: 0x00EC,
  22663. igujarati: 0x0A87,
  22664. igurmukhi: 0x0A07,
  22665. ihiragana: 0x3044,
  22666. ihookabove: 0x1EC9,
  22667. iibengali: 0x0988,
  22668. iicyrillic: 0x0438,
  22669. iideva: 0x0908,
  22670. iigujarati: 0x0A88,
  22671. iigurmukhi: 0x0A08,
  22672. iimatragurmukhi: 0x0A40,
  22673. iinvertedbreve: 0x020B,
  22674. iishortcyrillic: 0x0439,
  22675. iivowelsignbengali: 0x09C0,
  22676. iivowelsigndeva: 0x0940,
  22677. iivowelsigngujarati: 0x0AC0,
  22678. ij: 0x0133,
  22679. ikatakana: 0x30A4,
  22680. ikatakanahalfwidth: 0xFF72,
  22681. ikorean: 0x3163,
  22682. ilde: 0x02DC,
  22683. iluyhebrew: 0x05AC,
  22684. imacron: 0x012B,
  22685. imacroncyrillic: 0x04E3,
  22686. imageorapproximatelyequal: 0x2253,
  22687. imatragurmukhi: 0x0A3F,
  22688. imonospace: 0xFF49,
  22689. increment: 0x2206,
  22690. infinity: 0x221E,
  22691. iniarmenian: 0x056B,
  22692. integral: 0x222B,
  22693. integralbottom: 0x2321,
  22694. integralbt: 0x2321,
  22695. integralex: 0xF8F5,
  22696. integraltop: 0x2320,
  22697. integraltp: 0x2320,
  22698. intersection: 0x2229,
  22699. intisquare: 0x3305,
  22700. invbullet: 0x25D8,
  22701. invcircle: 0x25D9,
  22702. invsmileface: 0x263B,
  22703. iocyrillic: 0x0451,
  22704. iogonek: 0x012F,
  22705. iota: 0x03B9,
  22706. iotadieresis: 0x03CA,
  22707. iotadieresistonos: 0x0390,
  22708. iotalatin: 0x0269,
  22709. iotatonos: 0x03AF,
  22710. iparen: 0x24A4,
  22711. irigurmukhi: 0x0A72,
  22712. ismallhiragana: 0x3043,
  22713. ismallkatakana: 0x30A3,
  22714. ismallkatakanahalfwidth: 0xFF68,
  22715. issharbengali: 0x09FA,
  22716. istroke: 0x0268,
  22717. isuperior: 0xF6ED,
  22718. iterationhiragana: 0x309D,
  22719. iterationkatakana: 0x30FD,
  22720. itilde: 0x0129,
  22721. itildebelow: 0x1E2D,
  22722. iubopomofo: 0x3129,
  22723. iucyrillic: 0x044E,
  22724. ivowelsignbengali: 0x09BF,
  22725. ivowelsigndeva: 0x093F,
  22726. ivowelsigngujarati: 0x0ABF,
  22727. izhitsacyrillic: 0x0475,
  22728. izhitsadblgravecyrillic: 0x0477,
  22729. j: 0x006A,
  22730. jaarmenian: 0x0571,
  22731. jabengali: 0x099C,
  22732. jadeva: 0x091C,
  22733. jagujarati: 0x0A9C,
  22734. jagurmukhi: 0x0A1C,
  22735. jbopomofo: 0x3110,
  22736. jcaron: 0x01F0,
  22737. jcircle: 0x24D9,
  22738. jcircumflex: 0x0135,
  22739. jcrossedtail: 0x029D,
  22740. jdotlessstroke: 0x025F,
  22741. jecyrillic: 0x0458,
  22742. jeemarabic: 0x062C,
  22743. jeemfinalarabic: 0xFE9E,
  22744. jeeminitialarabic: 0xFE9F,
  22745. jeemmedialarabic: 0xFEA0,
  22746. jeharabic: 0x0698,
  22747. jehfinalarabic: 0xFB8B,
  22748. jhabengali: 0x099D,
  22749. jhadeva: 0x091D,
  22750. jhagujarati: 0x0A9D,
  22751. jhagurmukhi: 0x0A1D,
  22752. jheharmenian: 0x057B,
  22753. jis: 0x3004,
  22754. jmonospace: 0xFF4A,
  22755. jparen: 0x24A5,
  22756. jsuperior: 0x02B2,
  22757. k: 0x006B,
  22758. kabashkircyrillic: 0x04A1,
  22759. kabengali: 0x0995,
  22760. kacute: 0x1E31,
  22761. kacyrillic: 0x043A,
  22762. kadescendercyrillic: 0x049B,
  22763. kadeva: 0x0915,
  22764. kaf: 0x05DB,
  22765. kafarabic: 0x0643,
  22766. kafdagesh: 0xFB3B,
  22767. kafdageshhebrew: 0xFB3B,
  22768. kaffinalarabic: 0xFEDA,
  22769. kafhebrew: 0x05DB,
  22770. kafinitialarabic: 0xFEDB,
  22771. kafmedialarabic: 0xFEDC,
  22772. kafrafehebrew: 0xFB4D,
  22773. kagujarati: 0x0A95,
  22774. kagurmukhi: 0x0A15,
  22775. kahiragana: 0x304B,
  22776. kahookcyrillic: 0x04C4,
  22777. kakatakana: 0x30AB,
  22778. kakatakanahalfwidth: 0xFF76,
  22779. kappa: 0x03BA,
  22780. kappasymbolgreek: 0x03F0,
  22781. kapyeounmieumkorean: 0x3171,
  22782. kapyeounphieuphkorean: 0x3184,
  22783. kapyeounpieupkorean: 0x3178,
  22784. kapyeounssangpieupkorean: 0x3179,
  22785. karoriisquare: 0x330D,
  22786. kashidaautoarabic: 0x0640,
  22787. kashidaautonosidebearingarabic: 0x0640,
  22788. kasmallkatakana: 0x30F5,
  22789. kasquare: 0x3384,
  22790. kasraarabic: 0x0650,
  22791. kasratanarabic: 0x064D,
  22792. kastrokecyrillic: 0x049F,
  22793. katahiraprolongmarkhalfwidth: 0xFF70,
  22794. kaverticalstrokecyrillic: 0x049D,
  22795. kbopomofo: 0x310E,
  22796. kcalsquare: 0x3389,
  22797. kcaron: 0x01E9,
  22798. kcedilla: 0x0137,
  22799. kcircle: 0x24DA,
  22800. kcommaaccent: 0x0137,
  22801. kdotbelow: 0x1E33,
  22802. keharmenian: 0x0584,
  22803. kehiragana: 0x3051,
  22804. kekatakana: 0x30B1,
  22805. kekatakanahalfwidth: 0xFF79,
  22806. kenarmenian: 0x056F,
  22807. kesmallkatakana: 0x30F6,
  22808. kgreenlandic: 0x0138,
  22809. khabengali: 0x0996,
  22810. khacyrillic: 0x0445,
  22811. khadeva: 0x0916,
  22812. khagujarati: 0x0A96,
  22813. khagurmukhi: 0x0A16,
  22814. khaharabic: 0x062E,
  22815. khahfinalarabic: 0xFEA6,
  22816. khahinitialarabic: 0xFEA7,
  22817. khahmedialarabic: 0xFEA8,
  22818. kheicoptic: 0x03E7,
  22819. khhadeva: 0x0959,
  22820. khhagurmukhi: 0x0A59,
  22821. khieukhacirclekorean: 0x3278,
  22822. khieukhaparenkorean: 0x3218,
  22823. khieukhcirclekorean: 0x326A,
  22824. khieukhkorean: 0x314B,
  22825. khieukhparenkorean: 0x320A,
  22826. khokhaithai: 0x0E02,
  22827. khokhonthai: 0x0E05,
  22828. khokhuatthai: 0x0E03,
  22829. khokhwaithai: 0x0E04,
  22830. khomutthai: 0x0E5B,
  22831. khook: 0x0199,
  22832. khorakhangthai: 0x0E06,
  22833. khzsquare: 0x3391,
  22834. kihiragana: 0x304D,
  22835. kikatakana: 0x30AD,
  22836. kikatakanahalfwidth: 0xFF77,
  22837. kiroguramusquare: 0x3315,
  22838. kiromeetorusquare: 0x3316,
  22839. kirosquare: 0x3314,
  22840. kiyeokacirclekorean: 0x326E,
  22841. kiyeokaparenkorean: 0x320E,
  22842. kiyeokcirclekorean: 0x3260,
  22843. kiyeokkorean: 0x3131,
  22844. kiyeokparenkorean: 0x3200,
  22845. kiyeoksioskorean: 0x3133,
  22846. kjecyrillic: 0x045C,
  22847. klinebelow: 0x1E35,
  22848. klsquare: 0x3398,
  22849. kmcubedsquare: 0x33A6,
  22850. kmonospace: 0xFF4B,
  22851. kmsquaredsquare: 0x33A2,
  22852. kohiragana: 0x3053,
  22853. kohmsquare: 0x33C0,
  22854. kokaithai: 0x0E01,
  22855. kokatakana: 0x30B3,
  22856. kokatakanahalfwidth: 0xFF7A,
  22857. kooposquare: 0x331E,
  22858. koppacyrillic: 0x0481,
  22859. koreanstandardsymbol: 0x327F,
  22860. koroniscmb: 0x0343,
  22861. kparen: 0x24A6,
  22862. kpasquare: 0x33AA,
  22863. ksicyrillic: 0x046F,
  22864. ktsquare: 0x33CF,
  22865. kturned: 0x029E,
  22866. kuhiragana: 0x304F,
  22867. kukatakana: 0x30AF,
  22868. kukatakanahalfwidth: 0xFF78,
  22869. kvsquare: 0x33B8,
  22870. kwsquare: 0x33BE,
  22871. l: 0x006C,
  22872. labengali: 0x09B2,
  22873. lacute: 0x013A,
  22874. ladeva: 0x0932,
  22875. lagujarati: 0x0AB2,
  22876. lagurmukhi: 0x0A32,
  22877. lakkhangyaothai: 0x0E45,
  22878. lamaleffinalarabic: 0xFEFC,
  22879. lamalefhamzaabovefinalarabic: 0xFEF8,
  22880. lamalefhamzaaboveisolatedarabic: 0xFEF7,
  22881. lamalefhamzabelowfinalarabic: 0xFEFA,
  22882. lamalefhamzabelowisolatedarabic: 0xFEF9,
  22883. lamalefisolatedarabic: 0xFEFB,
  22884. lamalefmaddaabovefinalarabic: 0xFEF6,
  22885. lamalefmaddaaboveisolatedarabic: 0xFEF5,
  22886. lamarabic: 0x0644,
  22887. lambda: 0x03BB,
  22888. lambdastroke: 0x019B,
  22889. lamed: 0x05DC,
  22890. lameddagesh: 0xFB3C,
  22891. lameddageshhebrew: 0xFB3C,
  22892. lamedhebrew: 0x05DC,
  22893. lamfinalarabic: 0xFEDE,
  22894. lamhahinitialarabic: 0xFCCA,
  22895. laminitialarabic: 0xFEDF,
  22896. lamjeeminitialarabic: 0xFCC9,
  22897. lamkhahinitialarabic: 0xFCCB,
  22898. lamlamhehisolatedarabic: 0xFDF2,
  22899. lammedialarabic: 0xFEE0,
  22900. lammeemhahinitialarabic: 0xFD88,
  22901. lammeeminitialarabic: 0xFCCC,
  22902. largecircle: 0x25EF,
  22903. lbar: 0x019A,
  22904. lbelt: 0x026C,
  22905. lbopomofo: 0x310C,
  22906. lcaron: 0x013E,
  22907. lcedilla: 0x013C,
  22908. lcircle: 0x24DB,
  22909. lcircumflexbelow: 0x1E3D,
  22910. lcommaaccent: 0x013C,
  22911. ldot: 0x0140,
  22912. ldotaccent: 0x0140,
  22913. ldotbelow: 0x1E37,
  22914. ldotbelowmacron: 0x1E39,
  22915. leftangleabovecmb: 0x031A,
  22916. lefttackbelowcmb: 0x0318,
  22917. less: 0x003C,
  22918. lessequal: 0x2264,
  22919. lessequalorgreater: 0x22DA,
  22920. lessmonospace: 0xFF1C,
  22921. lessorequivalent: 0x2272,
  22922. lessorgreater: 0x2276,
  22923. lessoverequal: 0x2266,
  22924. lesssmall: 0xFE64,
  22925. lezh: 0x026E,
  22926. lfblock: 0x258C,
  22927. lhookretroflex: 0x026D,
  22928. lira: 0x20A4,
  22929. liwnarmenian: 0x056C,
  22930. lj: 0x01C9,
  22931. ljecyrillic: 0x0459,
  22932. ll: 0xF6C0,
  22933. lladeva: 0x0933,
  22934. llagujarati: 0x0AB3,
  22935. llinebelow: 0x1E3B,
  22936. llladeva: 0x0934,
  22937. llvocalicbengali: 0x09E1,
  22938. llvocalicdeva: 0x0961,
  22939. llvocalicvowelsignbengali: 0x09E3,
  22940. llvocalicvowelsigndeva: 0x0963,
  22941. lmiddletilde: 0x026B,
  22942. lmonospace: 0xFF4C,
  22943. lmsquare: 0x33D0,
  22944. lochulathai: 0x0E2C,
  22945. logicaland: 0x2227,
  22946. logicalnot: 0x00AC,
  22947. logicalnotreversed: 0x2310,
  22948. logicalor: 0x2228,
  22949. lolingthai: 0x0E25,
  22950. longs: 0x017F,
  22951. lowlinecenterline: 0xFE4E,
  22952. lowlinecmb: 0x0332,
  22953. lowlinedashed: 0xFE4D,
  22954. lozenge: 0x25CA,
  22955. lparen: 0x24A7,
  22956. lslash: 0x0142,
  22957. lsquare: 0x2113,
  22958. lsuperior: 0xF6EE,
  22959. ltshade: 0x2591,
  22960. luthai: 0x0E26,
  22961. lvocalicbengali: 0x098C,
  22962. lvocalicdeva: 0x090C,
  22963. lvocalicvowelsignbengali: 0x09E2,
  22964. lvocalicvowelsigndeva: 0x0962,
  22965. lxsquare: 0x33D3,
  22966. m: 0x006D,
  22967. mabengali: 0x09AE,
  22968. macron: 0x00AF,
  22969. macronbelowcmb: 0x0331,
  22970. macroncmb: 0x0304,
  22971. macronlowmod: 0x02CD,
  22972. macronmonospace: 0xFFE3,
  22973. macute: 0x1E3F,
  22974. madeva: 0x092E,
  22975. magujarati: 0x0AAE,
  22976. magurmukhi: 0x0A2E,
  22977. mahapakhhebrew: 0x05A4,
  22978. mahapakhlefthebrew: 0x05A4,
  22979. mahiragana: 0x307E,
  22980. maichattawalowleftthai: 0xF895,
  22981. maichattawalowrightthai: 0xF894,
  22982. maichattawathai: 0x0E4B,
  22983. maichattawaupperleftthai: 0xF893,
  22984. maieklowleftthai: 0xF88C,
  22985. maieklowrightthai: 0xF88B,
  22986. maiekthai: 0x0E48,
  22987. maiekupperleftthai: 0xF88A,
  22988. maihanakatleftthai: 0xF884,
  22989. maihanakatthai: 0x0E31,
  22990. maitaikhuleftthai: 0xF889,
  22991. maitaikhuthai: 0x0E47,
  22992. maitholowleftthai: 0xF88F,
  22993. maitholowrightthai: 0xF88E,
  22994. maithothai: 0x0E49,
  22995. maithoupperleftthai: 0xF88D,
  22996. maitrilowleftthai: 0xF892,
  22997. maitrilowrightthai: 0xF891,
  22998. maitrithai: 0x0E4A,
  22999. maitriupperleftthai: 0xF890,
  23000. maiyamokthai: 0x0E46,
  23001. makatakana: 0x30DE,
  23002. makatakanahalfwidth: 0xFF8F,
  23003. male: 0x2642,
  23004. mansyonsquare: 0x3347,
  23005. maqafhebrew: 0x05BE,
  23006. mars: 0x2642,
  23007. masoracirclehebrew: 0x05AF,
  23008. masquare: 0x3383,
  23009. mbopomofo: 0x3107,
  23010. mbsquare: 0x33D4,
  23011. mcircle: 0x24DC,
  23012. mcubedsquare: 0x33A5,
  23013. mdotaccent: 0x1E41,
  23014. mdotbelow: 0x1E43,
  23015. meemarabic: 0x0645,
  23016. meemfinalarabic: 0xFEE2,
  23017. meeminitialarabic: 0xFEE3,
  23018. meemmedialarabic: 0xFEE4,
  23019. meemmeeminitialarabic: 0xFCD1,
  23020. meemmeemisolatedarabic: 0xFC48,
  23021. meetorusquare: 0x334D,
  23022. mehiragana: 0x3081,
  23023. meizierasquare: 0x337E,
  23024. mekatakana: 0x30E1,
  23025. mekatakanahalfwidth: 0xFF92,
  23026. mem: 0x05DE,
  23027. memdagesh: 0xFB3E,
  23028. memdageshhebrew: 0xFB3E,
  23029. memhebrew: 0x05DE,
  23030. menarmenian: 0x0574,
  23031. merkhahebrew: 0x05A5,
  23032. merkhakefulahebrew: 0x05A6,
  23033. merkhakefulalefthebrew: 0x05A6,
  23034. merkhalefthebrew: 0x05A5,
  23035. mhook: 0x0271,
  23036. mhzsquare: 0x3392,
  23037. middledotkatakanahalfwidth: 0xFF65,
  23038. middot: 0x00B7,
  23039. mieumacirclekorean: 0x3272,
  23040. mieumaparenkorean: 0x3212,
  23041. mieumcirclekorean: 0x3264,
  23042. mieumkorean: 0x3141,
  23043. mieumpansioskorean: 0x3170,
  23044. mieumparenkorean: 0x3204,
  23045. mieumpieupkorean: 0x316E,
  23046. mieumsioskorean: 0x316F,
  23047. mihiragana: 0x307F,
  23048. mikatakana: 0x30DF,
  23049. mikatakanahalfwidth: 0xFF90,
  23050. minus: 0x2212,
  23051. minusbelowcmb: 0x0320,
  23052. minuscircle: 0x2296,
  23053. minusmod: 0x02D7,
  23054. minusplus: 0x2213,
  23055. minute: 0x2032,
  23056. miribaarusquare: 0x334A,
  23057. mirisquare: 0x3349,
  23058. mlonglegturned: 0x0270,
  23059. mlsquare: 0x3396,
  23060. mmcubedsquare: 0x33A3,
  23061. mmonospace: 0xFF4D,
  23062. mmsquaredsquare: 0x339F,
  23063. mohiragana: 0x3082,
  23064. mohmsquare: 0x33C1,
  23065. mokatakana: 0x30E2,
  23066. mokatakanahalfwidth: 0xFF93,
  23067. molsquare: 0x33D6,
  23068. momathai: 0x0E21,
  23069. moverssquare: 0x33A7,
  23070. moverssquaredsquare: 0x33A8,
  23071. mparen: 0x24A8,
  23072. mpasquare: 0x33AB,
  23073. mssquare: 0x33B3,
  23074. msuperior: 0xF6EF,
  23075. mturned: 0x026F,
  23076. mu: 0x00B5,
  23077. mu1: 0x00B5,
  23078. muasquare: 0x3382,
  23079. muchgreater: 0x226B,
  23080. muchless: 0x226A,
  23081. mufsquare: 0x338C,
  23082. mugreek: 0x03BC,
  23083. mugsquare: 0x338D,
  23084. muhiragana: 0x3080,
  23085. mukatakana: 0x30E0,
  23086. mukatakanahalfwidth: 0xFF91,
  23087. mulsquare: 0x3395,
  23088. multiply: 0x00D7,
  23089. mumsquare: 0x339B,
  23090. munahhebrew: 0x05A3,
  23091. munahlefthebrew: 0x05A3,
  23092. musicalnote: 0x266A,
  23093. musicalnotedbl: 0x266B,
  23094. musicflatsign: 0x266D,
  23095. musicsharpsign: 0x266F,
  23096. mussquare: 0x33B2,
  23097. muvsquare: 0x33B6,
  23098. muwsquare: 0x33BC,
  23099. mvmegasquare: 0x33B9,
  23100. mvsquare: 0x33B7,
  23101. mwmegasquare: 0x33BF,
  23102. mwsquare: 0x33BD,
  23103. n: 0x006E,
  23104. nabengali: 0x09A8,
  23105. nabla: 0x2207,
  23106. nacute: 0x0144,
  23107. nadeva: 0x0928,
  23108. nagujarati: 0x0AA8,
  23109. nagurmukhi: 0x0A28,
  23110. nahiragana: 0x306A,
  23111. nakatakana: 0x30CA,
  23112. nakatakanahalfwidth: 0xFF85,
  23113. napostrophe: 0x0149,
  23114. nasquare: 0x3381,
  23115. nbopomofo: 0x310B,
  23116. nbspace: 0x00A0,
  23117. ncaron: 0x0148,
  23118. ncedilla: 0x0146,
  23119. ncircle: 0x24DD,
  23120. ncircumflexbelow: 0x1E4B,
  23121. ncommaaccent: 0x0146,
  23122. ndotaccent: 0x1E45,
  23123. ndotbelow: 0x1E47,
  23124. nehiragana: 0x306D,
  23125. nekatakana: 0x30CD,
  23126. nekatakanahalfwidth: 0xFF88,
  23127. newsheqelsign: 0x20AA,
  23128. nfsquare: 0x338B,
  23129. ngabengali: 0x0999,
  23130. ngadeva: 0x0919,
  23131. ngagujarati: 0x0A99,
  23132. ngagurmukhi: 0x0A19,
  23133. ngonguthai: 0x0E07,
  23134. nhiragana: 0x3093,
  23135. nhookleft: 0x0272,
  23136. nhookretroflex: 0x0273,
  23137. nieunacirclekorean: 0x326F,
  23138. nieunaparenkorean: 0x320F,
  23139. nieuncieuckorean: 0x3135,
  23140. nieuncirclekorean: 0x3261,
  23141. nieunhieuhkorean: 0x3136,
  23142. nieunkorean: 0x3134,
  23143. nieunpansioskorean: 0x3168,
  23144. nieunparenkorean: 0x3201,
  23145. nieunsioskorean: 0x3167,
  23146. nieuntikeutkorean: 0x3166,
  23147. nihiragana: 0x306B,
  23148. nikatakana: 0x30CB,
  23149. nikatakanahalfwidth: 0xFF86,
  23150. nikhahitleftthai: 0xF899,
  23151. nikhahitthai: 0x0E4D,
  23152. nine: 0x0039,
  23153. ninearabic: 0x0669,
  23154. ninebengali: 0x09EF,
  23155. ninecircle: 0x2468,
  23156. ninecircleinversesansserif: 0x2792,
  23157. ninedeva: 0x096F,
  23158. ninegujarati: 0x0AEF,
  23159. ninegurmukhi: 0x0A6F,
  23160. ninehackarabic: 0x0669,
  23161. ninehangzhou: 0x3029,
  23162. nineideographicparen: 0x3228,
  23163. nineinferior: 0x2089,
  23164. ninemonospace: 0xFF19,
  23165. nineoldstyle: 0xF739,
  23166. nineparen: 0x247C,
  23167. nineperiod: 0x2490,
  23168. ninepersian: 0x06F9,
  23169. nineroman: 0x2178,
  23170. ninesuperior: 0x2079,
  23171. nineteencircle: 0x2472,
  23172. nineteenparen: 0x2486,
  23173. nineteenperiod: 0x249A,
  23174. ninethai: 0x0E59,
  23175. nj: 0x01CC,
  23176. njecyrillic: 0x045A,
  23177. nkatakana: 0x30F3,
  23178. nkatakanahalfwidth: 0xFF9D,
  23179. nlegrightlong: 0x019E,
  23180. nlinebelow: 0x1E49,
  23181. nmonospace: 0xFF4E,
  23182. nmsquare: 0x339A,
  23183. nnabengali: 0x09A3,
  23184. nnadeva: 0x0923,
  23185. nnagujarati: 0x0AA3,
  23186. nnagurmukhi: 0x0A23,
  23187. nnnadeva: 0x0929,
  23188. nohiragana: 0x306E,
  23189. nokatakana: 0x30CE,
  23190. nokatakanahalfwidth: 0xFF89,
  23191. nonbreakingspace: 0x00A0,
  23192. nonenthai: 0x0E13,
  23193. nonuthai: 0x0E19,
  23194. noonarabic: 0x0646,
  23195. noonfinalarabic: 0xFEE6,
  23196. noonghunnaarabic: 0x06BA,
  23197. noonghunnafinalarabic: 0xFB9F,
  23198. nooninitialarabic: 0xFEE7,
  23199. noonjeeminitialarabic: 0xFCD2,
  23200. noonjeemisolatedarabic: 0xFC4B,
  23201. noonmedialarabic: 0xFEE8,
  23202. noonmeeminitialarabic: 0xFCD5,
  23203. noonmeemisolatedarabic: 0xFC4E,
  23204. noonnoonfinalarabic: 0xFC8D,
  23205. notcontains: 0x220C,
  23206. notelement: 0x2209,
  23207. notelementof: 0x2209,
  23208. notequal: 0x2260,
  23209. notgreater: 0x226F,
  23210. notgreaternorequal: 0x2271,
  23211. notgreaternorless: 0x2279,
  23212. notidentical: 0x2262,
  23213. notless: 0x226E,
  23214. notlessnorequal: 0x2270,
  23215. notparallel: 0x2226,
  23216. notprecedes: 0x2280,
  23217. notsubset: 0x2284,
  23218. notsucceeds: 0x2281,
  23219. notsuperset: 0x2285,
  23220. nowarmenian: 0x0576,
  23221. nparen: 0x24A9,
  23222. nssquare: 0x33B1,
  23223. nsuperior: 0x207F,
  23224. ntilde: 0x00F1,
  23225. nu: 0x03BD,
  23226. nuhiragana: 0x306C,
  23227. nukatakana: 0x30CC,
  23228. nukatakanahalfwidth: 0xFF87,
  23229. nuktabengali: 0x09BC,
  23230. nuktadeva: 0x093C,
  23231. nuktagujarati: 0x0ABC,
  23232. nuktagurmukhi: 0x0A3C,
  23233. numbersign: 0x0023,
  23234. numbersignmonospace: 0xFF03,
  23235. numbersignsmall: 0xFE5F,
  23236. numeralsigngreek: 0x0374,
  23237. numeralsignlowergreek: 0x0375,
  23238. numero: 0x2116,
  23239. nun: 0x05E0,
  23240. nundagesh: 0xFB40,
  23241. nundageshhebrew: 0xFB40,
  23242. nunhebrew: 0x05E0,
  23243. nvsquare: 0x33B5,
  23244. nwsquare: 0x33BB,
  23245. nyabengali: 0x099E,
  23246. nyadeva: 0x091E,
  23247. nyagujarati: 0x0A9E,
  23248. nyagurmukhi: 0x0A1E,
  23249. o: 0x006F,
  23250. oacute: 0x00F3,
  23251. oangthai: 0x0E2D,
  23252. obarred: 0x0275,
  23253. obarredcyrillic: 0x04E9,
  23254. obarreddieresiscyrillic: 0x04EB,
  23255. obengali: 0x0993,
  23256. obopomofo: 0x311B,
  23257. obreve: 0x014F,
  23258. ocandradeva: 0x0911,
  23259. ocandragujarati: 0x0A91,
  23260. ocandravowelsigndeva: 0x0949,
  23261. ocandravowelsigngujarati: 0x0AC9,
  23262. ocaron: 0x01D2,
  23263. ocircle: 0x24DE,
  23264. ocircumflex: 0x00F4,
  23265. ocircumflexacute: 0x1ED1,
  23266. ocircumflexdotbelow: 0x1ED9,
  23267. ocircumflexgrave: 0x1ED3,
  23268. ocircumflexhookabove: 0x1ED5,
  23269. ocircumflextilde: 0x1ED7,
  23270. ocyrillic: 0x043E,
  23271. odblacute: 0x0151,
  23272. odblgrave: 0x020D,
  23273. odeva: 0x0913,
  23274. odieresis: 0x00F6,
  23275. odieresiscyrillic: 0x04E7,
  23276. odotbelow: 0x1ECD,
  23277. oe: 0x0153,
  23278. oekorean: 0x315A,
  23279. ogonek: 0x02DB,
  23280. ogonekcmb: 0x0328,
  23281. ograve: 0x00F2,
  23282. ogujarati: 0x0A93,
  23283. oharmenian: 0x0585,
  23284. ohiragana: 0x304A,
  23285. ohookabove: 0x1ECF,
  23286. ohorn: 0x01A1,
  23287. ohornacute: 0x1EDB,
  23288. ohorndotbelow: 0x1EE3,
  23289. ohorngrave: 0x1EDD,
  23290. ohornhookabove: 0x1EDF,
  23291. ohorntilde: 0x1EE1,
  23292. ohungarumlaut: 0x0151,
  23293. oi: 0x01A3,
  23294. oinvertedbreve: 0x020F,
  23295. okatakana: 0x30AA,
  23296. okatakanahalfwidth: 0xFF75,
  23297. okorean: 0x3157,
  23298. olehebrew: 0x05AB,
  23299. omacron: 0x014D,
  23300. omacronacute: 0x1E53,
  23301. omacrongrave: 0x1E51,
  23302. omdeva: 0x0950,
  23303. omega: 0x03C9,
  23304. omega1: 0x03D6,
  23305. omegacyrillic: 0x0461,
  23306. omegalatinclosed: 0x0277,
  23307. omegaroundcyrillic: 0x047B,
  23308. omegatitlocyrillic: 0x047D,
  23309. omegatonos: 0x03CE,
  23310. omgujarati: 0x0AD0,
  23311. omicron: 0x03BF,
  23312. omicrontonos: 0x03CC,
  23313. omonospace: 0xFF4F,
  23314. one: 0x0031,
  23315. onearabic: 0x0661,
  23316. onebengali: 0x09E7,
  23317. onecircle: 0x2460,
  23318. onecircleinversesansserif: 0x278A,
  23319. onedeva: 0x0967,
  23320. onedotenleader: 0x2024,
  23321. oneeighth: 0x215B,
  23322. onefitted: 0xF6DC,
  23323. onegujarati: 0x0AE7,
  23324. onegurmukhi: 0x0A67,
  23325. onehackarabic: 0x0661,
  23326. onehalf: 0x00BD,
  23327. onehangzhou: 0x3021,
  23328. oneideographicparen: 0x3220,
  23329. oneinferior: 0x2081,
  23330. onemonospace: 0xFF11,
  23331. onenumeratorbengali: 0x09F4,
  23332. oneoldstyle: 0xF731,
  23333. oneparen: 0x2474,
  23334. oneperiod: 0x2488,
  23335. onepersian: 0x06F1,
  23336. onequarter: 0x00BC,
  23337. oneroman: 0x2170,
  23338. onesuperior: 0x00B9,
  23339. onethai: 0x0E51,
  23340. onethird: 0x2153,
  23341. oogonek: 0x01EB,
  23342. oogonekmacron: 0x01ED,
  23343. oogurmukhi: 0x0A13,
  23344. oomatragurmukhi: 0x0A4B,
  23345. oopen: 0x0254,
  23346. oparen: 0x24AA,
  23347. openbullet: 0x25E6,
  23348. option: 0x2325,
  23349. ordfeminine: 0x00AA,
  23350. ordmasculine: 0x00BA,
  23351. orthogonal: 0x221F,
  23352. oshortdeva: 0x0912,
  23353. oshortvowelsigndeva: 0x094A,
  23354. oslash: 0x00F8,
  23355. oslashacute: 0x01FF,
  23356. osmallhiragana: 0x3049,
  23357. osmallkatakana: 0x30A9,
  23358. osmallkatakanahalfwidth: 0xFF6B,
  23359. ostrokeacute: 0x01FF,
  23360. osuperior: 0xF6F0,
  23361. otcyrillic: 0x047F,
  23362. otilde: 0x00F5,
  23363. otildeacute: 0x1E4D,
  23364. otildedieresis: 0x1E4F,
  23365. oubopomofo: 0x3121,
  23366. overline: 0x203E,
  23367. overlinecenterline: 0xFE4A,
  23368. overlinecmb: 0x0305,
  23369. overlinedashed: 0xFE49,
  23370. overlinedblwavy: 0xFE4C,
  23371. overlinewavy: 0xFE4B,
  23372. overscore: 0x00AF,
  23373. ovowelsignbengali: 0x09CB,
  23374. ovowelsigndeva: 0x094B,
  23375. ovowelsigngujarati: 0x0ACB,
  23376. p: 0x0070,
  23377. paampssquare: 0x3380,
  23378. paasentosquare: 0x332B,
  23379. pabengali: 0x09AA,
  23380. pacute: 0x1E55,
  23381. padeva: 0x092A,
  23382. pagedown: 0x21DF,
  23383. pageup: 0x21DE,
  23384. pagujarati: 0x0AAA,
  23385. pagurmukhi: 0x0A2A,
  23386. pahiragana: 0x3071,
  23387. paiyannoithai: 0x0E2F,
  23388. pakatakana: 0x30D1,
  23389. palatalizationcyrilliccmb: 0x0484,
  23390. palochkacyrillic: 0x04C0,
  23391. pansioskorean: 0x317F,
  23392. paragraph: 0x00B6,
  23393. parallel: 0x2225,
  23394. parenleft: 0x0028,
  23395. parenleftaltonearabic: 0xFD3E,
  23396. parenleftbt: 0xF8ED,
  23397. parenleftex: 0xF8EC,
  23398. parenleftinferior: 0x208D,
  23399. parenleftmonospace: 0xFF08,
  23400. parenleftsmall: 0xFE59,
  23401. parenleftsuperior: 0x207D,
  23402. parenlefttp: 0xF8EB,
  23403. parenleftvertical: 0xFE35,
  23404. parenright: 0x0029,
  23405. parenrightaltonearabic: 0xFD3F,
  23406. parenrightbt: 0xF8F8,
  23407. parenrightex: 0xF8F7,
  23408. parenrightinferior: 0x208E,
  23409. parenrightmonospace: 0xFF09,
  23410. parenrightsmall: 0xFE5A,
  23411. parenrightsuperior: 0x207E,
  23412. parenrighttp: 0xF8F6,
  23413. parenrightvertical: 0xFE36,
  23414. partialdiff: 0x2202,
  23415. paseqhebrew: 0x05C0,
  23416. pashtahebrew: 0x0599,
  23417. pasquare: 0x33A9,
  23418. patah: 0x05B7,
  23419. patah11: 0x05B7,
  23420. patah1d: 0x05B7,
  23421. patah2a: 0x05B7,
  23422. patahhebrew: 0x05B7,
  23423. patahnarrowhebrew: 0x05B7,
  23424. patahquarterhebrew: 0x05B7,
  23425. patahwidehebrew: 0x05B7,
  23426. pazerhebrew: 0x05A1,
  23427. pbopomofo: 0x3106,
  23428. pcircle: 0x24DF,
  23429. pdotaccent: 0x1E57,
  23430. pe: 0x05E4,
  23431. pecyrillic: 0x043F,
  23432. pedagesh: 0xFB44,
  23433. pedageshhebrew: 0xFB44,
  23434. peezisquare: 0x333B,
  23435. pefinaldageshhebrew: 0xFB43,
  23436. peharabic: 0x067E,
  23437. peharmenian: 0x057A,
  23438. pehebrew: 0x05E4,
  23439. pehfinalarabic: 0xFB57,
  23440. pehinitialarabic: 0xFB58,
  23441. pehiragana: 0x307A,
  23442. pehmedialarabic: 0xFB59,
  23443. pekatakana: 0x30DA,
  23444. pemiddlehookcyrillic: 0x04A7,
  23445. perafehebrew: 0xFB4E,
  23446. percent: 0x0025,
  23447. percentarabic: 0x066A,
  23448. percentmonospace: 0xFF05,
  23449. percentsmall: 0xFE6A,
  23450. period: 0x002E,
  23451. periodarmenian: 0x0589,
  23452. periodcentered: 0x00B7,
  23453. periodhalfwidth: 0xFF61,
  23454. periodinferior: 0xF6E7,
  23455. periodmonospace: 0xFF0E,
  23456. periodsmall: 0xFE52,
  23457. periodsuperior: 0xF6E8,
  23458. perispomenigreekcmb: 0x0342,
  23459. perpendicular: 0x22A5,
  23460. perthousand: 0x2030,
  23461. peseta: 0x20A7,
  23462. pfsquare: 0x338A,
  23463. phabengali: 0x09AB,
  23464. phadeva: 0x092B,
  23465. phagujarati: 0x0AAB,
  23466. phagurmukhi: 0x0A2B,
  23467. phi: 0x03C6,
  23468. phi1: 0x03D5,
  23469. phieuphacirclekorean: 0x327A,
  23470. phieuphaparenkorean: 0x321A,
  23471. phieuphcirclekorean: 0x326C,
  23472. phieuphkorean: 0x314D,
  23473. phieuphparenkorean: 0x320C,
  23474. philatin: 0x0278,
  23475. phinthuthai: 0x0E3A,
  23476. phisymbolgreek: 0x03D5,
  23477. phook: 0x01A5,
  23478. phophanthai: 0x0E1E,
  23479. phophungthai: 0x0E1C,
  23480. phosamphaothai: 0x0E20,
  23481. pi: 0x03C0,
  23482. pieupacirclekorean: 0x3273,
  23483. pieupaparenkorean: 0x3213,
  23484. pieupcieuckorean: 0x3176,
  23485. pieupcirclekorean: 0x3265,
  23486. pieupkiyeokkorean: 0x3172,
  23487. pieupkorean: 0x3142,
  23488. pieupparenkorean: 0x3205,
  23489. pieupsioskiyeokkorean: 0x3174,
  23490. pieupsioskorean: 0x3144,
  23491. pieupsiostikeutkorean: 0x3175,
  23492. pieupthieuthkorean: 0x3177,
  23493. pieuptikeutkorean: 0x3173,
  23494. pihiragana: 0x3074,
  23495. pikatakana: 0x30D4,
  23496. pisymbolgreek: 0x03D6,
  23497. piwrarmenian: 0x0583,
  23498. plus: 0x002B,
  23499. plusbelowcmb: 0x031F,
  23500. pluscircle: 0x2295,
  23501. plusminus: 0x00B1,
  23502. plusmod: 0x02D6,
  23503. plusmonospace: 0xFF0B,
  23504. plussmall: 0xFE62,
  23505. plussuperior: 0x207A,
  23506. pmonospace: 0xFF50,
  23507. pmsquare: 0x33D8,
  23508. pohiragana: 0x307D,
  23509. pointingindexdownwhite: 0x261F,
  23510. pointingindexleftwhite: 0x261C,
  23511. pointingindexrightwhite: 0x261E,
  23512. pointingindexupwhite: 0x261D,
  23513. pokatakana: 0x30DD,
  23514. poplathai: 0x0E1B,
  23515. postalmark: 0x3012,
  23516. postalmarkface: 0x3020,
  23517. pparen: 0x24AB,
  23518. precedes: 0x227A,
  23519. prescription: 0x211E,
  23520. primemod: 0x02B9,
  23521. primereversed: 0x2035,
  23522. product: 0x220F,
  23523. projective: 0x2305,
  23524. prolongedkana: 0x30FC,
  23525. propellor: 0x2318,
  23526. propersubset: 0x2282,
  23527. propersuperset: 0x2283,
  23528. proportion: 0x2237,
  23529. proportional: 0x221D,
  23530. psi: 0x03C8,
  23531. psicyrillic: 0x0471,
  23532. psilipneumatacyrilliccmb: 0x0486,
  23533. pssquare: 0x33B0,
  23534. puhiragana: 0x3077,
  23535. pukatakana: 0x30D7,
  23536. pvsquare: 0x33B4,
  23537. pwsquare: 0x33BA,
  23538. q: 0x0071,
  23539. qadeva: 0x0958,
  23540. qadmahebrew: 0x05A8,
  23541. qafarabic: 0x0642,
  23542. qaffinalarabic: 0xFED6,
  23543. qafinitialarabic: 0xFED7,
  23544. qafmedialarabic: 0xFED8,
  23545. qamats: 0x05B8,
  23546. qamats10: 0x05B8,
  23547. qamats1a: 0x05B8,
  23548. qamats1c: 0x05B8,
  23549. qamats27: 0x05B8,
  23550. qamats29: 0x05B8,
  23551. qamats33: 0x05B8,
  23552. qamatsde: 0x05B8,
  23553. qamatshebrew: 0x05B8,
  23554. qamatsnarrowhebrew: 0x05B8,
  23555. qamatsqatanhebrew: 0x05B8,
  23556. qamatsqatannarrowhebrew: 0x05B8,
  23557. qamatsqatanquarterhebrew: 0x05B8,
  23558. qamatsqatanwidehebrew: 0x05B8,
  23559. qamatsquarterhebrew: 0x05B8,
  23560. qamatswidehebrew: 0x05B8,
  23561. qarneyparahebrew: 0x059F,
  23562. qbopomofo: 0x3111,
  23563. qcircle: 0x24E0,
  23564. qhook: 0x02A0,
  23565. qmonospace: 0xFF51,
  23566. qof: 0x05E7,
  23567. qofdagesh: 0xFB47,
  23568. qofdageshhebrew: 0xFB47,
  23569. qofhebrew: 0x05E7,
  23570. qparen: 0x24AC,
  23571. quarternote: 0x2669,
  23572. qubuts: 0x05BB,
  23573. qubuts18: 0x05BB,
  23574. qubuts25: 0x05BB,
  23575. qubuts31: 0x05BB,
  23576. qubutshebrew: 0x05BB,
  23577. qubutsnarrowhebrew: 0x05BB,
  23578. qubutsquarterhebrew: 0x05BB,
  23579. qubutswidehebrew: 0x05BB,
  23580. question: 0x003F,
  23581. questionarabic: 0x061F,
  23582. questionarmenian: 0x055E,
  23583. questiondown: 0x00BF,
  23584. questiondownsmall: 0xF7BF,
  23585. questiongreek: 0x037E,
  23586. questionmonospace: 0xFF1F,
  23587. questionsmall: 0xF73F,
  23588. quotedbl: 0x0022,
  23589. quotedblbase: 0x201E,
  23590. quotedblleft: 0x201C,
  23591. quotedblmonospace: 0xFF02,
  23592. quotedblprime: 0x301E,
  23593. quotedblprimereversed: 0x301D,
  23594. quotedblright: 0x201D,
  23595. quoteleft: 0x2018,
  23596. quoteleftreversed: 0x201B,
  23597. quotereversed: 0x201B,
  23598. quoteright: 0x2019,
  23599. quoterightn: 0x0149,
  23600. quotesinglbase: 0x201A,
  23601. quotesingle: 0x0027,
  23602. quotesinglemonospace: 0xFF07,
  23603. r: 0x0072,
  23604. raarmenian: 0x057C,
  23605. rabengali: 0x09B0,
  23606. racute: 0x0155,
  23607. radeva: 0x0930,
  23608. radical: 0x221A,
  23609. radicalex: 0xF8E5,
  23610. radoverssquare: 0x33AE,
  23611. radoverssquaredsquare: 0x33AF,
  23612. radsquare: 0x33AD,
  23613. rafe: 0x05BF,
  23614. rafehebrew: 0x05BF,
  23615. ragujarati: 0x0AB0,
  23616. ragurmukhi: 0x0A30,
  23617. rahiragana: 0x3089,
  23618. rakatakana: 0x30E9,
  23619. rakatakanahalfwidth: 0xFF97,
  23620. ralowerdiagonalbengali: 0x09F1,
  23621. ramiddlediagonalbengali: 0x09F0,
  23622. ramshorn: 0x0264,
  23623. ratio: 0x2236,
  23624. rbopomofo: 0x3116,
  23625. rcaron: 0x0159,
  23626. rcedilla: 0x0157,
  23627. rcircle: 0x24E1,
  23628. rcommaaccent: 0x0157,
  23629. rdblgrave: 0x0211,
  23630. rdotaccent: 0x1E59,
  23631. rdotbelow: 0x1E5B,
  23632. rdotbelowmacron: 0x1E5D,
  23633. referencemark: 0x203B,
  23634. reflexsubset: 0x2286,
  23635. reflexsuperset: 0x2287,
  23636. registered: 0x00AE,
  23637. registersans: 0xF8E8,
  23638. registerserif: 0xF6DA,
  23639. reharabic: 0x0631,
  23640. reharmenian: 0x0580,
  23641. rehfinalarabic: 0xFEAE,
  23642. rehiragana: 0x308C,
  23643. rekatakana: 0x30EC,
  23644. rekatakanahalfwidth: 0xFF9A,
  23645. resh: 0x05E8,
  23646. reshdageshhebrew: 0xFB48,
  23647. reshhebrew: 0x05E8,
  23648. reversedtilde: 0x223D,
  23649. reviahebrew: 0x0597,
  23650. reviamugrashhebrew: 0x0597,
  23651. revlogicalnot: 0x2310,
  23652. rfishhook: 0x027E,
  23653. rfishhookreversed: 0x027F,
  23654. rhabengali: 0x09DD,
  23655. rhadeva: 0x095D,
  23656. rho: 0x03C1,
  23657. rhook: 0x027D,
  23658. rhookturned: 0x027B,
  23659. rhookturnedsuperior: 0x02B5,
  23660. rhosymbolgreek: 0x03F1,
  23661. rhotichookmod: 0x02DE,
  23662. rieulacirclekorean: 0x3271,
  23663. rieulaparenkorean: 0x3211,
  23664. rieulcirclekorean: 0x3263,
  23665. rieulhieuhkorean: 0x3140,
  23666. rieulkiyeokkorean: 0x313A,
  23667. rieulkiyeoksioskorean: 0x3169,
  23668. rieulkorean: 0x3139,
  23669. rieulmieumkorean: 0x313B,
  23670. rieulpansioskorean: 0x316C,
  23671. rieulparenkorean: 0x3203,
  23672. rieulphieuphkorean: 0x313F,
  23673. rieulpieupkorean: 0x313C,
  23674. rieulpieupsioskorean: 0x316B,
  23675. rieulsioskorean: 0x313D,
  23676. rieulthieuthkorean: 0x313E,
  23677. rieultikeutkorean: 0x316A,
  23678. rieulyeorinhieuhkorean: 0x316D,
  23679. rightangle: 0x221F,
  23680. righttackbelowcmb: 0x0319,
  23681. righttriangle: 0x22BF,
  23682. rihiragana: 0x308A,
  23683. rikatakana: 0x30EA,
  23684. rikatakanahalfwidth: 0xFF98,
  23685. ring: 0x02DA,
  23686. ringbelowcmb: 0x0325,
  23687. ringcmb: 0x030A,
  23688. ringhalfleft: 0x02BF,
  23689. ringhalfleftarmenian: 0x0559,
  23690. ringhalfleftbelowcmb: 0x031C,
  23691. ringhalfleftcentered: 0x02D3,
  23692. ringhalfright: 0x02BE,
  23693. ringhalfrightbelowcmb: 0x0339,
  23694. ringhalfrightcentered: 0x02D2,
  23695. rinvertedbreve: 0x0213,
  23696. rittorusquare: 0x3351,
  23697. rlinebelow: 0x1E5F,
  23698. rlongleg: 0x027C,
  23699. rlonglegturned: 0x027A,
  23700. rmonospace: 0xFF52,
  23701. rohiragana: 0x308D,
  23702. rokatakana: 0x30ED,
  23703. rokatakanahalfwidth: 0xFF9B,
  23704. roruathai: 0x0E23,
  23705. rparen: 0x24AD,
  23706. rrabengali: 0x09DC,
  23707. rradeva: 0x0931,
  23708. rragurmukhi: 0x0A5C,
  23709. rreharabic: 0x0691,
  23710. rrehfinalarabic: 0xFB8D,
  23711. rrvocalicbengali: 0x09E0,
  23712. rrvocalicdeva: 0x0960,
  23713. rrvocalicgujarati: 0x0AE0,
  23714. rrvocalicvowelsignbengali: 0x09C4,
  23715. rrvocalicvowelsigndeva: 0x0944,
  23716. rrvocalicvowelsigngujarati: 0x0AC4,
  23717. rsuperior: 0xF6F1,
  23718. rtblock: 0x2590,
  23719. rturned: 0x0279,
  23720. rturnedsuperior: 0x02B4,
  23721. ruhiragana: 0x308B,
  23722. rukatakana: 0x30EB,
  23723. rukatakanahalfwidth: 0xFF99,
  23724. rupeemarkbengali: 0x09F2,
  23725. rupeesignbengali: 0x09F3,
  23726. rupiah: 0xF6DD,
  23727. ruthai: 0x0E24,
  23728. rvocalicbengali: 0x098B,
  23729. rvocalicdeva: 0x090B,
  23730. rvocalicgujarati: 0x0A8B,
  23731. rvocalicvowelsignbengali: 0x09C3,
  23732. rvocalicvowelsigndeva: 0x0943,
  23733. rvocalicvowelsigngujarati: 0x0AC3,
  23734. s: 0x0073,
  23735. sabengali: 0x09B8,
  23736. sacute: 0x015B,
  23737. sacutedotaccent: 0x1E65,
  23738. sadarabic: 0x0635,
  23739. sadeva: 0x0938,
  23740. sadfinalarabic: 0xFEBA,
  23741. sadinitialarabic: 0xFEBB,
  23742. sadmedialarabic: 0xFEBC,
  23743. sagujarati: 0x0AB8,
  23744. sagurmukhi: 0x0A38,
  23745. sahiragana: 0x3055,
  23746. sakatakana: 0x30B5,
  23747. sakatakanahalfwidth: 0xFF7B,
  23748. sallallahoualayhewasallamarabic: 0xFDFA,
  23749. samekh: 0x05E1,
  23750. samekhdagesh: 0xFB41,
  23751. samekhdageshhebrew: 0xFB41,
  23752. samekhhebrew: 0x05E1,
  23753. saraaathai: 0x0E32,
  23754. saraaethai: 0x0E41,
  23755. saraaimaimalaithai: 0x0E44,
  23756. saraaimaimuanthai: 0x0E43,
  23757. saraamthai: 0x0E33,
  23758. saraathai: 0x0E30,
  23759. saraethai: 0x0E40,
  23760. saraiileftthai: 0xF886,
  23761. saraiithai: 0x0E35,
  23762. saraileftthai: 0xF885,
  23763. saraithai: 0x0E34,
  23764. saraothai: 0x0E42,
  23765. saraueeleftthai: 0xF888,
  23766. saraueethai: 0x0E37,
  23767. saraueleftthai: 0xF887,
  23768. sarauethai: 0x0E36,
  23769. sarauthai: 0x0E38,
  23770. sarauuthai: 0x0E39,
  23771. sbopomofo: 0x3119,
  23772. scaron: 0x0161,
  23773. scarondotaccent: 0x1E67,
  23774. scedilla: 0x015F,
  23775. schwa: 0x0259,
  23776. schwacyrillic: 0x04D9,
  23777. schwadieresiscyrillic: 0x04DB,
  23778. schwahook: 0x025A,
  23779. scircle: 0x24E2,
  23780. scircumflex: 0x015D,
  23781. scommaaccent: 0x0219,
  23782. sdotaccent: 0x1E61,
  23783. sdotbelow: 0x1E63,
  23784. sdotbelowdotaccent: 0x1E69,
  23785. seagullbelowcmb: 0x033C,
  23786. second: 0x2033,
  23787. secondtonechinese: 0x02CA,
  23788. section: 0x00A7,
  23789. seenarabic: 0x0633,
  23790. seenfinalarabic: 0xFEB2,
  23791. seeninitialarabic: 0xFEB3,
  23792. seenmedialarabic: 0xFEB4,
  23793. segol: 0x05B6,
  23794. segol13: 0x05B6,
  23795. segol1f: 0x05B6,
  23796. segol2c: 0x05B6,
  23797. segolhebrew: 0x05B6,
  23798. segolnarrowhebrew: 0x05B6,
  23799. segolquarterhebrew: 0x05B6,
  23800. segoltahebrew: 0x0592,
  23801. segolwidehebrew: 0x05B6,
  23802. seharmenian: 0x057D,
  23803. sehiragana: 0x305B,
  23804. sekatakana: 0x30BB,
  23805. sekatakanahalfwidth: 0xFF7E,
  23806. semicolon: 0x003B,
  23807. semicolonarabic: 0x061B,
  23808. semicolonmonospace: 0xFF1B,
  23809. semicolonsmall: 0xFE54,
  23810. semivoicedmarkkana: 0x309C,
  23811. semivoicedmarkkanahalfwidth: 0xFF9F,
  23812. sentisquare: 0x3322,
  23813. sentosquare: 0x3323,
  23814. seven: 0x0037,
  23815. sevenarabic: 0x0667,
  23816. sevenbengali: 0x09ED,
  23817. sevencircle: 0x2466,
  23818. sevencircleinversesansserif: 0x2790,
  23819. sevendeva: 0x096D,
  23820. seveneighths: 0x215E,
  23821. sevengujarati: 0x0AED,
  23822. sevengurmukhi: 0x0A6D,
  23823. sevenhackarabic: 0x0667,
  23824. sevenhangzhou: 0x3027,
  23825. sevenideographicparen: 0x3226,
  23826. seveninferior: 0x2087,
  23827. sevenmonospace: 0xFF17,
  23828. sevenoldstyle: 0xF737,
  23829. sevenparen: 0x247A,
  23830. sevenperiod: 0x248E,
  23831. sevenpersian: 0x06F7,
  23832. sevenroman: 0x2176,
  23833. sevensuperior: 0x2077,
  23834. seventeencircle: 0x2470,
  23835. seventeenparen: 0x2484,
  23836. seventeenperiod: 0x2498,
  23837. seventhai: 0x0E57,
  23838. sfthyphen: 0x00AD,
  23839. shaarmenian: 0x0577,
  23840. shabengali: 0x09B6,
  23841. shacyrillic: 0x0448,
  23842. shaddaarabic: 0x0651,
  23843. shaddadammaarabic: 0xFC61,
  23844. shaddadammatanarabic: 0xFC5E,
  23845. shaddafathaarabic: 0xFC60,
  23846. shaddakasraarabic: 0xFC62,
  23847. shaddakasratanarabic: 0xFC5F,
  23848. shade: 0x2592,
  23849. shadedark: 0x2593,
  23850. shadelight: 0x2591,
  23851. shademedium: 0x2592,
  23852. shadeva: 0x0936,
  23853. shagujarati: 0x0AB6,
  23854. shagurmukhi: 0x0A36,
  23855. shalshelethebrew: 0x0593,
  23856. shbopomofo: 0x3115,
  23857. shchacyrillic: 0x0449,
  23858. sheenarabic: 0x0634,
  23859. sheenfinalarabic: 0xFEB6,
  23860. sheeninitialarabic: 0xFEB7,
  23861. sheenmedialarabic: 0xFEB8,
  23862. sheicoptic: 0x03E3,
  23863. sheqel: 0x20AA,
  23864. sheqelhebrew: 0x20AA,
  23865. sheva: 0x05B0,
  23866. sheva115: 0x05B0,
  23867. sheva15: 0x05B0,
  23868. sheva22: 0x05B0,
  23869. sheva2e: 0x05B0,
  23870. shevahebrew: 0x05B0,
  23871. shevanarrowhebrew: 0x05B0,
  23872. shevaquarterhebrew: 0x05B0,
  23873. shevawidehebrew: 0x05B0,
  23874. shhacyrillic: 0x04BB,
  23875. shimacoptic: 0x03ED,
  23876. shin: 0x05E9,
  23877. shindagesh: 0xFB49,
  23878. shindageshhebrew: 0xFB49,
  23879. shindageshshindot: 0xFB2C,
  23880. shindageshshindothebrew: 0xFB2C,
  23881. shindageshsindot: 0xFB2D,
  23882. shindageshsindothebrew: 0xFB2D,
  23883. shindothebrew: 0x05C1,
  23884. shinhebrew: 0x05E9,
  23885. shinshindot: 0xFB2A,
  23886. shinshindothebrew: 0xFB2A,
  23887. shinsindot: 0xFB2B,
  23888. shinsindothebrew: 0xFB2B,
  23889. shook: 0x0282,
  23890. sigma: 0x03C3,
  23891. sigma1: 0x03C2,
  23892. sigmafinal: 0x03C2,
  23893. sigmalunatesymbolgreek: 0x03F2,
  23894. sihiragana: 0x3057,
  23895. sikatakana: 0x30B7,
  23896. sikatakanahalfwidth: 0xFF7C,
  23897. siluqhebrew: 0x05BD,
  23898. siluqlefthebrew: 0x05BD,
  23899. similar: 0x223C,
  23900. sindothebrew: 0x05C2,
  23901. siosacirclekorean: 0x3274,
  23902. siosaparenkorean: 0x3214,
  23903. sioscieuckorean: 0x317E,
  23904. sioscirclekorean: 0x3266,
  23905. sioskiyeokkorean: 0x317A,
  23906. sioskorean: 0x3145,
  23907. siosnieunkorean: 0x317B,
  23908. siosparenkorean: 0x3206,
  23909. siospieupkorean: 0x317D,
  23910. siostikeutkorean: 0x317C,
  23911. six: 0x0036,
  23912. sixarabic: 0x0666,
  23913. sixbengali: 0x09EC,
  23914. sixcircle: 0x2465,
  23915. sixcircleinversesansserif: 0x278F,
  23916. sixdeva: 0x096C,
  23917. sixgujarati: 0x0AEC,
  23918. sixgurmukhi: 0x0A6C,
  23919. sixhackarabic: 0x0666,
  23920. sixhangzhou: 0x3026,
  23921. sixideographicparen: 0x3225,
  23922. sixinferior: 0x2086,
  23923. sixmonospace: 0xFF16,
  23924. sixoldstyle: 0xF736,
  23925. sixparen: 0x2479,
  23926. sixperiod: 0x248D,
  23927. sixpersian: 0x06F6,
  23928. sixroman: 0x2175,
  23929. sixsuperior: 0x2076,
  23930. sixteencircle: 0x246F,
  23931. sixteencurrencydenominatorbengali: 0x09F9,
  23932. sixteenparen: 0x2483,
  23933. sixteenperiod: 0x2497,
  23934. sixthai: 0x0E56,
  23935. slash: 0x002F,
  23936. slashmonospace: 0xFF0F,
  23937. slong: 0x017F,
  23938. slongdotaccent: 0x1E9B,
  23939. smileface: 0x263A,
  23940. smonospace: 0xFF53,
  23941. sofpasuqhebrew: 0x05C3,
  23942. softhyphen: 0x00AD,
  23943. softsigncyrillic: 0x044C,
  23944. sohiragana: 0x305D,
  23945. sokatakana: 0x30BD,
  23946. sokatakanahalfwidth: 0xFF7F,
  23947. soliduslongoverlaycmb: 0x0338,
  23948. solidusshortoverlaycmb: 0x0337,
  23949. sorusithai: 0x0E29,
  23950. sosalathai: 0x0E28,
  23951. sosothai: 0x0E0B,
  23952. sosuathai: 0x0E2A,
  23953. space: 0x0020,
  23954. spacehackarabic: 0x0020,
  23955. spade: 0x2660,
  23956. spadesuitblack: 0x2660,
  23957. spadesuitwhite: 0x2664,
  23958. sparen: 0x24AE,
  23959. squarebelowcmb: 0x033B,
  23960. squarecc: 0x33C4,
  23961. squarecm: 0x339D,
  23962. squarediagonalcrosshatchfill: 0x25A9,
  23963. squarehorizontalfill: 0x25A4,
  23964. squarekg: 0x338F,
  23965. squarekm: 0x339E,
  23966. squarekmcapital: 0x33CE,
  23967. squareln: 0x33D1,
  23968. squarelog: 0x33D2,
  23969. squaremg: 0x338E,
  23970. squaremil: 0x33D5,
  23971. squaremm: 0x339C,
  23972. squaremsquared: 0x33A1,
  23973. squareorthogonalcrosshatchfill: 0x25A6,
  23974. squareupperlefttolowerrightfill: 0x25A7,
  23975. squareupperrighttolowerleftfill: 0x25A8,
  23976. squareverticalfill: 0x25A5,
  23977. squarewhitewithsmallblack: 0x25A3,
  23978. srsquare: 0x33DB,
  23979. ssabengali: 0x09B7,
  23980. ssadeva: 0x0937,
  23981. ssagujarati: 0x0AB7,
  23982. ssangcieuckorean: 0x3149,
  23983. ssanghieuhkorean: 0x3185,
  23984. ssangieungkorean: 0x3180,
  23985. ssangkiyeokkorean: 0x3132,
  23986. ssangnieunkorean: 0x3165,
  23987. ssangpieupkorean: 0x3143,
  23988. ssangsioskorean: 0x3146,
  23989. ssangtikeutkorean: 0x3138,
  23990. ssuperior: 0xF6F2,
  23991. sterling: 0x00A3,
  23992. sterlingmonospace: 0xFFE1,
  23993. strokelongoverlaycmb: 0x0336,
  23994. strokeshortoverlaycmb: 0x0335,
  23995. subset: 0x2282,
  23996. subsetnotequal: 0x228A,
  23997. subsetorequal: 0x2286,
  23998. succeeds: 0x227B,
  23999. suchthat: 0x220B,
  24000. suhiragana: 0x3059,
  24001. sukatakana: 0x30B9,
  24002. sukatakanahalfwidth: 0xFF7D,
  24003. sukunarabic: 0x0652,
  24004. summation: 0x2211,
  24005. sun: 0x263C,
  24006. superset: 0x2283,
  24007. supersetnotequal: 0x228B,
  24008. supersetorequal: 0x2287,
  24009. svsquare: 0x33DC,
  24010. syouwaerasquare: 0x337C,
  24011. t: 0x0074,
  24012. tabengali: 0x09A4,
  24013. tackdown: 0x22A4,
  24014. tackleft: 0x22A3,
  24015. tadeva: 0x0924,
  24016. tagujarati: 0x0AA4,
  24017. tagurmukhi: 0x0A24,
  24018. taharabic: 0x0637,
  24019. tahfinalarabic: 0xFEC2,
  24020. tahinitialarabic: 0xFEC3,
  24021. tahiragana: 0x305F,
  24022. tahmedialarabic: 0xFEC4,
  24023. taisyouerasquare: 0x337D,
  24024. takatakana: 0x30BF,
  24025. takatakanahalfwidth: 0xFF80,
  24026. tatweelarabic: 0x0640,
  24027. tau: 0x03C4,
  24028. tav: 0x05EA,
  24029. tavdages: 0xFB4A,
  24030. tavdagesh: 0xFB4A,
  24031. tavdageshhebrew: 0xFB4A,
  24032. tavhebrew: 0x05EA,
  24033. tbar: 0x0167,
  24034. tbopomofo: 0x310A,
  24035. tcaron: 0x0165,
  24036. tccurl: 0x02A8,
  24037. tcedilla: 0x0163,
  24038. tcheharabic: 0x0686,
  24039. tchehfinalarabic: 0xFB7B,
  24040. tchehinitialarabic: 0xFB7C,
  24041. tchehmedialarabic: 0xFB7D,
  24042. tcircle: 0x24E3,
  24043. tcircumflexbelow: 0x1E71,
  24044. tcommaaccent: 0x0163,
  24045. tdieresis: 0x1E97,
  24046. tdotaccent: 0x1E6B,
  24047. tdotbelow: 0x1E6D,
  24048. tecyrillic: 0x0442,
  24049. tedescendercyrillic: 0x04AD,
  24050. teharabic: 0x062A,
  24051. tehfinalarabic: 0xFE96,
  24052. tehhahinitialarabic: 0xFCA2,
  24053. tehhahisolatedarabic: 0xFC0C,
  24054. tehinitialarabic: 0xFE97,
  24055. tehiragana: 0x3066,
  24056. tehjeeminitialarabic: 0xFCA1,
  24057. tehjeemisolatedarabic: 0xFC0B,
  24058. tehmarbutaarabic: 0x0629,
  24059. tehmarbutafinalarabic: 0xFE94,
  24060. tehmedialarabic: 0xFE98,
  24061. tehmeeminitialarabic: 0xFCA4,
  24062. tehmeemisolatedarabic: 0xFC0E,
  24063. tehnoonfinalarabic: 0xFC73,
  24064. tekatakana: 0x30C6,
  24065. tekatakanahalfwidth: 0xFF83,
  24066. telephone: 0x2121,
  24067. telephoneblack: 0x260E,
  24068. telishagedolahebrew: 0x05A0,
  24069. telishaqetanahebrew: 0x05A9,
  24070. tencircle: 0x2469,
  24071. tenideographicparen: 0x3229,
  24072. tenparen: 0x247D,
  24073. tenperiod: 0x2491,
  24074. tenroman: 0x2179,
  24075. tesh: 0x02A7,
  24076. tet: 0x05D8,
  24077. tetdagesh: 0xFB38,
  24078. tetdageshhebrew: 0xFB38,
  24079. tethebrew: 0x05D8,
  24080. tetsecyrillic: 0x04B5,
  24081. tevirhebrew: 0x059B,
  24082. tevirlefthebrew: 0x059B,
  24083. thabengali: 0x09A5,
  24084. thadeva: 0x0925,
  24085. thagujarati: 0x0AA5,
  24086. thagurmukhi: 0x0A25,
  24087. thalarabic: 0x0630,
  24088. thalfinalarabic: 0xFEAC,
  24089. thanthakhatlowleftthai: 0xF898,
  24090. thanthakhatlowrightthai: 0xF897,
  24091. thanthakhatthai: 0x0E4C,
  24092. thanthakhatupperleftthai: 0xF896,
  24093. theharabic: 0x062B,
  24094. thehfinalarabic: 0xFE9A,
  24095. thehinitialarabic: 0xFE9B,
  24096. thehmedialarabic: 0xFE9C,
  24097. thereexists: 0x2203,
  24098. therefore: 0x2234,
  24099. theta: 0x03B8,
  24100. theta1: 0x03D1,
  24101. thetasymbolgreek: 0x03D1,
  24102. thieuthacirclekorean: 0x3279,
  24103. thieuthaparenkorean: 0x3219,
  24104. thieuthcirclekorean: 0x326B,
  24105. thieuthkorean: 0x314C,
  24106. thieuthparenkorean: 0x320B,
  24107. thirteencircle: 0x246C,
  24108. thirteenparen: 0x2480,
  24109. thirteenperiod: 0x2494,
  24110. thonangmonthothai: 0x0E11,
  24111. thook: 0x01AD,
  24112. thophuthaothai: 0x0E12,
  24113. thorn: 0x00FE,
  24114. thothahanthai: 0x0E17,
  24115. thothanthai: 0x0E10,
  24116. thothongthai: 0x0E18,
  24117. thothungthai: 0x0E16,
  24118. thousandcyrillic: 0x0482,
  24119. thousandsseparatorarabic: 0x066C,
  24120. thousandsseparatorpersian: 0x066C,
  24121. three: 0x0033,
  24122. threearabic: 0x0663,
  24123. threebengali: 0x09E9,
  24124. threecircle: 0x2462,
  24125. threecircleinversesansserif: 0x278C,
  24126. threedeva: 0x0969,
  24127. threeeighths: 0x215C,
  24128. threegujarati: 0x0AE9,
  24129. threegurmukhi: 0x0A69,
  24130. threehackarabic: 0x0663,
  24131. threehangzhou: 0x3023,
  24132. threeideographicparen: 0x3222,
  24133. threeinferior: 0x2083,
  24134. threemonospace: 0xFF13,
  24135. threenumeratorbengali: 0x09F6,
  24136. threeoldstyle: 0xF733,
  24137. threeparen: 0x2476,
  24138. threeperiod: 0x248A,
  24139. threepersian: 0x06F3,
  24140. threequarters: 0x00BE,
  24141. threequartersemdash: 0xF6DE,
  24142. threeroman: 0x2172,
  24143. threesuperior: 0x00B3,
  24144. threethai: 0x0E53,
  24145. thzsquare: 0x3394,
  24146. tihiragana: 0x3061,
  24147. tikatakana: 0x30C1,
  24148. tikatakanahalfwidth: 0xFF81,
  24149. tikeutacirclekorean: 0x3270,
  24150. tikeutaparenkorean: 0x3210,
  24151. tikeutcirclekorean: 0x3262,
  24152. tikeutkorean: 0x3137,
  24153. tikeutparenkorean: 0x3202,
  24154. tilde: 0x02DC,
  24155. tildebelowcmb: 0x0330,
  24156. tildecmb: 0x0303,
  24157. tildecomb: 0x0303,
  24158. tildedoublecmb: 0x0360,
  24159. tildeoperator: 0x223C,
  24160. tildeoverlaycmb: 0x0334,
  24161. tildeverticalcmb: 0x033E,
  24162. timescircle: 0x2297,
  24163. tipehahebrew: 0x0596,
  24164. tipehalefthebrew: 0x0596,
  24165. tippigurmukhi: 0x0A70,
  24166. titlocyrilliccmb: 0x0483,
  24167. tiwnarmenian: 0x057F,
  24168. tlinebelow: 0x1E6F,
  24169. tmonospace: 0xFF54,
  24170. toarmenian: 0x0569,
  24171. tohiragana: 0x3068,
  24172. tokatakana: 0x30C8,
  24173. tokatakanahalfwidth: 0xFF84,
  24174. tonebarextrahighmod: 0x02E5,
  24175. tonebarextralowmod: 0x02E9,
  24176. tonebarhighmod: 0x02E6,
  24177. tonebarlowmod: 0x02E8,
  24178. tonebarmidmod: 0x02E7,
  24179. tonefive: 0x01BD,
  24180. tonesix: 0x0185,
  24181. tonetwo: 0x01A8,
  24182. tonos: 0x0384,
  24183. tonsquare: 0x3327,
  24184. topatakthai: 0x0E0F,
  24185. tortoiseshellbracketleft: 0x3014,
  24186. tortoiseshellbracketleftsmall: 0xFE5D,
  24187. tortoiseshellbracketleftvertical: 0xFE39,
  24188. tortoiseshellbracketright: 0x3015,
  24189. tortoiseshellbracketrightsmall: 0xFE5E,
  24190. tortoiseshellbracketrightvertical: 0xFE3A,
  24191. totaothai: 0x0E15,
  24192. tpalatalhook: 0x01AB,
  24193. tparen: 0x24AF,
  24194. trademark: 0x2122,
  24195. trademarksans: 0xF8EA,
  24196. trademarkserif: 0xF6DB,
  24197. tretroflexhook: 0x0288,
  24198. triagdn: 0x25BC,
  24199. triaglf: 0x25C4,
  24200. triagrt: 0x25BA,
  24201. triagup: 0x25B2,
  24202. ts: 0x02A6,
  24203. tsadi: 0x05E6,
  24204. tsadidagesh: 0xFB46,
  24205. tsadidageshhebrew: 0xFB46,
  24206. tsadihebrew: 0x05E6,
  24207. tsecyrillic: 0x0446,
  24208. tsere: 0x05B5,
  24209. tsere12: 0x05B5,
  24210. tsere1e: 0x05B5,
  24211. tsere2b: 0x05B5,
  24212. tserehebrew: 0x05B5,
  24213. tserenarrowhebrew: 0x05B5,
  24214. tserequarterhebrew: 0x05B5,
  24215. tserewidehebrew: 0x05B5,
  24216. tshecyrillic: 0x045B,
  24217. tsuperior: 0xF6F3,
  24218. ttabengali: 0x099F,
  24219. ttadeva: 0x091F,
  24220. ttagujarati: 0x0A9F,
  24221. ttagurmukhi: 0x0A1F,
  24222. tteharabic: 0x0679,
  24223. ttehfinalarabic: 0xFB67,
  24224. ttehinitialarabic: 0xFB68,
  24225. ttehmedialarabic: 0xFB69,
  24226. tthabengali: 0x09A0,
  24227. tthadeva: 0x0920,
  24228. tthagujarati: 0x0AA0,
  24229. tthagurmukhi: 0x0A20,
  24230. tturned: 0x0287,
  24231. tuhiragana: 0x3064,
  24232. tukatakana: 0x30C4,
  24233. tukatakanahalfwidth: 0xFF82,
  24234. tusmallhiragana: 0x3063,
  24235. tusmallkatakana: 0x30C3,
  24236. tusmallkatakanahalfwidth: 0xFF6F,
  24237. twelvecircle: 0x246B,
  24238. twelveparen: 0x247F,
  24239. twelveperiod: 0x2493,
  24240. twelveroman: 0x217B,
  24241. twentycircle: 0x2473,
  24242. twentyhangzhou: 0x5344,
  24243. twentyparen: 0x2487,
  24244. twentyperiod: 0x249B,
  24245. two: 0x0032,
  24246. twoarabic: 0x0662,
  24247. twobengali: 0x09E8,
  24248. twocircle: 0x2461,
  24249. twocircleinversesansserif: 0x278B,
  24250. twodeva: 0x0968,
  24251. twodotenleader: 0x2025,
  24252. twodotleader: 0x2025,
  24253. twodotleadervertical: 0xFE30,
  24254. twogujarati: 0x0AE8,
  24255. twogurmukhi: 0x0A68,
  24256. twohackarabic: 0x0662,
  24257. twohangzhou: 0x3022,
  24258. twoideographicparen: 0x3221,
  24259. twoinferior: 0x2082,
  24260. twomonospace: 0xFF12,
  24261. twonumeratorbengali: 0x09F5,
  24262. twooldstyle: 0xF732,
  24263. twoparen: 0x2475,
  24264. twoperiod: 0x2489,
  24265. twopersian: 0x06F2,
  24266. tworoman: 0x2171,
  24267. twostroke: 0x01BB,
  24268. twosuperior: 0x00B2,
  24269. twothai: 0x0E52,
  24270. twothirds: 0x2154,
  24271. u: 0x0075,
  24272. uacute: 0x00FA,
  24273. ubar: 0x0289,
  24274. ubengali: 0x0989,
  24275. ubopomofo: 0x3128,
  24276. ubreve: 0x016D,
  24277. ucaron: 0x01D4,
  24278. ucircle: 0x24E4,
  24279. ucircumflex: 0x00FB,
  24280. ucircumflexbelow: 0x1E77,
  24281. ucyrillic: 0x0443,
  24282. udattadeva: 0x0951,
  24283. udblacute: 0x0171,
  24284. udblgrave: 0x0215,
  24285. udeva: 0x0909,
  24286. udieresis: 0x00FC,
  24287. udieresisacute: 0x01D8,
  24288. udieresisbelow: 0x1E73,
  24289. udieresiscaron: 0x01DA,
  24290. udieresiscyrillic: 0x04F1,
  24291. udieresisgrave: 0x01DC,
  24292. udieresismacron: 0x01D6,
  24293. udotbelow: 0x1EE5,
  24294. ugrave: 0x00F9,
  24295. ugujarati: 0x0A89,
  24296. ugurmukhi: 0x0A09,
  24297. uhiragana: 0x3046,
  24298. uhookabove: 0x1EE7,
  24299. uhorn: 0x01B0,
  24300. uhornacute: 0x1EE9,
  24301. uhorndotbelow: 0x1EF1,
  24302. uhorngrave: 0x1EEB,
  24303. uhornhookabove: 0x1EED,
  24304. uhorntilde: 0x1EEF,
  24305. uhungarumlaut: 0x0171,
  24306. uhungarumlautcyrillic: 0x04F3,
  24307. uinvertedbreve: 0x0217,
  24308. ukatakana: 0x30A6,
  24309. ukatakanahalfwidth: 0xFF73,
  24310. ukcyrillic: 0x0479,
  24311. ukorean: 0x315C,
  24312. umacron: 0x016B,
  24313. umacroncyrillic: 0x04EF,
  24314. umacrondieresis: 0x1E7B,
  24315. umatragurmukhi: 0x0A41,
  24316. umonospace: 0xFF55,
  24317. underscore: 0x005F,
  24318. underscoredbl: 0x2017,
  24319. underscoremonospace: 0xFF3F,
  24320. underscorevertical: 0xFE33,
  24321. underscorewavy: 0xFE4F,
  24322. union: 0x222A,
  24323. universal: 0x2200,
  24324. uogonek: 0x0173,
  24325. uparen: 0x24B0,
  24326. upblock: 0x2580,
  24327. upperdothebrew: 0x05C4,
  24328. upsilon: 0x03C5,
  24329. upsilondieresis: 0x03CB,
  24330. upsilondieresistonos: 0x03B0,
  24331. upsilonlatin: 0x028A,
  24332. upsilontonos: 0x03CD,
  24333. uptackbelowcmb: 0x031D,
  24334. uptackmod: 0x02D4,
  24335. uragurmukhi: 0x0A73,
  24336. uring: 0x016F,
  24337. ushortcyrillic: 0x045E,
  24338. usmallhiragana: 0x3045,
  24339. usmallkatakana: 0x30A5,
  24340. usmallkatakanahalfwidth: 0xFF69,
  24341. ustraightcyrillic: 0x04AF,
  24342. ustraightstrokecyrillic: 0x04B1,
  24343. utilde: 0x0169,
  24344. utildeacute: 0x1E79,
  24345. utildebelow: 0x1E75,
  24346. uubengali: 0x098A,
  24347. uudeva: 0x090A,
  24348. uugujarati: 0x0A8A,
  24349. uugurmukhi: 0x0A0A,
  24350. uumatragurmukhi: 0x0A42,
  24351. uuvowelsignbengali: 0x09C2,
  24352. uuvowelsigndeva: 0x0942,
  24353. uuvowelsigngujarati: 0x0AC2,
  24354. uvowelsignbengali: 0x09C1,
  24355. uvowelsigndeva: 0x0941,
  24356. uvowelsigngujarati: 0x0AC1,
  24357. v: 0x0076,
  24358. vadeva: 0x0935,
  24359. vagujarati: 0x0AB5,
  24360. vagurmukhi: 0x0A35,
  24361. vakatakana: 0x30F7,
  24362. vav: 0x05D5,
  24363. vavdagesh: 0xFB35,
  24364. vavdagesh65: 0xFB35,
  24365. vavdageshhebrew: 0xFB35,
  24366. vavhebrew: 0x05D5,
  24367. vavholam: 0xFB4B,
  24368. vavholamhebrew: 0xFB4B,
  24369. vavvavhebrew: 0x05F0,
  24370. vavyodhebrew: 0x05F1,
  24371. vcircle: 0x24E5,
  24372. vdotbelow: 0x1E7F,
  24373. vecyrillic: 0x0432,
  24374. veharabic: 0x06A4,
  24375. vehfinalarabic: 0xFB6B,
  24376. vehinitialarabic: 0xFB6C,
  24377. vehmedialarabic: 0xFB6D,
  24378. vekatakana: 0x30F9,
  24379. venus: 0x2640,
  24380. verticalbar: 0x007C,
  24381. verticallineabovecmb: 0x030D,
  24382. verticallinebelowcmb: 0x0329,
  24383. verticallinelowmod: 0x02CC,
  24384. verticallinemod: 0x02C8,
  24385. vewarmenian: 0x057E,
  24386. vhook: 0x028B,
  24387. vikatakana: 0x30F8,
  24388. viramabengali: 0x09CD,
  24389. viramadeva: 0x094D,
  24390. viramagujarati: 0x0ACD,
  24391. visargabengali: 0x0983,
  24392. visargadeva: 0x0903,
  24393. visargagujarati: 0x0A83,
  24394. vmonospace: 0xFF56,
  24395. voarmenian: 0x0578,
  24396. voicediterationhiragana: 0x309E,
  24397. voicediterationkatakana: 0x30FE,
  24398. voicedmarkkana: 0x309B,
  24399. voicedmarkkanahalfwidth: 0xFF9E,
  24400. vokatakana: 0x30FA,
  24401. vparen: 0x24B1,
  24402. vtilde: 0x1E7D,
  24403. vturned: 0x028C,
  24404. vuhiragana: 0x3094,
  24405. vukatakana: 0x30F4,
  24406. w: 0x0077,
  24407. wacute: 0x1E83,
  24408. waekorean: 0x3159,
  24409. wahiragana: 0x308F,
  24410. wakatakana: 0x30EF,
  24411. wakatakanahalfwidth: 0xFF9C,
  24412. wakorean: 0x3158,
  24413. wasmallhiragana: 0x308E,
  24414. wasmallkatakana: 0x30EE,
  24415. wattosquare: 0x3357,
  24416. wavedash: 0x301C,
  24417. wavyunderscorevertical: 0xFE34,
  24418. wawarabic: 0x0648,
  24419. wawfinalarabic: 0xFEEE,
  24420. wawhamzaabovearabic: 0x0624,
  24421. wawhamzaabovefinalarabic: 0xFE86,
  24422. wbsquare: 0x33DD,
  24423. wcircle: 0x24E6,
  24424. wcircumflex: 0x0175,
  24425. wdieresis: 0x1E85,
  24426. wdotaccent: 0x1E87,
  24427. wdotbelow: 0x1E89,
  24428. wehiragana: 0x3091,
  24429. weierstrass: 0x2118,
  24430. wekatakana: 0x30F1,
  24431. wekorean: 0x315E,
  24432. weokorean: 0x315D,
  24433. wgrave: 0x1E81,
  24434. whitebullet: 0x25E6,
  24435. whitecircle: 0x25CB,
  24436. whitecircleinverse: 0x25D9,
  24437. whitecornerbracketleft: 0x300E,
  24438. whitecornerbracketleftvertical: 0xFE43,
  24439. whitecornerbracketright: 0x300F,
  24440. whitecornerbracketrightvertical: 0xFE44,
  24441. whitediamond: 0x25C7,
  24442. whitediamondcontainingblacksmalldiamond: 0x25C8,
  24443. whitedownpointingsmalltriangle: 0x25BF,
  24444. whitedownpointingtriangle: 0x25BD,
  24445. whiteleftpointingsmalltriangle: 0x25C3,
  24446. whiteleftpointingtriangle: 0x25C1,
  24447. whitelenticularbracketleft: 0x3016,
  24448. whitelenticularbracketright: 0x3017,
  24449. whiterightpointingsmalltriangle: 0x25B9,
  24450. whiterightpointingtriangle: 0x25B7,
  24451. whitesmallsquare: 0x25AB,
  24452. whitesmilingface: 0x263A,
  24453. whitesquare: 0x25A1,
  24454. whitestar: 0x2606,
  24455. whitetelephone: 0x260F,
  24456. whitetortoiseshellbracketleft: 0x3018,
  24457. whitetortoiseshellbracketright: 0x3019,
  24458. whiteuppointingsmalltriangle: 0x25B5,
  24459. whiteuppointingtriangle: 0x25B3,
  24460. wihiragana: 0x3090,
  24461. wikatakana: 0x30F0,
  24462. wikorean: 0x315F,
  24463. wmonospace: 0xFF57,
  24464. wohiragana: 0x3092,
  24465. wokatakana: 0x30F2,
  24466. wokatakanahalfwidth: 0xFF66,
  24467. won: 0x20A9,
  24468. wonmonospace: 0xFFE6,
  24469. wowaenthai: 0x0E27,
  24470. wparen: 0x24B2,
  24471. wring: 0x1E98,
  24472. wsuperior: 0x02B7,
  24473. wturned: 0x028D,
  24474. wynn: 0x01BF,
  24475. x: 0x0078,
  24476. xabovecmb: 0x033D,
  24477. xbopomofo: 0x3112,
  24478. xcircle: 0x24E7,
  24479. xdieresis: 0x1E8D,
  24480. xdotaccent: 0x1E8B,
  24481. xeharmenian: 0x056D,
  24482. xi: 0x03BE,
  24483. xmonospace: 0xFF58,
  24484. xparen: 0x24B3,
  24485. xsuperior: 0x02E3,
  24486. y: 0x0079,
  24487. yaadosquare: 0x334E,
  24488. yabengali: 0x09AF,
  24489. yacute: 0x00FD,
  24490. yadeva: 0x092F,
  24491. yaekorean: 0x3152,
  24492. yagujarati: 0x0AAF,
  24493. yagurmukhi: 0x0A2F,
  24494. yahiragana: 0x3084,
  24495. yakatakana: 0x30E4,
  24496. yakatakanahalfwidth: 0xFF94,
  24497. yakorean: 0x3151,
  24498. yamakkanthai: 0x0E4E,
  24499. yasmallhiragana: 0x3083,
  24500. yasmallkatakana: 0x30E3,
  24501. yasmallkatakanahalfwidth: 0xFF6C,
  24502. yatcyrillic: 0x0463,
  24503. ycircle: 0x24E8,
  24504. ycircumflex: 0x0177,
  24505. ydieresis: 0x00FF,
  24506. ydotaccent: 0x1E8F,
  24507. ydotbelow: 0x1EF5,
  24508. yeharabic: 0x064A,
  24509. yehbarreearabic: 0x06D2,
  24510. yehbarreefinalarabic: 0xFBAF,
  24511. yehfinalarabic: 0xFEF2,
  24512. yehhamzaabovearabic: 0x0626,
  24513. yehhamzaabovefinalarabic: 0xFE8A,
  24514. yehhamzaaboveinitialarabic: 0xFE8B,
  24515. yehhamzaabovemedialarabic: 0xFE8C,
  24516. yehinitialarabic: 0xFEF3,
  24517. yehmedialarabic: 0xFEF4,
  24518. yehmeeminitialarabic: 0xFCDD,
  24519. yehmeemisolatedarabic: 0xFC58,
  24520. yehnoonfinalarabic: 0xFC94,
  24521. yehthreedotsbelowarabic: 0x06D1,
  24522. yekorean: 0x3156,
  24523. yen: 0x00A5,
  24524. yenmonospace: 0xFFE5,
  24525. yeokorean: 0x3155,
  24526. yeorinhieuhkorean: 0x3186,
  24527. yerahbenyomohebrew: 0x05AA,
  24528. yerahbenyomolefthebrew: 0x05AA,
  24529. yericyrillic: 0x044B,
  24530. yerudieresiscyrillic: 0x04F9,
  24531. yesieungkorean: 0x3181,
  24532. yesieungpansioskorean: 0x3183,
  24533. yesieungsioskorean: 0x3182,
  24534. yetivhebrew: 0x059A,
  24535. ygrave: 0x1EF3,
  24536. yhook: 0x01B4,
  24537. yhookabove: 0x1EF7,
  24538. yiarmenian: 0x0575,
  24539. yicyrillic: 0x0457,
  24540. yikorean: 0x3162,
  24541. yinyang: 0x262F,
  24542. yiwnarmenian: 0x0582,
  24543. ymonospace: 0xFF59,
  24544. yod: 0x05D9,
  24545. yoddagesh: 0xFB39,
  24546. yoddageshhebrew: 0xFB39,
  24547. yodhebrew: 0x05D9,
  24548. yodyodhebrew: 0x05F2,
  24549. yodyodpatahhebrew: 0xFB1F,
  24550. yohiragana: 0x3088,
  24551. yoikorean: 0x3189,
  24552. yokatakana: 0x30E8,
  24553. yokatakanahalfwidth: 0xFF96,
  24554. yokorean: 0x315B,
  24555. yosmallhiragana: 0x3087,
  24556. yosmallkatakana: 0x30E7,
  24557. yosmallkatakanahalfwidth: 0xFF6E,
  24558. yotgreek: 0x03F3,
  24559. yoyaekorean: 0x3188,
  24560. yoyakorean: 0x3187,
  24561. yoyakthai: 0x0E22,
  24562. yoyingthai: 0x0E0D,
  24563. yparen: 0x24B4,
  24564. ypogegrammeni: 0x037A,
  24565. ypogegrammenigreekcmb: 0x0345,
  24566. yr: 0x01A6,
  24567. yring: 0x1E99,
  24568. ysuperior: 0x02B8,
  24569. ytilde: 0x1EF9,
  24570. yturned: 0x028E,
  24571. yuhiragana: 0x3086,
  24572. yuikorean: 0x318C,
  24573. yukatakana: 0x30E6,
  24574. yukatakanahalfwidth: 0xFF95,
  24575. yukorean: 0x3160,
  24576. yusbigcyrillic: 0x046B,
  24577. yusbigiotifiedcyrillic: 0x046D,
  24578. yuslittlecyrillic: 0x0467,
  24579. yuslittleiotifiedcyrillic: 0x0469,
  24580. yusmallhiragana: 0x3085,
  24581. yusmallkatakana: 0x30E5,
  24582. yusmallkatakanahalfwidth: 0xFF6D,
  24583. yuyekorean: 0x318B,
  24584. yuyeokorean: 0x318A,
  24585. yyabengali: 0x09DF,
  24586. yyadeva: 0x095F,
  24587. z: 0x007A,
  24588. zaarmenian: 0x0566,
  24589. zacute: 0x017A,
  24590. zadeva: 0x095B,
  24591. zagurmukhi: 0x0A5B,
  24592. zaharabic: 0x0638,
  24593. zahfinalarabic: 0xFEC6,
  24594. zahinitialarabic: 0xFEC7,
  24595. zahiragana: 0x3056,
  24596. zahmedialarabic: 0xFEC8,
  24597. zainarabic: 0x0632,
  24598. zainfinalarabic: 0xFEB0,
  24599. zakatakana: 0x30B6,
  24600. zaqefgadolhebrew: 0x0595,
  24601. zaqefqatanhebrew: 0x0594,
  24602. zarqahebrew: 0x0598,
  24603. zayin: 0x05D6,
  24604. zayindagesh: 0xFB36,
  24605. zayindageshhebrew: 0xFB36,
  24606. zayinhebrew: 0x05D6,
  24607. zbopomofo: 0x3117,
  24608. zcaron: 0x017E,
  24609. zcircle: 0x24E9,
  24610. zcircumflex: 0x1E91,
  24611. zcurl: 0x0291,
  24612. zdot: 0x017C,
  24613. zdotaccent: 0x017C,
  24614. zdotbelow: 0x1E93,
  24615. zecyrillic: 0x0437,
  24616. zedescendercyrillic: 0x0499,
  24617. zedieresiscyrillic: 0x04DF,
  24618. zehiragana: 0x305C,
  24619. zekatakana: 0x30BC,
  24620. zero: 0x0030,
  24621. zeroarabic: 0x0660,
  24622. zerobengali: 0x09E6,
  24623. zerodeva: 0x0966,
  24624. zerogujarati: 0x0AE6,
  24625. zerogurmukhi: 0x0A66,
  24626. zerohackarabic: 0x0660,
  24627. zeroinferior: 0x2080,
  24628. zeromonospace: 0xFF10,
  24629. zerooldstyle: 0xF730,
  24630. zeropersian: 0x06F0,
  24631. zerosuperior: 0x2070,
  24632. zerothai: 0x0E50,
  24633. zerowidthjoiner: 0xFEFF,
  24634. zerowidthnonjoiner: 0x200C,
  24635. zerowidthspace: 0x200B,
  24636. zeta: 0x03B6,
  24637. zhbopomofo: 0x3113,
  24638. zhearmenian: 0x056A,
  24639. zhebrevecyrillic: 0x04C2,
  24640. zhecyrillic: 0x0436,
  24641. zhedescendercyrillic: 0x0497,
  24642. zhedieresiscyrillic: 0x04DD,
  24643. zihiragana: 0x3058,
  24644. zikatakana: 0x30B8,
  24645. zinorhebrew: 0x05AE,
  24646. zlinebelow: 0x1E95,
  24647. zmonospace: 0xFF5A,
  24648. zohiragana: 0x305E,
  24649. zokatakana: 0x30BE,
  24650. zparen: 0x24B5,
  24651. zretroflexhook: 0x0290,
  24652. zstroke: 0x01B6,
  24653. zuhiragana: 0x305A,
  24654. zukatakana: 0x30BA,
  24655. '.notdef': 0x0000
  24656. };
  24657. var DingbatsGlyphsUnicode = {
  24658. space: 0x0020,
  24659. a1: 0x2701,
  24660. a2: 0x2702,
  24661. a202: 0x2703,
  24662. a3: 0x2704,
  24663. a4: 0x260E,
  24664. a5: 0x2706,
  24665. a119: 0x2707,
  24666. a118: 0x2708,
  24667. a117: 0x2709,
  24668. a11: 0x261B,
  24669. a12: 0x261E,
  24670. a13: 0x270C,
  24671. a14: 0x270D,
  24672. a15: 0x270E,
  24673. a16: 0x270F,
  24674. a105: 0x2710,
  24675. a17: 0x2711,
  24676. a18: 0x2712,
  24677. a19: 0x2713,
  24678. a20: 0x2714,
  24679. a21: 0x2715,
  24680. a22: 0x2716,
  24681. a23: 0x2717,
  24682. a24: 0x2718,
  24683. a25: 0x2719,
  24684. a26: 0x271A,
  24685. a27: 0x271B,
  24686. a28: 0x271C,
  24687. a6: 0x271D,
  24688. a7: 0x271E,
  24689. a8: 0x271F,
  24690. a9: 0x2720,
  24691. a10: 0x2721,
  24692. a29: 0x2722,
  24693. a30: 0x2723,
  24694. a31: 0x2724,
  24695. a32: 0x2725,
  24696. a33: 0x2726,
  24697. a34: 0x2727,
  24698. a35: 0x2605,
  24699. a36: 0x2729,
  24700. a37: 0x272A,
  24701. a38: 0x272B,
  24702. a39: 0x272C,
  24703. a40: 0x272D,
  24704. a41: 0x272E,
  24705. a42: 0x272F,
  24706. a43: 0x2730,
  24707. a44: 0x2731,
  24708. a45: 0x2732,
  24709. a46: 0x2733,
  24710. a47: 0x2734,
  24711. a48: 0x2735,
  24712. a49: 0x2736,
  24713. a50: 0x2737,
  24714. a51: 0x2738,
  24715. a52: 0x2739,
  24716. a53: 0x273A,
  24717. a54: 0x273B,
  24718. a55: 0x273C,
  24719. a56: 0x273D,
  24720. a57: 0x273E,
  24721. a58: 0x273F,
  24722. a59: 0x2740,
  24723. a60: 0x2741,
  24724. a61: 0x2742,
  24725. a62: 0x2743,
  24726. a63: 0x2744,
  24727. a64: 0x2745,
  24728. a65: 0x2746,
  24729. a66: 0x2747,
  24730. a67: 0x2748,
  24731. a68: 0x2749,
  24732. a69: 0x274A,
  24733. a70: 0x274B,
  24734. a71: 0x25CF,
  24735. a72: 0x274D,
  24736. a73: 0x25A0,
  24737. a74: 0x274F,
  24738. a203: 0x2750,
  24739. a75: 0x2751,
  24740. a204: 0x2752,
  24741. a76: 0x25B2,
  24742. a77: 0x25BC,
  24743. a78: 0x25C6,
  24744. a79: 0x2756,
  24745. a81: 0x25D7,
  24746. a82: 0x2758,
  24747. a83: 0x2759,
  24748. a84: 0x275A,
  24749. a97: 0x275B,
  24750. a98: 0x275C,
  24751. a99: 0x275D,
  24752. a100: 0x275E,
  24753. a101: 0x2761,
  24754. a102: 0x2762,
  24755. a103: 0x2763,
  24756. a104: 0x2764,
  24757. a106: 0x2765,
  24758. a107: 0x2766,
  24759. a108: 0x2767,
  24760. a112: 0x2663,
  24761. a111: 0x2666,
  24762. a110: 0x2665,
  24763. a109: 0x2660,
  24764. a120: 0x2460,
  24765. a121: 0x2461,
  24766. a122: 0x2462,
  24767. a123: 0x2463,
  24768. a124: 0x2464,
  24769. a125: 0x2465,
  24770. a126: 0x2466,
  24771. a127: 0x2467,
  24772. a128: 0x2468,
  24773. a129: 0x2469,
  24774. a130: 0x2776,
  24775. a131: 0x2777,
  24776. a132: 0x2778,
  24777. a133: 0x2779,
  24778. a134: 0x277A,
  24779. a135: 0x277B,
  24780. a136: 0x277C,
  24781. a137: 0x277D,
  24782. a138: 0x277E,
  24783. a139: 0x277F,
  24784. a140: 0x2780,
  24785. a141: 0x2781,
  24786. a142: 0x2782,
  24787. a143: 0x2783,
  24788. a144: 0x2784,
  24789. a145: 0x2785,
  24790. a146: 0x2786,
  24791. a147: 0x2787,
  24792. a148: 0x2788,
  24793. a149: 0x2789,
  24794. a150: 0x278A,
  24795. a151: 0x278B,
  24796. a152: 0x278C,
  24797. a153: 0x278D,
  24798. a154: 0x278E,
  24799. a155: 0x278F,
  24800. a156: 0x2790,
  24801. a157: 0x2791,
  24802. a158: 0x2792,
  24803. a159: 0x2793,
  24804. a160: 0x2794,
  24805. a161: 0x2192,
  24806. a163: 0x2194,
  24807. a164: 0x2195,
  24808. a196: 0x2798,
  24809. a165: 0x2799,
  24810. a192: 0x279A,
  24811. a166: 0x279B,
  24812. a167: 0x279C,
  24813. a168: 0x279D,
  24814. a169: 0x279E,
  24815. a170: 0x279F,
  24816. a171: 0x27A0,
  24817. a172: 0x27A1,
  24818. a173: 0x27A2,
  24819. a162: 0x27A3,
  24820. a174: 0x27A4,
  24821. a175: 0x27A5,
  24822. a176: 0x27A6,
  24823. a177: 0x27A7,
  24824. a178: 0x27A8,
  24825. a179: 0x27A9,
  24826. a193: 0x27AA,
  24827. a180: 0x27AB,
  24828. a199: 0x27AC,
  24829. a181: 0x27AD,
  24830. a200: 0x27AE,
  24831. a182: 0x27AF,
  24832. a201: 0x27B1,
  24833. a183: 0x27B2,
  24834. a184: 0x27B3,
  24835. a197: 0x27B4,
  24836. a185: 0x27B5,
  24837. a194: 0x27B6,
  24838. a198: 0x27B7,
  24839. a186: 0x27B8,
  24840. a195: 0x27B9,
  24841. a187: 0x27BA,
  24842. a188: 0x27BB,
  24843. a189: 0x27BC,
  24844. a190: 0x27BD,
  24845. a191: 0x27BE,
  24846. a89: 0x2768, // 0xF8D7
  24847. a90: 0x2769, // 0xF8D8
  24848. a93: 0x276A, // 0xF8D9
  24849. a94: 0x276B, // 0xF8DA
  24850. a91: 0x276C, // 0xF8DB
  24851. a92: 0x276D, // 0xF8DC
  24852. a205: 0x276E, // 0xF8DD
  24853. a85: 0x276F, // 0xF8DE
  24854. a206: 0x2770, // 0xF8DF
  24855. a86: 0x2771, // 0xF8E0
  24856. a87: 0x2772, // 0xF8E1
  24857. a88: 0x2773, // 0xF8E2
  24858. a95: 0x2774, // 0xF8E3
  24859. a96: 0x2775, // 0xF8E4
  24860. '.notdef': 0x0000
  24861. };
  24862. var PDFImage = (function PDFImageClosure() {
  24863. /**
  24864. * Decode the image in the main thread if it supported. Resovles the promise
  24865. * when the image data is ready.
  24866. */
  24867. function handleImageData(handler, xref, res, image) {
  24868. if (image instanceof JpegStream && image.isNativelyDecodable(xref, res)) {
  24869. // For natively supported jpegs send them to the main thread for decoding.
  24870. var dict = image.dict;
  24871. var colorSpace = dict.get('ColorSpace', 'CS');
  24872. colorSpace = ColorSpace.parse(colorSpace, xref, res);
  24873. var numComps = colorSpace.numComps;
  24874. var decodePromise = handler.sendWithPromise('JpegDecode',
  24875. [image.getIR(), numComps]);
  24876. return decodePromise.then(function (message) {
  24877. var data = message.data;
  24878. return new Stream(data, 0, data.length, image.dict);
  24879. });
  24880. } else {
  24881. return Promise.resolve(image);
  24882. }
  24883. }
  24884. /**
  24885. * Decode and clamp a value. The formula is different from the spec because we
  24886. * don't decode to float range [0,1], we decode it in the [0,max] range.
  24887. */
  24888. function decodeAndClamp(value, addend, coefficient, max) {
  24889. value = addend + value * coefficient;
  24890. // Clamp the value to the range
  24891. return (value < 0 ? 0 : (value > max ? max : value));
  24892. }
  24893. function PDFImage(xref, res, image, inline, smask, mask, isMask) {
  24894. this.image = image;
  24895. var dict = image.dict;
  24896. if (dict.has('Filter')) {
  24897. var filter = dict.get('Filter').name;
  24898. if (filter === 'JPXDecode') {
  24899. var jpxImage = new JpxImage();
  24900. jpxImage.parseImageProperties(image.stream);
  24901. image.stream.reset();
  24902. image.bitsPerComponent = jpxImage.bitsPerComponent;
  24903. image.numComps = jpxImage.componentsCount;
  24904. } else if (filter === 'JBIG2Decode') {
  24905. image.bitsPerComponent = 1;
  24906. image.numComps = 1;
  24907. }
  24908. }
  24909. // TODO cache rendered images?
  24910. this.width = dict.get('Width', 'W');
  24911. this.height = dict.get('Height', 'H');
  24912. if (this.width < 1 || this.height < 1) {
  24913. error('Invalid image width: ' + this.width + ' or height: ' +
  24914. this.height);
  24915. }
  24916. this.interpolate = dict.get('Interpolate', 'I') || false;
  24917. this.imageMask = dict.get('ImageMask', 'IM') || false;
  24918. this.matte = dict.get('Matte') || false;
  24919. var bitsPerComponent = image.bitsPerComponent;
  24920. if (!bitsPerComponent) {
  24921. bitsPerComponent = dict.get('BitsPerComponent', 'BPC');
  24922. if (!bitsPerComponent) {
  24923. if (this.imageMask) {
  24924. bitsPerComponent = 1;
  24925. } else {
  24926. error('Bits per component missing in image: ' + this.imageMask);
  24927. }
  24928. }
  24929. }
  24930. this.bpc = bitsPerComponent;
  24931. if (!this.imageMask) {
  24932. var colorSpace = dict.get('ColorSpace', 'CS');
  24933. if (!colorSpace) {
  24934. info('JPX images (which do not require color spaces)');
  24935. switch (image.numComps) {
  24936. case 1:
  24937. colorSpace = Name.get('DeviceGray');
  24938. break;
  24939. case 3:
  24940. colorSpace = Name.get('DeviceRGB');
  24941. break;
  24942. case 4:
  24943. colorSpace = Name.get('DeviceCMYK');
  24944. break;
  24945. default:
  24946. error('JPX images with ' + this.numComps +
  24947. ' color components not supported.');
  24948. }
  24949. }
  24950. this.colorSpace = ColorSpace.parse(colorSpace, xref, res);
  24951. this.numComps = this.colorSpace.numComps;
  24952. }
  24953. this.decode = dict.get('Decode', 'D');
  24954. this.needsDecode = false;
  24955. if (this.decode &&
  24956. ((this.colorSpace && !this.colorSpace.isDefaultDecode(this.decode)) ||
  24957. (isMask && !ColorSpace.isDefaultDecode(this.decode, 1)))) {
  24958. this.needsDecode = true;
  24959. // Do some preprocessing to avoid more math.
  24960. var max = (1 << bitsPerComponent) - 1;
  24961. this.decodeCoefficients = [];
  24962. this.decodeAddends = [];
  24963. for (var i = 0, j = 0; i < this.decode.length; i += 2, ++j) {
  24964. var dmin = this.decode[i];
  24965. var dmax = this.decode[i + 1];
  24966. this.decodeCoefficients[j] = dmax - dmin;
  24967. this.decodeAddends[j] = max * dmin;
  24968. }
  24969. }
  24970. if (smask) {
  24971. this.smask = new PDFImage(xref, res, smask, false);
  24972. } else if (mask) {
  24973. if (isStream(mask)) {
  24974. this.mask = new PDFImage(xref, res, mask, false, null, null, true);
  24975. } else {
  24976. // Color key mask (just an array).
  24977. this.mask = mask;
  24978. }
  24979. }
  24980. }
  24981. /**
  24982. * Handles processing of image data and returns the Promise that is resolved
  24983. * with a PDFImage when the image is ready to be used.
  24984. */
  24985. PDFImage.buildImage = function PDFImage_buildImage(handler, xref,
  24986. res, image, inline) {
  24987. var imagePromise = handleImageData(handler, xref, res, image);
  24988. var smaskPromise;
  24989. var maskPromise;
  24990. var smask = image.dict.get('SMask');
  24991. var mask = image.dict.get('Mask');
  24992. if (smask) {
  24993. smaskPromise = handleImageData(handler, xref, res, smask);
  24994. maskPromise = Promise.resolve(null);
  24995. } else {
  24996. smaskPromise = Promise.resolve(null);
  24997. if (mask) {
  24998. if (isStream(mask)) {
  24999. maskPromise = handleImageData(handler, xref, res, mask);
  25000. } else if (isArray(mask)) {
  25001. maskPromise = Promise.resolve(mask);
  25002. } else {
  25003. warn('Unsupported mask format.');
  25004. maskPromise = Promise.resolve(null);
  25005. }
  25006. } else {
  25007. maskPromise = Promise.resolve(null);
  25008. }
  25009. }
  25010. return Promise.all([imagePromise, smaskPromise, maskPromise]).then(
  25011. function(results) {
  25012. var imageData = results[0];
  25013. var smaskData = results[1];
  25014. var maskData = results[2];
  25015. return new PDFImage(xref, res, imageData, inline, smaskData, maskData);
  25016. });
  25017. };
  25018. /**
  25019. * Resize an image using the nearest neighbor algorithm. Currently only
  25020. * supports one and three component images.
  25021. * @param {TypedArray} pixels The original image with one component.
  25022. * @param {Number} bpc Number of bits per component.
  25023. * @param {Number} components Number of color components, 1 or 3 is supported.
  25024. * @param {Number} w1 Original width.
  25025. * @param {Number} h1 Original height.
  25026. * @param {Number} w2 New width.
  25027. * @param {Number} h2 New height.
  25028. * @param {TypedArray} dest (Optional) The destination buffer.
  25029. * @param {Number} alpha01 (Optional) Size reserved for the alpha channel.
  25030. * @return {TypedArray} Resized image data.
  25031. */
  25032. PDFImage.resize = function PDFImage_resize(pixels, bpc, components,
  25033. w1, h1, w2, h2, dest, alpha01) {
  25034. if (components !== 1 && components !== 3) {
  25035. error('Unsupported component count for resizing.');
  25036. }
  25037. var length = w2 * h2 * components;
  25038. var temp = dest ? dest : (bpc <= 8 ? new Uint8Array(length) :
  25039. (bpc <= 16 ? new Uint16Array(length) : new Uint32Array(length)));
  25040. var xRatio = w1 / w2;
  25041. var yRatio = h1 / h2;
  25042. var i, j, py, newIndex = 0, oldIndex;
  25043. var xScaled = new Uint16Array(w2);
  25044. var w1Scanline = w1 * components;
  25045. if (alpha01 !== 1) {
  25046. alpha01 = 0;
  25047. }
  25048. for (j = 0; j < w2; j++) {
  25049. xScaled[j] = Math.floor(j * xRatio) * components;
  25050. }
  25051. if (components === 1) {
  25052. for (i = 0; i < h2; i++) {
  25053. py = Math.floor(i * yRatio) * w1Scanline;
  25054. for (j = 0; j < w2; j++) {
  25055. oldIndex = py + xScaled[j];
  25056. temp[newIndex++] = pixels[oldIndex];
  25057. }
  25058. }
  25059. } else if (components === 3) {
  25060. for (i = 0; i < h2; i++) {
  25061. py = Math.floor(i * yRatio) * w1Scanline;
  25062. for (j = 0; j < w2; j++) {
  25063. oldIndex = py + xScaled[j];
  25064. temp[newIndex++] = pixels[oldIndex++];
  25065. temp[newIndex++] = pixels[oldIndex++];
  25066. temp[newIndex++] = pixels[oldIndex++];
  25067. newIndex += alpha01;
  25068. }
  25069. }
  25070. }
  25071. return temp;
  25072. };
  25073. PDFImage.createMask =
  25074. function PDFImage_createMask(imgArray, width, height,
  25075. imageIsFromDecodeStream, inverseDecode) {
  25076. // |imgArray| might not contain full data for every pixel of the mask, so
  25077. // we need to distinguish between |computedLength| and |actualLength|.
  25078. // In particular, if inverseDecode is true, then the array we return must
  25079. // have a length of |computedLength|.
  25080. var computedLength = ((width + 7) >> 3) * height;
  25081. var actualLength = imgArray.byteLength;
  25082. var haveFullData = computedLength === actualLength;
  25083. var data, i;
  25084. if (imageIsFromDecodeStream && (!inverseDecode || haveFullData)) {
  25085. // imgArray came from a DecodeStream and its data is in an appropriate
  25086. // form, so we can just transfer it.
  25087. data = imgArray;
  25088. } else if (!inverseDecode) {
  25089. data = new Uint8Array(actualLength);
  25090. data.set(imgArray);
  25091. } else {
  25092. data = new Uint8Array(computedLength);
  25093. data.set(imgArray);
  25094. for (i = actualLength; i < computedLength; i++) {
  25095. data[i] = 0xff;
  25096. }
  25097. }
  25098. // If necessary, invert the original mask data (but not any extra we might
  25099. // have added above). It's safe to modify the array -- whether it's the
  25100. // original or a copy, we're about to transfer it anyway, so nothing else
  25101. // in this thread can be relying on its contents.
  25102. if (inverseDecode) {
  25103. for (i = 0; i < actualLength; i++) {
  25104. data[i] = ~data[i];
  25105. }
  25106. }
  25107. return {data: data, width: width, height: height};
  25108. };
  25109. PDFImage.prototype = {
  25110. get drawWidth() {
  25111. return Math.max(this.width,
  25112. this.smask && this.smask.width || 0,
  25113. this.mask && this.mask.width || 0);
  25114. },
  25115. get drawHeight() {
  25116. return Math.max(this.height,
  25117. this.smask && this.smask.height || 0,
  25118. this.mask && this.mask.height || 0);
  25119. },
  25120. decodeBuffer: function PDFImage_decodeBuffer(buffer) {
  25121. var bpc = this.bpc;
  25122. var numComps = this.numComps;
  25123. var decodeAddends = this.decodeAddends;
  25124. var decodeCoefficients = this.decodeCoefficients;
  25125. var max = (1 << bpc) - 1;
  25126. var i, ii;
  25127. if (bpc === 1) {
  25128. // If the buffer needed decode that means it just needs to be inverted.
  25129. for (i = 0, ii = buffer.length; i < ii; i++) {
  25130. buffer[i] = +!(buffer[i]);
  25131. }
  25132. return;
  25133. }
  25134. var index = 0;
  25135. for (i = 0, ii = this.width * this.height; i < ii; i++) {
  25136. for (var j = 0; j < numComps; j++) {
  25137. buffer[index] = decodeAndClamp(buffer[index], decodeAddends[j],
  25138. decodeCoefficients[j], max);
  25139. index++;
  25140. }
  25141. }
  25142. },
  25143. getComponents: function PDFImage_getComponents(buffer) {
  25144. var bpc = this.bpc;
  25145. // This image doesn't require any extra work.
  25146. if (bpc === 8) {
  25147. return buffer;
  25148. }
  25149. var width = this.width;
  25150. var height = this.height;
  25151. var numComps = this.numComps;
  25152. var length = width * height * numComps;
  25153. var bufferPos = 0;
  25154. var output = (bpc <= 8 ? new Uint8Array(length) :
  25155. (bpc <= 16 ? new Uint16Array(length) : new Uint32Array(length)));
  25156. var rowComps = width * numComps;
  25157. var max = (1 << bpc) - 1;
  25158. var i = 0, ii, buf;
  25159. if (bpc === 1) {
  25160. // Optimization for reading 1 bpc images.
  25161. var mask, loop1End, loop2End;
  25162. for (var j = 0; j < height; j++) {
  25163. loop1End = i + (rowComps & ~7);
  25164. loop2End = i + rowComps;
  25165. // unroll loop for all full bytes
  25166. while (i < loop1End) {
  25167. buf = buffer[bufferPos++];
  25168. output[i] = (buf >> 7) & 1;
  25169. output[i + 1] = (buf >> 6) & 1;
  25170. output[i + 2] = (buf >> 5) & 1;
  25171. output[i + 3] = (buf >> 4) & 1;
  25172. output[i + 4] = (buf >> 3) & 1;
  25173. output[i + 5] = (buf >> 2) & 1;
  25174. output[i + 6] = (buf >> 1) & 1;
  25175. output[i + 7] = buf & 1;
  25176. i += 8;
  25177. }
  25178. // handle remaing bits
  25179. if (i < loop2End) {
  25180. buf = buffer[bufferPos++];
  25181. mask = 128;
  25182. while (i < loop2End) {
  25183. output[i++] = +!!(buf & mask);
  25184. mask >>= 1;
  25185. }
  25186. }
  25187. }
  25188. } else {
  25189. // The general case that handles all other bpc values.
  25190. var bits = 0;
  25191. buf = 0;
  25192. for (i = 0, ii = length; i < ii; ++i) {
  25193. if (i % rowComps === 0) {
  25194. buf = 0;
  25195. bits = 0;
  25196. }
  25197. while (bits < bpc) {
  25198. buf = (buf << 8) | buffer[bufferPos++];
  25199. bits += 8;
  25200. }
  25201. var remainingBits = bits - bpc;
  25202. var value = buf >> remainingBits;
  25203. output[i] = (value < 0 ? 0 : (value > max ? max : value));
  25204. buf = buf & ((1 << remainingBits) - 1);
  25205. bits = remainingBits;
  25206. }
  25207. }
  25208. return output;
  25209. },
  25210. fillOpacity: function PDFImage_fillOpacity(rgbaBuf, width, height,
  25211. actualHeight, image) {
  25212. var smask = this.smask;
  25213. var mask = this.mask;
  25214. var alphaBuf, sw, sh, i, ii, j;
  25215. if (smask) {
  25216. sw = smask.width;
  25217. sh = smask.height;
  25218. alphaBuf = new Uint8Array(sw * sh);
  25219. smask.fillGrayBuffer(alphaBuf);
  25220. if (sw !== width || sh !== height) {
  25221. alphaBuf = PDFImage.resize(alphaBuf, smask.bpc, 1, sw, sh, width,
  25222. height);
  25223. }
  25224. } else if (mask) {
  25225. if (mask instanceof PDFImage) {
  25226. sw = mask.width;
  25227. sh = mask.height;
  25228. alphaBuf = new Uint8Array(sw * sh);
  25229. mask.numComps = 1;
  25230. mask.fillGrayBuffer(alphaBuf);
  25231. // Need to invert values in rgbaBuf
  25232. for (i = 0, ii = sw * sh; i < ii; ++i) {
  25233. alphaBuf[i] = 255 - alphaBuf[i];
  25234. }
  25235. if (sw !== width || sh !== height) {
  25236. alphaBuf = PDFImage.resize(alphaBuf, mask.bpc, 1, sw, sh, width,
  25237. height);
  25238. }
  25239. } else if (isArray(mask)) {
  25240. // Color key mask: if any of the compontents are outside the range
  25241. // then they should be painted.
  25242. alphaBuf = new Uint8Array(width * height);
  25243. var numComps = this.numComps;
  25244. for (i = 0, ii = width * height; i < ii; ++i) {
  25245. var opacity = 0;
  25246. var imageOffset = i * numComps;
  25247. for (j = 0; j < numComps; ++j) {
  25248. var color = image[imageOffset + j];
  25249. var maskOffset = j * 2;
  25250. if (color < mask[maskOffset] || color > mask[maskOffset + 1]) {
  25251. opacity = 255;
  25252. break;
  25253. }
  25254. }
  25255. alphaBuf[i] = opacity;
  25256. }
  25257. } else {
  25258. error('Unknown mask format.');
  25259. }
  25260. }
  25261. if (alphaBuf) {
  25262. for (i = 0, j = 3, ii = width * actualHeight; i < ii; ++i, j += 4) {
  25263. rgbaBuf[j] = alphaBuf[i];
  25264. }
  25265. } else {
  25266. // No mask.
  25267. for (i = 0, j = 3, ii = width * actualHeight; i < ii; ++i, j += 4) {
  25268. rgbaBuf[j] = 255;
  25269. }
  25270. }
  25271. },
  25272. undoPreblend: function PDFImage_undoPreblend(buffer, width, height) {
  25273. var matte = this.smask && this.smask.matte;
  25274. if (!matte) {
  25275. return;
  25276. }
  25277. var matteRgb = this.colorSpace.getRgb(matte, 0);
  25278. var matteR = matteRgb[0];
  25279. var matteG = matteRgb[1];
  25280. var matteB = matteRgb[2];
  25281. var length = width * height * 4;
  25282. var r, g, b;
  25283. for (var i = 0; i < length; i += 4) {
  25284. var alpha = buffer[i + 3];
  25285. if (alpha === 0) {
  25286. // according formula we have to get Infinity in all components
  25287. // making it white (typical paper color) should be okay
  25288. buffer[i] = 255;
  25289. buffer[i + 1] = 255;
  25290. buffer[i + 2] = 255;
  25291. continue;
  25292. }
  25293. var k = 255 / alpha;
  25294. r = (buffer[i] - matteR) * k + matteR;
  25295. g = (buffer[i + 1] - matteG) * k + matteG;
  25296. b = (buffer[i + 2] - matteB) * k + matteB;
  25297. buffer[i] = r <= 0 ? 0 : r >= 255 ? 255 : r | 0;
  25298. buffer[i + 1] = g <= 0 ? 0 : g >= 255 ? 255 : g | 0;
  25299. buffer[i + 2] = b <= 0 ? 0 : b >= 255 ? 255 : b | 0;
  25300. }
  25301. },
  25302. createImageData: function PDFImage_createImageData(forceRGBA) {
  25303. var drawWidth = this.drawWidth;
  25304. var drawHeight = this.drawHeight;
  25305. var imgData = { // other fields are filled in below
  25306. width: drawWidth,
  25307. height: drawHeight
  25308. };
  25309. var numComps = this.numComps;
  25310. var originalWidth = this.width;
  25311. var originalHeight = this.height;
  25312. var bpc = this.bpc;
  25313. // Rows start at byte boundary.
  25314. var rowBytes = (originalWidth * numComps * bpc + 7) >> 3;
  25315. var imgArray;
  25316. if (!forceRGBA) {
  25317. // If it is a 1-bit-per-pixel grayscale (i.e. black-and-white) image
  25318. // without any complications, we pass a same-sized copy to the main
  25319. // thread rather than expanding by 32x to RGBA form. This saves *lots*
  25320. // of memory for many scanned documents. It's also much faster.
  25321. //
  25322. // Similarly, if it is a 24-bit-per pixel RGB image without any
  25323. // complications, we avoid expanding by 1.333x to RGBA form.
  25324. var kind;
  25325. if (this.colorSpace.name === 'DeviceGray' && bpc === 1) {
  25326. kind = ImageKind.GRAYSCALE_1BPP;
  25327. } else if (this.colorSpace.name === 'DeviceRGB' && bpc === 8 &&
  25328. !this.needsDecode) {
  25329. kind = ImageKind.RGB_24BPP;
  25330. }
  25331. if (kind && !this.smask && !this.mask &&
  25332. drawWidth === originalWidth && drawHeight === originalHeight) {
  25333. imgData.kind = kind;
  25334. imgArray = this.getImageBytes(originalHeight * rowBytes);
  25335. // If imgArray came from a DecodeStream, we're safe to transfer it
  25336. // (and thus neuter it) because it will constitute the entire
  25337. // DecodeStream's data. But if it came from a Stream, we need to
  25338. // copy it because it'll only be a portion of the Stream's data, and
  25339. // the rest will be read later on.
  25340. if (this.image instanceof DecodeStream) {
  25341. imgData.data = imgArray;
  25342. } else {
  25343. var newArray = new Uint8Array(imgArray.length);
  25344. newArray.set(imgArray);
  25345. imgData.data = newArray;
  25346. }
  25347. if (this.needsDecode) {
  25348. // Invert the buffer (which must be grayscale if we reached here).
  25349. assert(kind === ImageKind.GRAYSCALE_1BPP);
  25350. var buffer = imgData.data;
  25351. for (var i = 0, ii = buffer.length; i < ii; i++) {
  25352. buffer[i] ^= 0xff;
  25353. }
  25354. }
  25355. return imgData;
  25356. }
  25357. if (this.image instanceof JpegStream && !this.smask && !this.mask) {
  25358. imgData.kind = ImageKind.RGB_24BPP;
  25359. imgData.data = this.getImageBytes(originalHeight * rowBytes,
  25360. drawWidth, drawHeight, true);
  25361. return imgData;
  25362. }
  25363. }
  25364. imgArray = this.getImageBytes(originalHeight * rowBytes);
  25365. // imgArray can be incomplete (e.g. after CCITT fax encoding).
  25366. var actualHeight = 0 | (imgArray.length / rowBytes *
  25367. drawHeight / originalHeight);
  25368. var comps = this.getComponents(imgArray);
  25369. // If opacity data is present, use RGBA_32BPP form. Otherwise, use the
  25370. // more compact RGB_24BPP form if allowable.
  25371. var alpha01, maybeUndoPreblend;
  25372. if (!forceRGBA && !this.smask && !this.mask) {
  25373. imgData.kind = ImageKind.RGB_24BPP;
  25374. imgData.data = new Uint8Array(drawWidth * drawHeight * 3);
  25375. alpha01 = 0;
  25376. maybeUndoPreblend = false;
  25377. } else {
  25378. imgData.kind = ImageKind.RGBA_32BPP;
  25379. imgData.data = new Uint8Array(drawWidth * drawHeight * 4);
  25380. alpha01 = 1;
  25381. maybeUndoPreblend = true;
  25382. // Color key masking (opacity) must be performed before decoding.
  25383. this.fillOpacity(imgData.data, drawWidth, drawHeight, actualHeight,
  25384. comps);
  25385. }
  25386. if (this.needsDecode) {
  25387. this.decodeBuffer(comps);
  25388. }
  25389. this.colorSpace.fillRgb(imgData.data, originalWidth, originalHeight,
  25390. drawWidth, drawHeight, actualHeight, bpc, comps,
  25391. alpha01);
  25392. if (maybeUndoPreblend) {
  25393. this.undoPreblend(imgData.data, drawWidth, actualHeight);
  25394. }
  25395. return imgData;
  25396. },
  25397. fillGrayBuffer: function PDFImage_fillGrayBuffer(buffer) {
  25398. var numComps = this.numComps;
  25399. if (numComps !== 1) {
  25400. error('Reading gray scale from a color image: ' + numComps);
  25401. }
  25402. var width = this.width;
  25403. var height = this.height;
  25404. var bpc = this.bpc;
  25405. // rows start at byte boundary
  25406. var rowBytes = (width * numComps * bpc + 7) >> 3;
  25407. var imgArray = this.getImageBytes(height * rowBytes);
  25408. var comps = this.getComponents(imgArray);
  25409. var i, length;
  25410. if (bpc === 1) {
  25411. // inline decoding (= inversion) for 1 bpc images
  25412. length = width * height;
  25413. if (this.needsDecode) {
  25414. // invert and scale to {0, 255}
  25415. for (i = 0; i < length; ++i) {
  25416. buffer[i] = (comps[i] - 1) & 255;
  25417. }
  25418. } else {
  25419. // scale to {0, 255}
  25420. for (i = 0; i < length; ++i) {
  25421. buffer[i] = (-comps[i]) & 255;
  25422. }
  25423. }
  25424. return;
  25425. }
  25426. if (this.needsDecode) {
  25427. this.decodeBuffer(comps);
  25428. }
  25429. length = width * height;
  25430. // we aren't using a colorspace so we need to scale the value
  25431. var scale = 255 / ((1 << bpc) - 1);
  25432. for (i = 0; i < length; ++i) {
  25433. buffer[i] = (scale * comps[i]) | 0;
  25434. }
  25435. },
  25436. getImageBytes: function PDFImage_getImageBytes(length,
  25437. drawWidth, drawHeight,
  25438. forceRGB) {
  25439. this.image.reset();
  25440. this.image.drawWidth = drawWidth || this.width;
  25441. this.image.drawHeight = drawHeight || this.height;
  25442. this.image.forceRGB = !!forceRGB;
  25443. return this.image.getBytes(length);
  25444. }
  25445. };
  25446. return PDFImage;
  25447. })();
  25448. // The Metrics object contains glyph widths (in glyph space units).
  25449. // As per PDF spec, for most fonts (Type 3 being an exception) a glyph
  25450. // space unit corresponds to 1/1000th of text space unit.
  25451. var Metrics = {
  25452. 'Courier': 600,
  25453. 'Courier-Bold': 600,
  25454. 'Courier-BoldOblique': 600,
  25455. 'Courier-Oblique': 600,
  25456. 'Helvetica' : {
  25457. 'space': 278,
  25458. 'exclam': 278,
  25459. 'quotedbl': 355,
  25460. 'numbersign': 556,
  25461. 'dollar': 556,
  25462. 'percent': 889,
  25463. 'ampersand': 667,
  25464. 'quoteright': 222,
  25465. 'parenleft': 333,
  25466. 'parenright': 333,
  25467. 'asterisk': 389,
  25468. 'plus': 584,
  25469. 'comma': 278,
  25470. 'hyphen': 333,
  25471. 'period': 278,
  25472. 'slash': 278,
  25473. 'zero': 556,
  25474. 'one': 556,
  25475. 'two': 556,
  25476. 'three': 556,
  25477. 'four': 556,
  25478. 'five': 556,
  25479. 'six': 556,
  25480. 'seven': 556,
  25481. 'eight': 556,
  25482. 'nine': 556,
  25483. 'colon': 278,
  25484. 'semicolon': 278,
  25485. 'less': 584,
  25486. 'equal': 584,
  25487. 'greater': 584,
  25488. 'question': 556,
  25489. 'at': 1015,
  25490. 'A': 667,
  25491. 'B': 667,
  25492. 'C': 722,
  25493. 'D': 722,
  25494. 'E': 667,
  25495. 'F': 611,
  25496. 'G': 778,
  25497. 'H': 722,
  25498. 'I': 278,
  25499. 'J': 500,
  25500. 'K': 667,
  25501. 'L': 556,
  25502. 'M': 833,
  25503. 'N': 722,
  25504. 'O': 778,
  25505. 'P': 667,
  25506. 'Q': 778,
  25507. 'R': 722,
  25508. 'S': 667,
  25509. 'T': 611,
  25510. 'U': 722,
  25511. 'V': 667,
  25512. 'W': 944,
  25513. 'X': 667,
  25514. 'Y': 667,
  25515. 'Z': 611,
  25516. 'bracketleft': 278,
  25517. 'backslash': 278,
  25518. 'bracketright': 278,
  25519. 'asciicircum': 469,
  25520. 'underscore': 556,
  25521. 'quoteleft': 222,
  25522. 'a': 556,
  25523. 'b': 556,
  25524. 'c': 500,
  25525. 'd': 556,
  25526. 'e': 556,
  25527. 'f': 278,
  25528. 'g': 556,
  25529. 'h': 556,
  25530. 'i': 222,
  25531. 'j': 222,
  25532. 'k': 500,
  25533. 'l': 222,
  25534. 'm': 833,
  25535. 'n': 556,
  25536. 'o': 556,
  25537. 'p': 556,
  25538. 'q': 556,
  25539. 'r': 333,
  25540. 's': 500,
  25541. 't': 278,
  25542. 'u': 556,
  25543. 'v': 500,
  25544. 'w': 722,
  25545. 'x': 500,
  25546. 'y': 500,
  25547. 'z': 500,
  25548. 'braceleft': 334,
  25549. 'bar': 260,
  25550. 'braceright': 334,
  25551. 'asciitilde': 584,
  25552. 'exclamdown': 333,
  25553. 'cent': 556,
  25554. 'sterling': 556,
  25555. 'fraction': 167,
  25556. 'yen': 556,
  25557. 'florin': 556,
  25558. 'section': 556,
  25559. 'currency': 556,
  25560. 'quotesingle': 191,
  25561. 'quotedblleft': 333,
  25562. 'guillemotleft': 556,
  25563. 'guilsinglleft': 333,
  25564. 'guilsinglright': 333,
  25565. 'fi': 500,
  25566. 'fl': 500,
  25567. 'endash': 556,
  25568. 'dagger': 556,
  25569. 'daggerdbl': 556,
  25570. 'periodcentered': 278,
  25571. 'paragraph': 537,
  25572. 'bullet': 350,
  25573. 'quotesinglbase': 222,
  25574. 'quotedblbase': 333,
  25575. 'quotedblright': 333,
  25576. 'guillemotright': 556,
  25577. 'ellipsis': 1000,
  25578. 'perthousand': 1000,
  25579. 'questiondown': 611,
  25580. 'grave': 333,
  25581. 'acute': 333,
  25582. 'circumflex': 333,
  25583. 'tilde': 333,
  25584. 'macron': 333,
  25585. 'breve': 333,
  25586. 'dotaccent': 333,
  25587. 'dieresis': 333,
  25588. 'ring': 333,
  25589. 'cedilla': 333,
  25590. 'hungarumlaut': 333,
  25591. 'ogonek': 333,
  25592. 'caron': 333,
  25593. 'emdash': 1000,
  25594. 'AE': 1000,
  25595. 'ordfeminine': 370,
  25596. 'Lslash': 556,
  25597. 'Oslash': 778,
  25598. 'OE': 1000,
  25599. 'ordmasculine': 365,
  25600. 'ae': 889,
  25601. 'dotlessi': 278,
  25602. 'lslash': 222,
  25603. 'oslash': 611,
  25604. 'oe': 944,
  25605. 'germandbls': 611,
  25606. 'Idieresis': 278,
  25607. 'eacute': 556,
  25608. 'abreve': 556,
  25609. 'uhungarumlaut': 556,
  25610. 'ecaron': 556,
  25611. 'Ydieresis': 667,
  25612. 'divide': 584,
  25613. 'Yacute': 667,
  25614. 'Acircumflex': 667,
  25615. 'aacute': 556,
  25616. 'Ucircumflex': 722,
  25617. 'yacute': 500,
  25618. 'scommaaccent': 500,
  25619. 'ecircumflex': 556,
  25620. 'Uring': 722,
  25621. 'Udieresis': 722,
  25622. 'aogonek': 556,
  25623. 'Uacute': 722,
  25624. 'uogonek': 556,
  25625. 'Edieresis': 667,
  25626. 'Dcroat': 722,
  25627. 'commaaccent': 250,
  25628. 'copyright': 737,
  25629. 'Emacron': 667,
  25630. 'ccaron': 500,
  25631. 'aring': 556,
  25632. 'Ncommaaccent': 722,
  25633. 'lacute': 222,
  25634. 'agrave': 556,
  25635. 'Tcommaaccent': 611,
  25636. 'Cacute': 722,
  25637. 'atilde': 556,
  25638. 'Edotaccent': 667,
  25639. 'scaron': 500,
  25640. 'scedilla': 500,
  25641. 'iacute': 278,
  25642. 'lozenge': 471,
  25643. 'Rcaron': 722,
  25644. 'Gcommaaccent': 778,
  25645. 'ucircumflex': 556,
  25646. 'acircumflex': 556,
  25647. 'Amacron': 667,
  25648. 'rcaron': 333,
  25649. 'ccedilla': 500,
  25650. 'Zdotaccent': 611,
  25651. 'Thorn': 667,
  25652. 'Omacron': 778,
  25653. 'Racute': 722,
  25654. 'Sacute': 667,
  25655. 'dcaron': 643,
  25656. 'Umacron': 722,
  25657. 'uring': 556,
  25658. 'threesuperior': 333,
  25659. 'Ograve': 778,
  25660. 'Agrave': 667,
  25661. 'Abreve': 667,
  25662. 'multiply': 584,
  25663. 'uacute': 556,
  25664. 'Tcaron': 611,
  25665. 'partialdiff': 476,
  25666. 'ydieresis': 500,
  25667. 'Nacute': 722,
  25668. 'icircumflex': 278,
  25669. 'Ecircumflex': 667,
  25670. 'adieresis': 556,
  25671. 'edieresis': 556,
  25672. 'cacute': 500,
  25673. 'nacute': 556,
  25674. 'umacron': 556,
  25675. 'Ncaron': 722,
  25676. 'Iacute': 278,
  25677. 'plusminus': 584,
  25678. 'brokenbar': 260,
  25679. 'registered': 737,
  25680. 'Gbreve': 778,
  25681. 'Idotaccent': 278,
  25682. 'summation': 600,
  25683. 'Egrave': 667,
  25684. 'racute': 333,
  25685. 'omacron': 556,
  25686. 'Zacute': 611,
  25687. 'Zcaron': 611,
  25688. 'greaterequal': 549,
  25689. 'Eth': 722,
  25690. 'Ccedilla': 722,
  25691. 'lcommaaccent': 222,
  25692. 'tcaron': 317,
  25693. 'eogonek': 556,
  25694. 'Uogonek': 722,
  25695. 'Aacute': 667,
  25696. 'Adieresis': 667,
  25697. 'egrave': 556,
  25698. 'zacute': 500,
  25699. 'iogonek': 222,
  25700. 'Oacute': 778,
  25701. 'oacute': 556,
  25702. 'amacron': 556,
  25703. 'sacute': 500,
  25704. 'idieresis': 278,
  25705. 'Ocircumflex': 778,
  25706. 'Ugrave': 722,
  25707. 'Delta': 612,
  25708. 'thorn': 556,
  25709. 'twosuperior': 333,
  25710. 'Odieresis': 778,
  25711. 'mu': 556,
  25712. 'igrave': 278,
  25713. 'ohungarumlaut': 556,
  25714. 'Eogonek': 667,
  25715. 'dcroat': 556,
  25716. 'threequarters': 834,
  25717. 'Scedilla': 667,
  25718. 'lcaron': 299,
  25719. 'Kcommaaccent': 667,
  25720. 'Lacute': 556,
  25721. 'trademark': 1000,
  25722. 'edotaccent': 556,
  25723. 'Igrave': 278,
  25724. 'Imacron': 278,
  25725. 'Lcaron': 556,
  25726. 'onehalf': 834,
  25727. 'lessequal': 549,
  25728. 'ocircumflex': 556,
  25729. 'ntilde': 556,
  25730. 'Uhungarumlaut': 722,
  25731. 'Eacute': 667,
  25732. 'emacron': 556,
  25733. 'gbreve': 556,
  25734. 'onequarter': 834,
  25735. 'Scaron': 667,
  25736. 'Scommaaccent': 667,
  25737. 'Ohungarumlaut': 778,
  25738. 'degree': 400,
  25739. 'ograve': 556,
  25740. 'Ccaron': 722,
  25741. 'ugrave': 556,
  25742. 'radical': 453,
  25743. 'Dcaron': 722,
  25744. 'rcommaaccent': 333,
  25745. 'Ntilde': 722,
  25746. 'otilde': 556,
  25747. 'Rcommaaccent': 722,
  25748. 'Lcommaaccent': 556,
  25749. 'Atilde': 667,
  25750. 'Aogonek': 667,
  25751. 'Aring': 667,
  25752. 'Otilde': 778,
  25753. 'zdotaccent': 500,
  25754. 'Ecaron': 667,
  25755. 'Iogonek': 278,
  25756. 'kcommaaccent': 500,
  25757. 'minus': 584,
  25758. 'Icircumflex': 278,
  25759. 'ncaron': 556,
  25760. 'tcommaaccent': 278,
  25761. 'logicalnot': 584,
  25762. 'odieresis': 556,
  25763. 'udieresis': 556,
  25764. 'notequal': 549,
  25765. 'gcommaaccent': 556,
  25766. 'eth': 556,
  25767. 'zcaron': 500,
  25768. 'ncommaaccent': 556,
  25769. 'onesuperior': 333,
  25770. 'imacron': 278,
  25771. 'Euro': 556
  25772. },
  25773. 'Helvetica-Bold': {
  25774. 'space': 278,
  25775. 'exclam': 333,
  25776. 'quotedbl': 474,
  25777. 'numbersign': 556,
  25778. 'dollar': 556,
  25779. 'percent': 889,
  25780. 'ampersand': 722,
  25781. 'quoteright': 278,
  25782. 'parenleft': 333,
  25783. 'parenright': 333,
  25784. 'asterisk': 389,
  25785. 'plus': 584,
  25786. 'comma': 278,
  25787. 'hyphen': 333,
  25788. 'period': 278,
  25789. 'slash': 278,
  25790. 'zero': 556,
  25791. 'one': 556,
  25792. 'two': 556,
  25793. 'three': 556,
  25794. 'four': 556,
  25795. 'five': 556,
  25796. 'six': 556,
  25797. 'seven': 556,
  25798. 'eight': 556,
  25799. 'nine': 556,
  25800. 'colon': 333,
  25801. 'semicolon': 333,
  25802. 'less': 584,
  25803. 'equal': 584,
  25804. 'greater': 584,
  25805. 'question': 611,
  25806. 'at': 975,
  25807. 'A': 722,
  25808. 'B': 722,
  25809. 'C': 722,
  25810. 'D': 722,
  25811. 'E': 667,
  25812. 'F': 611,
  25813. 'G': 778,
  25814. 'H': 722,
  25815. 'I': 278,
  25816. 'J': 556,
  25817. 'K': 722,
  25818. 'L': 611,
  25819. 'M': 833,
  25820. 'N': 722,
  25821. 'O': 778,
  25822. 'P': 667,
  25823. 'Q': 778,
  25824. 'R': 722,
  25825. 'S': 667,
  25826. 'T': 611,
  25827. 'U': 722,
  25828. 'V': 667,
  25829. 'W': 944,
  25830. 'X': 667,
  25831. 'Y': 667,
  25832. 'Z': 611,
  25833. 'bracketleft': 333,
  25834. 'backslash': 278,
  25835. 'bracketright': 333,
  25836. 'asciicircum': 584,
  25837. 'underscore': 556,
  25838. 'quoteleft': 278,
  25839. 'a': 556,
  25840. 'b': 611,
  25841. 'c': 556,
  25842. 'd': 611,
  25843. 'e': 556,
  25844. 'f': 333,
  25845. 'g': 611,
  25846. 'h': 611,
  25847. 'i': 278,
  25848. 'j': 278,
  25849. 'k': 556,
  25850. 'l': 278,
  25851. 'm': 889,
  25852. 'n': 611,
  25853. 'o': 611,
  25854. 'p': 611,
  25855. 'q': 611,
  25856. 'r': 389,
  25857. 's': 556,
  25858. 't': 333,
  25859. 'u': 611,
  25860. 'v': 556,
  25861. 'w': 778,
  25862. 'x': 556,
  25863. 'y': 556,
  25864. 'z': 500,
  25865. 'braceleft': 389,
  25866. 'bar': 280,
  25867. 'braceright': 389,
  25868. 'asciitilde': 584,
  25869. 'exclamdown': 333,
  25870. 'cent': 556,
  25871. 'sterling': 556,
  25872. 'fraction': 167,
  25873. 'yen': 556,
  25874. 'florin': 556,
  25875. 'section': 556,
  25876. 'currency': 556,
  25877. 'quotesingle': 238,
  25878. 'quotedblleft': 500,
  25879. 'guillemotleft': 556,
  25880. 'guilsinglleft': 333,
  25881. 'guilsinglright': 333,
  25882. 'fi': 611,
  25883. 'fl': 611,
  25884. 'endash': 556,
  25885. 'dagger': 556,
  25886. 'daggerdbl': 556,
  25887. 'periodcentered': 278,
  25888. 'paragraph': 556,
  25889. 'bullet': 350,
  25890. 'quotesinglbase': 278,
  25891. 'quotedblbase': 500,
  25892. 'quotedblright': 500,
  25893. 'guillemotright': 556,
  25894. 'ellipsis': 1000,
  25895. 'perthousand': 1000,
  25896. 'questiondown': 611,
  25897. 'grave': 333,
  25898. 'acute': 333,
  25899. 'circumflex': 333,
  25900. 'tilde': 333,
  25901. 'macron': 333,
  25902. 'breve': 333,
  25903. 'dotaccent': 333,
  25904. 'dieresis': 333,
  25905. 'ring': 333,
  25906. 'cedilla': 333,
  25907. 'hungarumlaut': 333,
  25908. 'ogonek': 333,
  25909. 'caron': 333,
  25910. 'emdash': 1000,
  25911. 'AE': 1000,
  25912. 'ordfeminine': 370,
  25913. 'Lslash': 611,
  25914. 'Oslash': 778,
  25915. 'OE': 1000,
  25916. 'ordmasculine': 365,
  25917. 'ae': 889,
  25918. 'dotlessi': 278,
  25919. 'lslash': 278,
  25920. 'oslash': 611,
  25921. 'oe': 944,
  25922. 'germandbls': 611,
  25923. 'Idieresis': 278,
  25924. 'eacute': 556,
  25925. 'abreve': 556,
  25926. 'uhungarumlaut': 611,
  25927. 'ecaron': 556,
  25928. 'Ydieresis': 667,
  25929. 'divide': 584,
  25930. 'Yacute': 667,
  25931. 'Acircumflex': 722,
  25932. 'aacute': 556,
  25933. 'Ucircumflex': 722,
  25934. 'yacute': 556,
  25935. 'scommaaccent': 556,
  25936. 'ecircumflex': 556,
  25937. 'Uring': 722,
  25938. 'Udieresis': 722,
  25939. 'aogonek': 556,
  25940. 'Uacute': 722,
  25941. 'uogonek': 611,
  25942. 'Edieresis': 667,
  25943. 'Dcroat': 722,
  25944. 'commaaccent': 250,
  25945. 'copyright': 737,
  25946. 'Emacron': 667,
  25947. 'ccaron': 556,
  25948. 'aring': 556,
  25949. 'Ncommaaccent': 722,
  25950. 'lacute': 278,
  25951. 'agrave': 556,
  25952. 'Tcommaaccent': 611,
  25953. 'Cacute': 722,
  25954. 'atilde': 556,
  25955. 'Edotaccent': 667,
  25956. 'scaron': 556,
  25957. 'scedilla': 556,
  25958. 'iacute': 278,
  25959. 'lozenge': 494,
  25960. 'Rcaron': 722,
  25961. 'Gcommaaccent': 778,
  25962. 'ucircumflex': 611,
  25963. 'acircumflex': 556,
  25964. 'Amacron': 722,
  25965. 'rcaron': 389,
  25966. 'ccedilla': 556,
  25967. 'Zdotaccent': 611,
  25968. 'Thorn': 667,
  25969. 'Omacron': 778,
  25970. 'Racute': 722,
  25971. 'Sacute': 667,
  25972. 'dcaron': 743,
  25973. 'Umacron': 722,
  25974. 'uring': 611,
  25975. 'threesuperior': 333,
  25976. 'Ograve': 778,
  25977. 'Agrave': 722,
  25978. 'Abreve': 722,
  25979. 'multiply': 584,
  25980. 'uacute': 611,
  25981. 'Tcaron': 611,
  25982. 'partialdiff': 494,
  25983. 'ydieresis': 556,
  25984. 'Nacute': 722,
  25985. 'icircumflex': 278,
  25986. 'Ecircumflex': 667,
  25987. 'adieresis': 556,
  25988. 'edieresis': 556,
  25989. 'cacute': 556,
  25990. 'nacute': 611,
  25991. 'umacron': 611,
  25992. 'Ncaron': 722,
  25993. 'Iacute': 278,
  25994. 'plusminus': 584,
  25995. 'brokenbar': 280,
  25996. 'registered': 737,
  25997. 'Gbreve': 778,
  25998. 'Idotaccent': 278,
  25999. 'summation': 600,
  26000. 'Egrave': 667,
  26001. 'racute': 389,
  26002. 'omacron': 611,
  26003. 'Zacute': 611,
  26004. 'Zcaron': 611,
  26005. 'greaterequal': 549,
  26006. 'Eth': 722,
  26007. 'Ccedilla': 722,
  26008. 'lcommaaccent': 278,
  26009. 'tcaron': 389,
  26010. 'eogonek': 556,
  26011. 'Uogonek': 722,
  26012. 'Aacute': 722,
  26013. 'Adieresis': 722,
  26014. 'egrave': 556,
  26015. 'zacute': 500,
  26016. 'iogonek': 278,
  26017. 'Oacute': 778,
  26018. 'oacute': 611,
  26019. 'amacron': 556,
  26020. 'sacute': 556,
  26021. 'idieresis': 278,
  26022. 'Ocircumflex': 778,
  26023. 'Ugrave': 722,
  26024. 'Delta': 612,
  26025. 'thorn': 611,
  26026. 'twosuperior': 333,
  26027. 'Odieresis': 778,
  26028. 'mu': 611,
  26029. 'igrave': 278,
  26030. 'ohungarumlaut': 611,
  26031. 'Eogonek': 667,
  26032. 'dcroat': 611,
  26033. 'threequarters': 834,
  26034. 'Scedilla': 667,
  26035. 'lcaron': 400,
  26036. 'Kcommaaccent': 722,
  26037. 'Lacute': 611,
  26038. 'trademark': 1000,
  26039. 'edotaccent': 556,
  26040. 'Igrave': 278,
  26041. 'Imacron': 278,
  26042. 'Lcaron': 611,
  26043. 'onehalf': 834,
  26044. 'lessequal': 549,
  26045. 'ocircumflex': 611,
  26046. 'ntilde': 611,
  26047. 'Uhungarumlaut': 722,
  26048. 'Eacute': 667,
  26049. 'emacron': 556,
  26050. 'gbreve': 611,
  26051. 'onequarter': 834,
  26052. 'Scaron': 667,
  26053. 'Scommaaccent': 667,
  26054. 'Ohungarumlaut': 778,
  26055. 'degree': 400,
  26056. 'ograve': 611,
  26057. 'Ccaron': 722,
  26058. 'ugrave': 611,
  26059. 'radical': 549,
  26060. 'Dcaron': 722,
  26061. 'rcommaaccent': 389,
  26062. 'Ntilde': 722,
  26063. 'otilde': 611,
  26064. 'Rcommaaccent': 722,
  26065. 'Lcommaaccent': 611,
  26066. 'Atilde': 722,
  26067. 'Aogonek': 722,
  26068. 'Aring': 722,
  26069. 'Otilde': 778,
  26070. 'zdotaccent': 500,
  26071. 'Ecaron': 667,
  26072. 'Iogonek': 278,
  26073. 'kcommaaccent': 556,
  26074. 'minus': 584,
  26075. 'Icircumflex': 278,
  26076. 'ncaron': 611,
  26077. 'tcommaaccent': 333,
  26078. 'logicalnot': 584,
  26079. 'odieresis': 611,
  26080. 'udieresis': 611,
  26081. 'notequal': 549,
  26082. 'gcommaaccent': 611,
  26083. 'eth': 611,
  26084. 'zcaron': 500,
  26085. 'ncommaaccent': 611,
  26086. 'onesuperior': 333,
  26087. 'imacron': 278,
  26088. 'Euro': 556
  26089. },
  26090. 'Helvetica-BoldOblique': {
  26091. 'space': 278,
  26092. 'exclam': 333,
  26093. 'quotedbl': 474,
  26094. 'numbersign': 556,
  26095. 'dollar': 556,
  26096. 'percent': 889,
  26097. 'ampersand': 722,
  26098. 'quoteright': 278,
  26099. 'parenleft': 333,
  26100. 'parenright': 333,
  26101. 'asterisk': 389,
  26102. 'plus': 584,
  26103. 'comma': 278,
  26104. 'hyphen': 333,
  26105. 'period': 278,
  26106. 'slash': 278,
  26107. 'zero': 556,
  26108. 'one': 556,
  26109. 'two': 556,
  26110. 'three': 556,
  26111. 'four': 556,
  26112. 'five': 556,
  26113. 'six': 556,
  26114. 'seven': 556,
  26115. 'eight': 556,
  26116. 'nine': 556,
  26117. 'colon': 333,
  26118. 'semicolon': 333,
  26119. 'less': 584,
  26120. 'equal': 584,
  26121. 'greater': 584,
  26122. 'question': 611,
  26123. 'at': 975,
  26124. 'A': 722,
  26125. 'B': 722,
  26126. 'C': 722,
  26127. 'D': 722,
  26128. 'E': 667,
  26129. 'F': 611,
  26130. 'G': 778,
  26131. 'H': 722,
  26132. 'I': 278,
  26133. 'J': 556,
  26134. 'K': 722,
  26135. 'L': 611,
  26136. 'M': 833,
  26137. 'N': 722,
  26138. 'O': 778,
  26139. 'P': 667,
  26140. 'Q': 778,
  26141. 'R': 722,
  26142. 'S': 667,
  26143. 'T': 611,
  26144. 'U': 722,
  26145. 'V': 667,
  26146. 'W': 944,
  26147. 'X': 667,
  26148. 'Y': 667,
  26149. 'Z': 611,
  26150. 'bracketleft': 333,
  26151. 'backslash': 278,
  26152. 'bracketright': 333,
  26153. 'asciicircum': 584,
  26154. 'underscore': 556,
  26155. 'quoteleft': 278,
  26156. 'a': 556,
  26157. 'b': 611,
  26158. 'c': 556,
  26159. 'd': 611,
  26160. 'e': 556,
  26161. 'f': 333,
  26162. 'g': 611,
  26163. 'h': 611,
  26164. 'i': 278,
  26165. 'j': 278,
  26166. 'k': 556,
  26167. 'l': 278,
  26168. 'm': 889,
  26169. 'n': 611,
  26170. 'o': 611,
  26171. 'p': 611,
  26172. 'q': 611,
  26173. 'r': 389,
  26174. 's': 556,
  26175. 't': 333,
  26176. 'u': 611,
  26177. 'v': 556,
  26178. 'w': 778,
  26179. 'x': 556,
  26180. 'y': 556,
  26181. 'z': 500,
  26182. 'braceleft': 389,
  26183. 'bar': 280,
  26184. 'braceright': 389,
  26185. 'asciitilde': 584,
  26186. 'exclamdown': 333,
  26187. 'cent': 556,
  26188. 'sterling': 556,
  26189. 'fraction': 167,
  26190. 'yen': 556,
  26191. 'florin': 556,
  26192. 'section': 556,
  26193. 'currency': 556,
  26194. 'quotesingle': 238,
  26195. 'quotedblleft': 500,
  26196. 'guillemotleft': 556,
  26197. 'guilsinglleft': 333,
  26198. 'guilsinglright': 333,
  26199. 'fi': 611,
  26200. 'fl': 611,
  26201. 'endash': 556,
  26202. 'dagger': 556,
  26203. 'daggerdbl': 556,
  26204. 'periodcentered': 278,
  26205. 'paragraph': 556,
  26206. 'bullet': 350,
  26207. 'quotesinglbase': 278,
  26208. 'quotedblbase': 500,
  26209. 'quotedblright': 500,
  26210. 'guillemotright': 556,
  26211. 'ellipsis': 1000,
  26212. 'perthousand': 1000,
  26213. 'questiondown': 611,
  26214. 'grave': 333,
  26215. 'acute': 333,
  26216. 'circumflex': 333,
  26217. 'tilde': 333,
  26218. 'macron': 333,
  26219. 'breve': 333,
  26220. 'dotaccent': 333,
  26221. 'dieresis': 333,
  26222. 'ring': 333,
  26223. 'cedilla': 333,
  26224. 'hungarumlaut': 333,
  26225. 'ogonek': 333,
  26226. 'caron': 333,
  26227. 'emdash': 1000,
  26228. 'AE': 1000,
  26229. 'ordfeminine': 370,
  26230. 'Lslash': 611,
  26231. 'Oslash': 778,
  26232. 'OE': 1000,
  26233. 'ordmasculine': 365,
  26234. 'ae': 889,
  26235. 'dotlessi': 278,
  26236. 'lslash': 278,
  26237. 'oslash': 611,
  26238. 'oe': 944,
  26239. 'germandbls': 611,
  26240. 'Idieresis': 278,
  26241. 'eacute': 556,
  26242. 'abreve': 556,
  26243. 'uhungarumlaut': 611,
  26244. 'ecaron': 556,
  26245. 'Ydieresis': 667,
  26246. 'divide': 584,
  26247. 'Yacute': 667,
  26248. 'Acircumflex': 722,
  26249. 'aacute': 556,
  26250. 'Ucircumflex': 722,
  26251. 'yacute': 556,
  26252. 'scommaaccent': 556,
  26253. 'ecircumflex': 556,
  26254. 'Uring': 722,
  26255. 'Udieresis': 722,
  26256. 'aogonek': 556,
  26257. 'Uacute': 722,
  26258. 'uogonek': 611,
  26259. 'Edieresis': 667,
  26260. 'Dcroat': 722,
  26261. 'commaaccent': 250,
  26262. 'copyright': 737,
  26263. 'Emacron': 667,
  26264. 'ccaron': 556,
  26265. 'aring': 556,
  26266. 'Ncommaaccent': 722,
  26267. 'lacute': 278,
  26268. 'agrave': 556,
  26269. 'Tcommaaccent': 611,
  26270. 'Cacute': 722,
  26271. 'atilde': 556,
  26272. 'Edotaccent': 667,
  26273. 'scaron': 556,
  26274. 'scedilla': 556,
  26275. 'iacute': 278,
  26276. 'lozenge': 494,
  26277. 'Rcaron': 722,
  26278. 'Gcommaaccent': 778,
  26279. 'ucircumflex': 611,
  26280. 'acircumflex': 556,
  26281. 'Amacron': 722,
  26282. 'rcaron': 389,
  26283. 'ccedilla': 556,
  26284. 'Zdotaccent': 611,
  26285. 'Thorn': 667,
  26286. 'Omacron': 778,
  26287. 'Racute': 722,
  26288. 'Sacute': 667,
  26289. 'dcaron': 743,
  26290. 'Umacron': 722,
  26291. 'uring': 611,
  26292. 'threesuperior': 333,
  26293. 'Ograve': 778,
  26294. 'Agrave': 722,
  26295. 'Abreve': 722,
  26296. 'multiply': 584,
  26297. 'uacute': 611,
  26298. 'Tcaron': 611,
  26299. 'partialdiff': 494,
  26300. 'ydieresis': 556,
  26301. 'Nacute': 722,
  26302. 'icircumflex': 278,
  26303. 'Ecircumflex': 667,
  26304. 'adieresis': 556,
  26305. 'edieresis': 556,
  26306. 'cacute': 556,
  26307. 'nacute': 611,
  26308. 'umacron': 611,
  26309. 'Ncaron': 722,
  26310. 'Iacute': 278,
  26311. 'plusminus': 584,
  26312. 'brokenbar': 280,
  26313. 'registered': 737,
  26314. 'Gbreve': 778,
  26315. 'Idotaccent': 278,
  26316. 'summation': 600,
  26317. 'Egrave': 667,
  26318. 'racute': 389,
  26319. 'omacron': 611,
  26320. 'Zacute': 611,
  26321. 'Zcaron': 611,
  26322. 'greaterequal': 549,
  26323. 'Eth': 722,
  26324. 'Ccedilla': 722,
  26325. 'lcommaaccent': 278,
  26326. 'tcaron': 389,
  26327. 'eogonek': 556,
  26328. 'Uogonek': 722,
  26329. 'Aacute': 722,
  26330. 'Adieresis': 722,
  26331. 'egrave': 556,
  26332. 'zacute': 500,
  26333. 'iogonek': 278,
  26334. 'Oacute': 778,
  26335. 'oacute': 611,
  26336. 'amacron': 556,
  26337. 'sacute': 556,
  26338. 'idieresis': 278,
  26339. 'Ocircumflex': 778,
  26340. 'Ugrave': 722,
  26341. 'Delta': 612,
  26342. 'thorn': 611,
  26343. 'twosuperior': 333,
  26344. 'Odieresis': 778,
  26345. 'mu': 611,
  26346. 'igrave': 278,
  26347. 'ohungarumlaut': 611,
  26348. 'Eogonek': 667,
  26349. 'dcroat': 611,
  26350. 'threequarters': 834,
  26351. 'Scedilla': 667,
  26352. 'lcaron': 400,
  26353. 'Kcommaaccent': 722,
  26354. 'Lacute': 611,
  26355. 'trademark': 1000,
  26356. 'edotaccent': 556,
  26357. 'Igrave': 278,
  26358. 'Imacron': 278,
  26359. 'Lcaron': 611,
  26360. 'onehalf': 834,
  26361. 'lessequal': 549,
  26362. 'ocircumflex': 611,
  26363. 'ntilde': 611,
  26364. 'Uhungarumlaut': 722,
  26365. 'Eacute': 667,
  26366. 'emacron': 556,
  26367. 'gbreve': 611,
  26368. 'onequarter': 834,
  26369. 'Scaron': 667,
  26370. 'Scommaaccent': 667,
  26371. 'Ohungarumlaut': 778,
  26372. 'degree': 400,
  26373. 'ograve': 611,
  26374. 'Ccaron': 722,
  26375. 'ugrave': 611,
  26376. 'radical': 549,
  26377. 'Dcaron': 722,
  26378. 'rcommaaccent': 389,
  26379. 'Ntilde': 722,
  26380. 'otilde': 611,
  26381. 'Rcommaaccent': 722,
  26382. 'Lcommaaccent': 611,
  26383. 'Atilde': 722,
  26384. 'Aogonek': 722,
  26385. 'Aring': 722,
  26386. 'Otilde': 778,
  26387. 'zdotaccent': 500,
  26388. 'Ecaron': 667,
  26389. 'Iogonek': 278,
  26390. 'kcommaaccent': 556,
  26391. 'minus': 584,
  26392. 'Icircumflex': 278,
  26393. 'ncaron': 611,
  26394. 'tcommaaccent': 333,
  26395. 'logicalnot': 584,
  26396. 'odieresis': 611,
  26397. 'udieresis': 611,
  26398. 'notequal': 549,
  26399. 'gcommaaccent': 611,
  26400. 'eth': 611,
  26401. 'zcaron': 500,
  26402. 'ncommaaccent': 611,
  26403. 'onesuperior': 333,
  26404. 'imacron': 278,
  26405. 'Euro': 556
  26406. },
  26407. 'Helvetica-Oblique' : {
  26408. 'space': 278,
  26409. 'exclam': 278,
  26410. 'quotedbl': 355,
  26411. 'numbersign': 556,
  26412. 'dollar': 556,
  26413. 'percent': 889,
  26414. 'ampersand': 667,
  26415. 'quoteright': 222,
  26416. 'parenleft': 333,
  26417. 'parenright': 333,
  26418. 'asterisk': 389,
  26419. 'plus': 584,
  26420. 'comma': 278,
  26421. 'hyphen': 333,
  26422. 'period': 278,
  26423. 'slash': 278,
  26424. 'zero': 556,
  26425. 'one': 556,
  26426. 'two': 556,
  26427. 'three': 556,
  26428. 'four': 556,
  26429. 'five': 556,
  26430. 'six': 556,
  26431. 'seven': 556,
  26432. 'eight': 556,
  26433. 'nine': 556,
  26434. 'colon': 278,
  26435. 'semicolon': 278,
  26436. 'less': 584,
  26437. 'equal': 584,
  26438. 'greater': 584,
  26439. 'question': 556,
  26440. 'at': 1015,
  26441. 'A': 667,
  26442. 'B': 667,
  26443. 'C': 722,
  26444. 'D': 722,
  26445. 'E': 667,
  26446. 'F': 611,
  26447. 'G': 778,
  26448. 'H': 722,
  26449. 'I': 278,
  26450. 'J': 500,
  26451. 'K': 667,
  26452. 'L': 556,
  26453. 'M': 833,
  26454. 'N': 722,
  26455. 'O': 778,
  26456. 'P': 667,
  26457. 'Q': 778,
  26458. 'R': 722,
  26459. 'S': 667,
  26460. 'T': 611,
  26461. 'U': 722,
  26462. 'V': 667,
  26463. 'W': 944,
  26464. 'X': 667,
  26465. 'Y': 667,
  26466. 'Z': 611,
  26467. 'bracketleft': 278,
  26468. 'backslash': 278,
  26469. 'bracketright': 278,
  26470. 'asciicircum': 469,
  26471. 'underscore': 556,
  26472. 'quoteleft': 222,
  26473. 'a': 556,
  26474. 'b': 556,
  26475. 'c': 500,
  26476. 'd': 556,
  26477. 'e': 556,
  26478. 'f': 278,
  26479. 'g': 556,
  26480. 'h': 556,
  26481. 'i': 222,
  26482. 'j': 222,
  26483. 'k': 500,
  26484. 'l': 222,
  26485. 'm': 833,
  26486. 'n': 556,
  26487. 'o': 556,
  26488. 'p': 556,
  26489. 'q': 556,
  26490. 'r': 333,
  26491. 's': 500,
  26492. 't': 278,
  26493. 'u': 556,
  26494. 'v': 500,
  26495. 'w': 722,
  26496. 'x': 500,
  26497. 'y': 500,
  26498. 'z': 500,
  26499. 'braceleft': 334,
  26500. 'bar': 260,
  26501. 'braceright': 334,
  26502. 'asciitilde': 584,
  26503. 'exclamdown': 333,
  26504. 'cent': 556,
  26505. 'sterling': 556,
  26506. 'fraction': 167,
  26507. 'yen': 556,
  26508. 'florin': 556,
  26509. 'section': 556,
  26510. 'currency': 556,
  26511. 'quotesingle': 191,
  26512. 'quotedblleft': 333,
  26513. 'guillemotleft': 556,
  26514. 'guilsinglleft': 333,
  26515. 'guilsinglright': 333,
  26516. 'fi': 500,
  26517. 'fl': 500,
  26518. 'endash': 556,
  26519. 'dagger': 556,
  26520. 'daggerdbl': 556,
  26521. 'periodcentered': 278,
  26522. 'paragraph': 537,
  26523. 'bullet': 350,
  26524. 'quotesinglbase': 222,
  26525. 'quotedblbase': 333,
  26526. 'quotedblright': 333,
  26527. 'guillemotright': 556,
  26528. 'ellipsis': 1000,
  26529. 'perthousand': 1000,
  26530. 'questiondown': 611,
  26531. 'grave': 333,
  26532. 'acute': 333,
  26533. 'circumflex': 333,
  26534. 'tilde': 333,
  26535. 'macron': 333,
  26536. 'breve': 333,
  26537. 'dotaccent': 333,
  26538. 'dieresis': 333,
  26539. 'ring': 333,
  26540. 'cedilla': 333,
  26541. 'hungarumlaut': 333,
  26542. 'ogonek': 333,
  26543. 'caron': 333,
  26544. 'emdash': 1000,
  26545. 'AE': 1000,
  26546. 'ordfeminine': 370,
  26547. 'Lslash': 556,
  26548. 'Oslash': 778,
  26549. 'OE': 1000,
  26550. 'ordmasculine': 365,
  26551. 'ae': 889,
  26552. 'dotlessi': 278,
  26553. 'lslash': 222,
  26554. 'oslash': 611,
  26555. 'oe': 944,
  26556. 'germandbls': 611,
  26557. 'Idieresis': 278,
  26558. 'eacute': 556,
  26559. 'abreve': 556,
  26560. 'uhungarumlaut': 556,
  26561. 'ecaron': 556,
  26562. 'Ydieresis': 667,
  26563. 'divide': 584,
  26564. 'Yacute': 667,
  26565. 'Acircumflex': 667,
  26566. 'aacute': 556,
  26567. 'Ucircumflex': 722,
  26568. 'yacute': 500,
  26569. 'scommaaccent': 500,
  26570. 'ecircumflex': 556,
  26571. 'Uring': 722,
  26572. 'Udieresis': 722,
  26573. 'aogonek': 556,
  26574. 'Uacute': 722,
  26575. 'uogonek': 556,
  26576. 'Edieresis': 667,
  26577. 'Dcroat': 722,
  26578. 'commaaccent': 250,
  26579. 'copyright': 737,
  26580. 'Emacron': 667,
  26581. 'ccaron': 500,
  26582. 'aring': 556,
  26583. 'Ncommaaccent': 722,
  26584. 'lacute': 222,
  26585. 'agrave': 556,
  26586. 'Tcommaaccent': 611,
  26587. 'Cacute': 722,
  26588. 'atilde': 556,
  26589. 'Edotaccent': 667,
  26590. 'scaron': 500,
  26591. 'scedilla': 500,
  26592. 'iacute': 278,
  26593. 'lozenge': 471,
  26594. 'Rcaron': 722,
  26595. 'Gcommaaccent': 778,
  26596. 'ucircumflex': 556,
  26597. 'acircumflex': 556,
  26598. 'Amacron': 667,
  26599. 'rcaron': 333,
  26600. 'ccedilla': 500,
  26601. 'Zdotaccent': 611,
  26602. 'Thorn': 667,
  26603. 'Omacron': 778,
  26604. 'Racute': 722,
  26605. 'Sacute': 667,
  26606. 'dcaron': 643,
  26607. 'Umacron': 722,
  26608. 'uring': 556,
  26609. 'threesuperior': 333,
  26610. 'Ograve': 778,
  26611. 'Agrave': 667,
  26612. 'Abreve': 667,
  26613. 'multiply': 584,
  26614. 'uacute': 556,
  26615. 'Tcaron': 611,
  26616. 'partialdiff': 476,
  26617. 'ydieresis': 500,
  26618. 'Nacute': 722,
  26619. 'icircumflex': 278,
  26620. 'Ecircumflex': 667,
  26621. 'adieresis': 556,
  26622. 'edieresis': 556,
  26623. 'cacute': 500,
  26624. 'nacute': 556,
  26625. 'umacron': 556,
  26626. 'Ncaron': 722,
  26627. 'Iacute': 278,
  26628. 'plusminus': 584,
  26629. 'brokenbar': 260,
  26630. 'registered': 737,
  26631. 'Gbreve': 778,
  26632. 'Idotaccent': 278,
  26633. 'summation': 600,
  26634. 'Egrave': 667,
  26635. 'racute': 333,
  26636. 'omacron': 556,
  26637. 'Zacute': 611,
  26638. 'Zcaron': 611,
  26639. 'greaterequal': 549,
  26640. 'Eth': 722,
  26641. 'Ccedilla': 722,
  26642. 'lcommaaccent': 222,
  26643. 'tcaron': 317,
  26644. 'eogonek': 556,
  26645. 'Uogonek': 722,
  26646. 'Aacute': 667,
  26647. 'Adieresis': 667,
  26648. 'egrave': 556,
  26649. 'zacute': 500,
  26650. 'iogonek': 222,
  26651. 'Oacute': 778,
  26652. 'oacute': 556,
  26653. 'amacron': 556,
  26654. 'sacute': 500,
  26655. 'idieresis': 278,
  26656. 'Ocircumflex': 778,
  26657. 'Ugrave': 722,
  26658. 'Delta': 612,
  26659. 'thorn': 556,
  26660. 'twosuperior': 333,
  26661. 'Odieresis': 778,
  26662. 'mu': 556,
  26663. 'igrave': 278,
  26664. 'ohungarumlaut': 556,
  26665. 'Eogonek': 667,
  26666. 'dcroat': 556,
  26667. 'threequarters': 834,
  26668. 'Scedilla': 667,
  26669. 'lcaron': 299,
  26670. 'Kcommaaccent': 667,
  26671. 'Lacute': 556,
  26672. 'trademark': 1000,
  26673. 'edotaccent': 556,
  26674. 'Igrave': 278,
  26675. 'Imacron': 278,
  26676. 'Lcaron': 556,
  26677. 'onehalf': 834,
  26678. 'lessequal': 549,
  26679. 'ocircumflex': 556,
  26680. 'ntilde': 556,
  26681. 'Uhungarumlaut': 722,
  26682. 'Eacute': 667,
  26683. 'emacron': 556,
  26684. 'gbreve': 556,
  26685. 'onequarter': 834,
  26686. 'Scaron': 667,
  26687. 'Scommaaccent': 667,
  26688. 'Ohungarumlaut': 778,
  26689. 'degree': 400,
  26690. 'ograve': 556,
  26691. 'Ccaron': 722,
  26692. 'ugrave': 556,
  26693. 'radical': 453,
  26694. 'Dcaron': 722,
  26695. 'rcommaaccent': 333,
  26696. 'Ntilde': 722,
  26697. 'otilde': 556,
  26698. 'Rcommaaccent': 722,
  26699. 'Lcommaaccent': 556,
  26700. 'Atilde': 667,
  26701. 'Aogonek': 667,
  26702. 'Aring': 667,
  26703. 'Otilde': 778,
  26704. 'zdotaccent': 500,
  26705. 'Ecaron': 667,
  26706. 'Iogonek': 278,
  26707. 'kcommaaccent': 500,
  26708. 'minus': 584,
  26709. 'Icircumflex': 278,
  26710. 'ncaron': 556,
  26711. 'tcommaaccent': 278,
  26712. 'logicalnot': 584,
  26713. 'odieresis': 556,
  26714. 'udieresis': 556,
  26715. 'notequal': 549,
  26716. 'gcommaaccent': 556,
  26717. 'eth': 556,
  26718. 'zcaron': 500,
  26719. 'ncommaaccent': 556,
  26720. 'onesuperior': 333,
  26721. 'imacron': 278,
  26722. 'Euro': 556
  26723. },
  26724. 'Symbol': {
  26725. 'space': 250,
  26726. 'exclam': 333,
  26727. 'universal': 713,
  26728. 'numbersign': 500,
  26729. 'existential': 549,
  26730. 'percent': 833,
  26731. 'ampersand': 778,
  26732. 'suchthat': 439,
  26733. 'parenleft': 333,
  26734. 'parenright': 333,
  26735. 'asteriskmath': 500,
  26736. 'plus': 549,
  26737. 'comma': 250,
  26738. 'minus': 549,
  26739. 'period': 250,
  26740. 'slash': 278,
  26741. 'zero': 500,
  26742. 'one': 500,
  26743. 'two': 500,
  26744. 'three': 500,
  26745. 'four': 500,
  26746. 'five': 500,
  26747. 'six': 500,
  26748. 'seven': 500,
  26749. 'eight': 500,
  26750. 'nine': 500,
  26751. 'colon': 278,
  26752. 'semicolon': 278,
  26753. 'less': 549,
  26754. 'equal': 549,
  26755. 'greater': 549,
  26756. 'question': 444,
  26757. 'congruent': 549,
  26758. 'Alpha': 722,
  26759. 'Beta': 667,
  26760. 'Chi': 722,
  26761. 'Delta': 612,
  26762. 'Epsilon': 611,
  26763. 'Phi': 763,
  26764. 'Gamma': 603,
  26765. 'Eta': 722,
  26766. 'Iota': 333,
  26767. 'theta1': 631,
  26768. 'Kappa': 722,
  26769. 'Lambda': 686,
  26770. 'Mu': 889,
  26771. 'Nu': 722,
  26772. 'Omicron': 722,
  26773. 'Pi': 768,
  26774. 'Theta': 741,
  26775. 'Rho': 556,
  26776. 'Sigma': 592,
  26777. 'Tau': 611,
  26778. 'Upsilon': 690,
  26779. 'sigma1': 439,
  26780. 'Omega': 768,
  26781. 'Xi': 645,
  26782. 'Psi': 795,
  26783. 'Zeta': 611,
  26784. 'bracketleft': 333,
  26785. 'therefore': 863,
  26786. 'bracketright': 333,
  26787. 'perpendicular': 658,
  26788. 'underscore': 500,
  26789. 'radicalex': 500,
  26790. 'alpha': 631,
  26791. 'beta': 549,
  26792. 'chi': 549,
  26793. 'delta': 494,
  26794. 'epsilon': 439,
  26795. 'phi': 521,
  26796. 'gamma': 411,
  26797. 'eta': 603,
  26798. 'iota': 329,
  26799. 'phi1': 603,
  26800. 'kappa': 549,
  26801. 'lambda': 549,
  26802. 'mu': 576,
  26803. 'nu': 521,
  26804. 'omicron': 549,
  26805. 'pi': 549,
  26806. 'theta': 521,
  26807. 'rho': 549,
  26808. 'sigma': 603,
  26809. 'tau': 439,
  26810. 'upsilon': 576,
  26811. 'omega1': 713,
  26812. 'omega': 686,
  26813. 'xi': 493,
  26814. 'psi': 686,
  26815. 'zeta': 494,
  26816. 'braceleft': 480,
  26817. 'bar': 200,
  26818. 'braceright': 480,
  26819. 'similar': 549,
  26820. 'Euro': 750,
  26821. 'Upsilon1': 620,
  26822. 'minute': 247,
  26823. 'lessequal': 549,
  26824. 'fraction': 167,
  26825. 'infinity': 713,
  26826. 'florin': 500,
  26827. 'club': 753,
  26828. 'diamond': 753,
  26829. 'heart': 753,
  26830. 'spade': 753,
  26831. 'arrowboth': 1042,
  26832. 'arrowleft': 987,
  26833. 'arrowup': 603,
  26834. 'arrowright': 987,
  26835. 'arrowdown': 603,
  26836. 'degree': 400,
  26837. 'plusminus': 549,
  26838. 'second': 411,
  26839. 'greaterequal': 549,
  26840. 'multiply': 549,
  26841. 'proportional': 713,
  26842. 'partialdiff': 494,
  26843. 'bullet': 460,
  26844. 'divide': 549,
  26845. 'notequal': 549,
  26846. 'equivalence': 549,
  26847. 'approxequal': 549,
  26848. 'ellipsis': 1000,
  26849. 'arrowvertex': 603,
  26850. 'arrowhorizex': 1000,
  26851. 'carriagereturn': 658,
  26852. 'aleph': 823,
  26853. 'Ifraktur': 686,
  26854. 'Rfraktur': 795,
  26855. 'weierstrass': 987,
  26856. 'circlemultiply': 768,
  26857. 'circleplus': 768,
  26858. 'emptyset': 823,
  26859. 'intersection': 768,
  26860. 'union': 768,
  26861. 'propersuperset': 713,
  26862. 'reflexsuperset': 713,
  26863. 'notsubset': 713,
  26864. 'propersubset': 713,
  26865. 'reflexsubset': 713,
  26866. 'element': 713,
  26867. 'notelement': 713,
  26868. 'angle': 768,
  26869. 'gradient': 713,
  26870. 'registerserif': 790,
  26871. 'copyrightserif': 790,
  26872. 'trademarkserif': 890,
  26873. 'product': 823,
  26874. 'radical': 549,
  26875. 'dotmath': 250,
  26876. 'logicalnot': 713,
  26877. 'logicaland': 603,
  26878. 'logicalor': 603,
  26879. 'arrowdblboth': 1042,
  26880. 'arrowdblleft': 987,
  26881. 'arrowdblup': 603,
  26882. 'arrowdblright': 987,
  26883. 'arrowdbldown': 603,
  26884. 'lozenge': 494,
  26885. 'angleleft': 329,
  26886. 'registersans': 790,
  26887. 'copyrightsans': 790,
  26888. 'trademarksans': 786,
  26889. 'summation': 713,
  26890. 'parenlefttp': 384,
  26891. 'parenleftex': 384,
  26892. 'parenleftbt': 384,
  26893. 'bracketlefttp': 384,
  26894. 'bracketleftex': 384,
  26895. 'bracketleftbt': 384,
  26896. 'bracelefttp': 494,
  26897. 'braceleftmid': 494,
  26898. 'braceleftbt': 494,
  26899. 'braceex': 494,
  26900. 'angleright': 329,
  26901. 'integral': 274,
  26902. 'integraltp': 686,
  26903. 'integralex': 686,
  26904. 'integralbt': 686,
  26905. 'parenrighttp': 384,
  26906. 'parenrightex': 384,
  26907. 'parenrightbt': 384,
  26908. 'bracketrighttp': 384,
  26909. 'bracketrightex': 384,
  26910. 'bracketrightbt': 384,
  26911. 'bracerighttp': 494,
  26912. 'bracerightmid': 494,
  26913. 'bracerightbt': 494,
  26914. 'apple': 790
  26915. },
  26916. 'Times-Roman': {
  26917. 'space': 250,
  26918. 'exclam': 333,
  26919. 'quotedbl': 408,
  26920. 'numbersign': 500,
  26921. 'dollar': 500,
  26922. 'percent': 833,
  26923. 'ampersand': 778,
  26924. 'quoteright': 333,
  26925. 'parenleft': 333,
  26926. 'parenright': 333,
  26927. 'asterisk': 500,
  26928. 'plus': 564,
  26929. 'comma': 250,
  26930. 'hyphen': 333,
  26931. 'period': 250,
  26932. 'slash': 278,
  26933. 'zero': 500,
  26934. 'one': 500,
  26935. 'two': 500,
  26936. 'three': 500,
  26937. 'four': 500,
  26938. 'five': 500,
  26939. 'six': 500,
  26940. 'seven': 500,
  26941. 'eight': 500,
  26942. 'nine': 500,
  26943. 'colon': 278,
  26944. 'semicolon': 278,
  26945. 'less': 564,
  26946. 'equal': 564,
  26947. 'greater': 564,
  26948. 'question': 444,
  26949. 'at': 921,
  26950. 'A': 722,
  26951. 'B': 667,
  26952. 'C': 667,
  26953. 'D': 722,
  26954. 'E': 611,
  26955. 'F': 556,
  26956. 'G': 722,
  26957. 'H': 722,
  26958. 'I': 333,
  26959. 'J': 389,
  26960. 'K': 722,
  26961. 'L': 611,
  26962. 'M': 889,
  26963. 'N': 722,
  26964. 'O': 722,
  26965. 'P': 556,
  26966. 'Q': 722,
  26967. 'R': 667,
  26968. 'S': 556,
  26969. 'T': 611,
  26970. 'U': 722,
  26971. 'V': 722,
  26972. 'W': 944,
  26973. 'X': 722,
  26974. 'Y': 722,
  26975. 'Z': 611,
  26976. 'bracketleft': 333,
  26977. 'backslash': 278,
  26978. 'bracketright': 333,
  26979. 'asciicircum': 469,
  26980. 'underscore': 500,
  26981. 'quoteleft': 333,
  26982. 'a': 444,
  26983. 'b': 500,
  26984. 'c': 444,
  26985. 'd': 500,
  26986. 'e': 444,
  26987. 'f': 333,
  26988. 'g': 500,
  26989. 'h': 500,
  26990. 'i': 278,
  26991. 'j': 278,
  26992. 'k': 500,
  26993. 'l': 278,
  26994. 'm': 778,
  26995. 'n': 500,
  26996. 'o': 500,
  26997. 'p': 500,
  26998. 'q': 500,
  26999. 'r': 333,
  27000. 's': 389,
  27001. 't': 278,
  27002. 'u': 500,
  27003. 'v': 500,
  27004. 'w': 722,
  27005. 'x': 500,
  27006. 'y': 500,
  27007. 'z': 444,
  27008. 'braceleft': 480,
  27009. 'bar': 200,
  27010. 'braceright': 480,
  27011. 'asciitilde': 541,
  27012. 'exclamdown': 333,
  27013. 'cent': 500,
  27014. 'sterling': 500,
  27015. 'fraction': 167,
  27016. 'yen': 500,
  27017. 'florin': 500,
  27018. 'section': 500,
  27019. 'currency': 500,
  27020. 'quotesingle': 180,
  27021. 'quotedblleft': 444,
  27022. 'guillemotleft': 500,
  27023. 'guilsinglleft': 333,
  27024. 'guilsinglright': 333,
  27025. 'fi': 556,
  27026. 'fl': 556,
  27027. 'endash': 500,
  27028. 'dagger': 500,
  27029. 'daggerdbl': 500,
  27030. 'periodcentered': 250,
  27031. 'paragraph': 453,
  27032. 'bullet': 350,
  27033. 'quotesinglbase': 333,
  27034. 'quotedblbase': 444,
  27035. 'quotedblright': 444,
  27036. 'guillemotright': 500,
  27037. 'ellipsis': 1000,
  27038. 'perthousand': 1000,
  27039. 'questiondown': 444,
  27040. 'grave': 333,
  27041. 'acute': 333,
  27042. 'circumflex': 333,
  27043. 'tilde': 333,
  27044. 'macron': 333,
  27045. 'breve': 333,
  27046. 'dotaccent': 333,
  27047. 'dieresis': 333,
  27048. 'ring': 333,
  27049. 'cedilla': 333,
  27050. 'hungarumlaut': 333,
  27051. 'ogonek': 333,
  27052. 'caron': 333,
  27053. 'emdash': 1000,
  27054. 'AE': 889,
  27055. 'ordfeminine': 276,
  27056. 'Lslash': 611,
  27057. 'Oslash': 722,
  27058. 'OE': 889,
  27059. 'ordmasculine': 310,
  27060. 'ae': 667,
  27061. 'dotlessi': 278,
  27062. 'lslash': 278,
  27063. 'oslash': 500,
  27064. 'oe': 722,
  27065. 'germandbls': 500,
  27066. 'Idieresis': 333,
  27067. 'eacute': 444,
  27068. 'abreve': 444,
  27069. 'uhungarumlaut': 500,
  27070. 'ecaron': 444,
  27071. 'Ydieresis': 722,
  27072. 'divide': 564,
  27073. 'Yacute': 722,
  27074. 'Acircumflex': 722,
  27075. 'aacute': 444,
  27076. 'Ucircumflex': 722,
  27077. 'yacute': 500,
  27078. 'scommaaccent': 389,
  27079. 'ecircumflex': 444,
  27080. 'Uring': 722,
  27081. 'Udieresis': 722,
  27082. 'aogonek': 444,
  27083. 'Uacute': 722,
  27084. 'uogonek': 500,
  27085. 'Edieresis': 611,
  27086. 'Dcroat': 722,
  27087. 'commaaccent': 250,
  27088. 'copyright': 760,
  27089. 'Emacron': 611,
  27090. 'ccaron': 444,
  27091. 'aring': 444,
  27092. 'Ncommaaccent': 722,
  27093. 'lacute': 278,
  27094. 'agrave': 444,
  27095. 'Tcommaaccent': 611,
  27096. 'Cacute': 667,
  27097. 'atilde': 444,
  27098. 'Edotaccent': 611,
  27099. 'scaron': 389,
  27100. 'scedilla': 389,
  27101. 'iacute': 278,
  27102. 'lozenge': 471,
  27103. 'Rcaron': 667,
  27104. 'Gcommaaccent': 722,
  27105. 'ucircumflex': 500,
  27106. 'acircumflex': 444,
  27107. 'Amacron': 722,
  27108. 'rcaron': 333,
  27109. 'ccedilla': 444,
  27110. 'Zdotaccent': 611,
  27111. 'Thorn': 556,
  27112. 'Omacron': 722,
  27113. 'Racute': 667,
  27114. 'Sacute': 556,
  27115. 'dcaron': 588,
  27116. 'Umacron': 722,
  27117. 'uring': 500,
  27118. 'threesuperior': 300,
  27119. 'Ograve': 722,
  27120. 'Agrave': 722,
  27121. 'Abreve': 722,
  27122. 'multiply': 564,
  27123. 'uacute': 500,
  27124. 'Tcaron': 611,
  27125. 'partialdiff': 476,
  27126. 'ydieresis': 500,
  27127. 'Nacute': 722,
  27128. 'icircumflex': 278,
  27129. 'Ecircumflex': 611,
  27130. 'adieresis': 444,
  27131. 'edieresis': 444,
  27132. 'cacute': 444,
  27133. 'nacute': 500,
  27134. 'umacron': 500,
  27135. 'Ncaron': 722,
  27136. 'Iacute': 333,
  27137. 'plusminus': 564,
  27138. 'brokenbar': 200,
  27139. 'registered': 760,
  27140. 'Gbreve': 722,
  27141. 'Idotaccent': 333,
  27142. 'summation': 600,
  27143. 'Egrave': 611,
  27144. 'racute': 333,
  27145. 'omacron': 500,
  27146. 'Zacute': 611,
  27147. 'Zcaron': 611,
  27148. 'greaterequal': 549,
  27149. 'Eth': 722,
  27150. 'Ccedilla': 667,
  27151. 'lcommaaccent': 278,
  27152. 'tcaron': 326,
  27153. 'eogonek': 444,
  27154. 'Uogonek': 722,
  27155. 'Aacute': 722,
  27156. 'Adieresis': 722,
  27157. 'egrave': 444,
  27158. 'zacute': 444,
  27159. 'iogonek': 278,
  27160. 'Oacute': 722,
  27161. 'oacute': 500,
  27162. 'amacron': 444,
  27163. 'sacute': 389,
  27164. 'idieresis': 278,
  27165. 'Ocircumflex': 722,
  27166. 'Ugrave': 722,
  27167. 'Delta': 612,
  27168. 'thorn': 500,
  27169. 'twosuperior': 300,
  27170. 'Odieresis': 722,
  27171. 'mu': 500,
  27172. 'igrave': 278,
  27173. 'ohungarumlaut': 500,
  27174. 'Eogonek': 611,
  27175. 'dcroat': 500,
  27176. 'threequarters': 750,
  27177. 'Scedilla': 556,
  27178. 'lcaron': 344,
  27179. 'Kcommaaccent': 722,
  27180. 'Lacute': 611,
  27181. 'trademark': 980,
  27182. 'edotaccent': 444,
  27183. 'Igrave': 333,
  27184. 'Imacron': 333,
  27185. 'Lcaron': 611,
  27186. 'onehalf': 750,
  27187. 'lessequal': 549,
  27188. 'ocircumflex': 500,
  27189. 'ntilde': 500,
  27190. 'Uhungarumlaut': 722,
  27191. 'Eacute': 611,
  27192. 'emacron': 444,
  27193. 'gbreve': 500,
  27194. 'onequarter': 750,
  27195. 'Scaron': 556,
  27196. 'Scommaaccent': 556,
  27197. 'Ohungarumlaut': 722,
  27198. 'degree': 400,
  27199. 'ograve': 500,
  27200. 'Ccaron': 667,
  27201. 'ugrave': 500,
  27202. 'radical': 453,
  27203. 'Dcaron': 722,
  27204. 'rcommaaccent': 333,
  27205. 'Ntilde': 722,
  27206. 'otilde': 500,
  27207. 'Rcommaaccent': 667,
  27208. 'Lcommaaccent': 611,
  27209. 'Atilde': 722,
  27210. 'Aogonek': 722,
  27211. 'Aring': 722,
  27212. 'Otilde': 722,
  27213. 'zdotaccent': 444,
  27214. 'Ecaron': 611,
  27215. 'Iogonek': 333,
  27216. 'kcommaaccent': 500,
  27217. 'minus': 564,
  27218. 'Icircumflex': 333,
  27219. 'ncaron': 500,
  27220. 'tcommaaccent': 278,
  27221. 'logicalnot': 564,
  27222. 'odieresis': 500,
  27223. 'udieresis': 500,
  27224. 'notequal': 549,
  27225. 'gcommaaccent': 500,
  27226. 'eth': 500,
  27227. 'zcaron': 444,
  27228. 'ncommaaccent': 500,
  27229. 'onesuperior': 300,
  27230. 'imacron': 278,
  27231. 'Euro': 500
  27232. },
  27233. 'Times-Bold': {
  27234. 'space': 250,
  27235. 'exclam': 333,
  27236. 'quotedbl': 555,
  27237. 'numbersign': 500,
  27238. 'dollar': 500,
  27239. 'percent': 1000,
  27240. 'ampersand': 833,
  27241. 'quoteright': 333,
  27242. 'parenleft': 333,
  27243. 'parenright': 333,
  27244. 'asterisk': 500,
  27245. 'plus': 570,
  27246. 'comma': 250,
  27247. 'hyphen': 333,
  27248. 'period': 250,
  27249. 'slash': 278,
  27250. 'zero': 500,
  27251. 'one': 500,
  27252. 'two': 500,
  27253. 'three': 500,
  27254. 'four': 500,
  27255. 'five': 500,
  27256. 'six': 500,
  27257. 'seven': 500,
  27258. 'eight': 500,
  27259. 'nine': 500,
  27260. 'colon': 333,
  27261. 'semicolon': 333,
  27262. 'less': 570,
  27263. 'equal': 570,
  27264. 'greater': 570,
  27265. 'question': 500,
  27266. 'at': 930,
  27267. 'A': 722,
  27268. 'B': 667,
  27269. 'C': 722,
  27270. 'D': 722,
  27271. 'E': 667,
  27272. 'F': 611,
  27273. 'G': 778,
  27274. 'H': 778,
  27275. 'I': 389,
  27276. 'J': 500,
  27277. 'K': 778,
  27278. 'L': 667,
  27279. 'M': 944,
  27280. 'N': 722,
  27281. 'O': 778,
  27282. 'P': 611,
  27283. 'Q': 778,
  27284. 'R': 722,
  27285. 'S': 556,
  27286. 'T': 667,
  27287. 'U': 722,
  27288. 'V': 722,
  27289. 'W': 1000,
  27290. 'X': 722,
  27291. 'Y': 722,
  27292. 'Z': 667,
  27293. 'bracketleft': 333,
  27294. 'backslash': 278,
  27295. 'bracketright': 333,
  27296. 'asciicircum': 581,
  27297. 'underscore': 500,
  27298. 'quoteleft': 333,
  27299. 'a': 500,
  27300. 'b': 556,
  27301. 'c': 444,
  27302. 'd': 556,
  27303. 'e': 444,
  27304. 'f': 333,
  27305. 'g': 500,
  27306. 'h': 556,
  27307. 'i': 278,
  27308. 'j': 333,
  27309. 'k': 556,
  27310. 'l': 278,
  27311. 'm': 833,
  27312. 'n': 556,
  27313. 'o': 500,
  27314. 'p': 556,
  27315. 'q': 556,
  27316. 'r': 444,
  27317. 's': 389,
  27318. 't': 333,
  27319. 'u': 556,
  27320. 'v': 500,
  27321. 'w': 722,
  27322. 'x': 500,
  27323. 'y': 500,
  27324. 'z': 444,
  27325. 'braceleft': 394,
  27326. 'bar': 220,
  27327. 'braceright': 394,
  27328. 'asciitilde': 520,
  27329. 'exclamdown': 333,
  27330. 'cent': 500,
  27331. 'sterling': 500,
  27332. 'fraction': 167,
  27333. 'yen': 500,
  27334. 'florin': 500,
  27335. 'section': 500,
  27336. 'currency': 500,
  27337. 'quotesingle': 278,
  27338. 'quotedblleft': 500,
  27339. 'guillemotleft': 500,
  27340. 'guilsinglleft': 333,
  27341. 'guilsinglright': 333,
  27342. 'fi': 556,
  27343. 'fl': 556,
  27344. 'endash': 500,
  27345. 'dagger': 500,
  27346. 'daggerdbl': 500,
  27347. 'periodcentered': 250,
  27348. 'paragraph': 540,
  27349. 'bullet': 350,
  27350. 'quotesinglbase': 333,
  27351. 'quotedblbase': 500,
  27352. 'quotedblright': 500,
  27353. 'guillemotright': 500,
  27354. 'ellipsis': 1000,
  27355. 'perthousand': 1000,
  27356. 'questiondown': 500,
  27357. 'grave': 333,
  27358. 'acute': 333,
  27359. 'circumflex': 333,
  27360. 'tilde': 333,
  27361. 'macron': 333,
  27362. 'breve': 333,
  27363. 'dotaccent': 333,
  27364. 'dieresis': 333,
  27365. 'ring': 333,
  27366. 'cedilla': 333,
  27367. 'hungarumlaut': 333,
  27368. 'ogonek': 333,
  27369. 'caron': 333,
  27370. 'emdash': 1000,
  27371. 'AE': 1000,
  27372. 'ordfeminine': 300,
  27373. 'Lslash': 667,
  27374. 'Oslash': 778,
  27375. 'OE': 1000,
  27376. 'ordmasculine': 330,
  27377. 'ae': 722,
  27378. 'dotlessi': 278,
  27379. 'lslash': 278,
  27380. 'oslash': 500,
  27381. 'oe': 722,
  27382. 'germandbls': 556,
  27383. 'Idieresis': 389,
  27384. 'eacute': 444,
  27385. 'abreve': 500,
  27386. 'uhungarumlaut': 556,
  27387. 'ecaron': 444,
  27388. 'Ydieresis': 722,
  27389. 'divide': 570,
  27390. 'Yacute': 722,
  27391. 'Acircumflex': 722,
  27392. 'aacute': 500,
  27393. 'Ucircumflex': 722,
  27394. 'yacute': 500,
  27395. 'scommaaccent': 389,
  27396. 'ecircumflex': 444,
  27397. 'Uring': 722,
  27398. 'Udieresis': 722,
  27399. 'aogonek': 500,
  27400. 'Uacute': 722,
  27401. 'uogonek': 556,
  27402. 'Edieresis': 667,
  27403. 'Dcroat': 722,
  27404. 'commaaccent': 250,
  27405. 'copyright': 747,
  27406. 'Emacron': 667,
  27407. 'ccaron': 444,
  27408. 'aring': 500,
  27409. 'Ncommaaccent': 722,
  27410. 'lacute': 278,
  27411. 'agrave': 500,
  27412. 'Tcommaaccent': 667,
  27413. 'Cacute': 722,
  27414. 'atilde': 500,
  27415. 'Edotaccent': 667,
  27416. 'scaron': 389,
  27417. 'scedilla': 389,
  27418. 'iacute': 278,
  27419. 'lozenge': 494,
  27420. 'Rcaron': 722,
  27421. 'Gcommaaccent': 778,
  27422. 'ucircumflex': 556,
  27423. 'acircumflex': 500,
  27424. 'Amacron': 722,
  27425. 'rcaron': 444,
  27426. 'ccedilla': 444,
  27427. 'Zdotaccent': 667,
  27428. 'Thorn': 611,
  27429. 'Omacron': 778,
  27430. 'Racute': 722,
  27431. 'Sacute': 556,
  27432. 'dcaron': 672,
  27433. 'Umacron': 722,
  27434. 'uring': 556,
  27435. 'threesuperior': 300,
  27436. 'Ograve': 778,
  27437. 'Agrave': 722,
  27438. 'Abreve': 722,
  27439. 'multiply': 570,
  27440. 'uacute': 556,
  27441. 'Tcaron': 667,
  27442. 'partialdiff': 494,
  27443. 'ydieresis': 500,
  27444. 'Nacute': 722,
  27445. 'icircumflex': 278,
  27446. 'Ecircumflex': 667,
  27447. 'adieresis': 500,
  27448. 'edieresis': 444,
  27449. 'cacute': 444,
  27450. 'nacute': 556,
  27451. 'umacron': 556,
  27452. 'Ncaron': 722,
  27453. 'Iacute': 389,
  27454. 'plusminus': 570,
  27455. 'brokenbar': 220,
  27456. 'registered': 747,
  27457. 'Gbreve': 778,
  27458. 'Idotaccent': 389,
  27459. 'summation': 600,
  27460. 'Egrave': 667,
  27461. 'racute': 444,
  27462. 'omacron': 500,
  27463. 'Zacute': 667,
  27464. 'Zcaron': 667,
  27465. 'greaterequal': 549,
  27466. 'Eth': 722,
  27467. 'Ccedilla': 722,
  27468. 'lcommaaccent': 278,
  27469. 'tcaron': 416,
  27470. 'eogonek': 444,
  27471. 'Uogonek': 722,
  27472. 'Aacute': 722,
  27473. 'Adieresis': 722,
  27474. 'egrave': 444,
  27475. 'zacute': 444,
  27476. 'iogonek': 278,
  27477. 'Oacute': 778,
  27478. 'oacute': 500,
  27479. 'amacron': 500,
  27480. 'sacute': 389,
  27481. 'idieresis': 278,
  27482. 'Ocircumflex': 778,
  27483. 'Ugrave': 722,
  27484. 'Delta': 612,
  27485. 'thorn': 556,
  27486. 'twosuperior': 300,
  27487. 'Odieresis': 778,
  27488. 'mu': 556,
  27489. 'igrave': 278,
  27490. 'ohungarumlaut': 500,
  27491. 'Eogonek': 667,
  27492. 'dcroat': 556,
  27493. 'threequarters': 750,
  27494. 'Scedilla': 556,
  27495. 'lcaron': 394,
  27496. 'Kcommaaccent': 778,
  27497. 'Lacute': 667,
  27498. 'trademark': 1000,
  27499. 'edotaccent': 444,
  27500. 'Igrave': 389,
  27501. 'Imacron': 389,
  27502. 'Lcaron': 667,
  27503. 'onehalf': 750,
  27504. 'lessequal': 549,
  27505. 'ocircumflex': 500,
  27506. 'ntilde': 556,
  27507. 'Uhungarumlaut': 722,
  27508. 'Eacute': 667,
  27509. 'emacron': 444,
  27510. 'gbreve': 500,
  27511. 'onequarter': 750,
  27512. 'Scaron': 556,
  27513. 'Scommaaccent': 556,
  27514. 'Ohungarumlaut': 778,
  27515. 'degree': 400,
  27516. 'ograve': 500,
  27517. 'Ccaron': 722,
  27518. 'ugrave': 556,
  27519. 'radical': 549,
  27520. 'Dcaron': 722,
  27521. 'rcommaaccent': 444,
  27522. 'Ntilde': 722,
  27523. 'otilde': 500,
  27524. 'Rcommaaccent': 722,
  27525. 'Lcommaaccent': 667,
  27526. 'Atilde': 722,
  27527. 'Aogonek': 722,
  27528. 'Aring': 722,
  27529. 'Otilde': 778,
  27530. 'zdotaccent': 444,
  27531. 'Ecaron': 667,
  27532. 'Iogonek': 389,
  27533. 'kcommaaccent': 556,
  27534. 'minus': 570,
  27535. 'Icircumflex': 389,
  27536. 'ncaron': 556,
  27537. 'tcommaaccent': 333,
  27538. 'logicalnot': 570,
  27539. 'odieresis': 500,
  27540. 'udieresis': 556,
  27541. 'notequal': 549,
  27542. 'gcommaaccent': 500,
  27543. 'eth': 500,
  27544. 'zcaron': 444,
  27545. 'ncommaaccent': 556,
  27546. 'onesuperior': 300,
  27547. 'imacron': 278,
  27548. 'Euro': 500
  27549. },
  27550. 'Times-BoldItalic': {
  27551. 'space': 250,
  27552. 'exclam': 389,
  27553. 'quotedbl': 555,
  27554. 'numbersign': 500,
  27555. 'dollar': 500,
  27556. 'percent': 833,
  27557. 'ampersand': 778,
  27558. 'quoteright': 333,
  27559. 'parenleft': 333,
  27560. 'parenright': 333,
  27561. 'asterisk': 500,
  27562. 'plus': 570,
  27563. 'comma': 250,
  27564. 'hyphen': 333,
  27565. 'period': 250,
  27566. 'slash': 278,
  27567. 'zero': 500,
  27568. 'one': 500,
  27569. 'two': 500,
  27570. 'three': 500,
  27571. 'four': 500,
  27572. 'five': 500,
  27573. 'six': 500,
  27574. 'seven': 500,
  27575. 'eight': 500,
  27576. 'nine': 500,
  27577. 'colon': 333,
  27578. 'semicolon': 333,
  27579. 'less': 570,
  27580. 'equal': 570,
  27581. 'greater': 570,
  27582. 'question': 500,
  27583. 'at': 832,
  27584. 'A': 667,
  27585. 'B': 667,
  27586. 'C': 667,
  27587. 'D': 722,
  27588. 'E': 667,
  27589. 'F': 667,
  27590. 'G': 722,
  27591. 'H': 778,
  27592. 'I': 389,
  27593. 'J': 500,
  27594. 'K': 667,
  27595. 'L': 611,
  27596. 'M': 889,
  27597. 'N': 722,
  27598. 'O': 722,
  27599. 'P': 611,
  27600. 'Q': 722,
  27601. 'R': 667,
  27602. 'S': 556,
  27603. 'T': 611,
  27604. 'U': 722,
  27605. 'V': 667,
  27606. 'W': 889,
  27607. 'X': 667,
  27608. 'Y': 611,
  27609. 'Z': 611,
  27610. 'bracketleft': 333,
  27611. 'backslash': 278,
  27612. 'bracketright': 333,
  27613. 'asciicircum': 570,
  27614. 'underscore': 500,
  27615. 'quoteleft': 333,
  27616. 'a': 500,
  27617. 'b': 500,
  27618. 'c': 444,
  27619. 'd': 500,
  27620. 'e': 444,
  27621. 'f': 333,
  27622. 'g': 500,
  27623. 'h': 556,
  27624. 'i': 278,
  27625. 'j': 278,
  27626. 'k': 500,
  27627. 'l': 278,
  27628. 'm': 778,
  27629. 'n': 556,
  27630. 'o': 500,
  27631. 'p': 500,
  27632. 'q': 500,
  27633. 'r': 389,
  27634. 's': 389,
  27635. 't': 278,
  27636. 'u': 556,
  27637. 'v': 444,
  27638. 'w': 667,
  27639. 'x': 500,
  27640. 'y': 444,
  27641. 'z': 389,
  27642. 'braceleft': 348,
  27643. 'bar': 220,
  27644. 'braceright': 348,
  27645. 'asciitilde': 570,
  27646. 'exclamdown': 389,
  27647. 'cent': 500,
  27648. 'sterling': 500,
  27649. 'fraction': 167,
  27650. 'yen': 500,
  27651. 'florin': 500,
  27652. 'section': 500,
  27653. 'currency': 500,
  27654. 'quotesingle': 278,
  27655. 'quotedblleft': 500,
  27656. 'guillemotleft': 500,
  27657. 'guilsinglleft': 333,
  27658. 'guilsinglright': 333,
  27659. 'fi': 556,
  27660. 'fl': 556,
  27661. 'endash': 500,
  27662. 'dagger': 500,
  27663. 'daggerdbl': 500,
  27664. 'periodcentered': 250,
  27665. 'paragraph': 500,
  27666. 'bullet': 350,
  27667. 'quotesinglbase': 333,
  27668. 'quotedblbase': 500,
  27669. 'quotedblright': 500,
  27670. 'guillemotright': 500,
  27671. 'ellipsis': 1000,
  27672. 'perthousand': 1000,
  27673. 'questiondown': 500,
  27674. 'grave': 333,
  27675. 'acute': 333,
  27676. 'circumflex': 333,
  27677. 'tilde': 333,
  27678. 'macron': 333,
  27679. 'breve': 333,
  27680. 'dotaccent': 333,
  27681. 'dieresis': 333,
  27682. 'ring': 333,
  27683. 'cedilla': 333,
  27684. 'hungarumlaut': 333,
  27685. 'ogonek': 333,
  27686. 'caron': 333,
  27687. 'emdash': 1000,
  27688. 'AE': 944,
  27689. 'ordfeminine': 266,
  27690. 'Lslash': 611,
  27691. 'Oslash': 722,
  27692. 'OE': 944,
  27693. 'ordmasculine': 300,
  27694. 'ae': 722,
  27695. 'dotlessi': 278,
  27696. 'lslash': 278,
  27697. 'oslash': 500,
  27698. 'oe': 722,
  27699. 'germandbls': 500,
  27700. 'Idieresis': 389,
  27701. 'eacute': 444,
  27702. 'abreve': 500,
  27703. 'uhungarumlaut': 556,
  27704. 'ecaron': 444,
  27705. 'Ydieresis': 611,
  27706. 'divide': 570,
  27707. 'Yacute': 611,
  27708. 'Acircumflex': 667,
  27709. 'aacute': 500,
  27710. 'Ucircumflex': 722,
  27711. 'yacute': 444,
  27712. 'scommaaccent': 389,
  27713. 'ecircumflex': 444,
  27714. 'Uring': 722,
  27715. 'Udieresis': 722,
  27716. 'aogonek': 500,
  27717. 'Uacute': 722,
  27718. 'uogonek': 556,
  27719. 'Edieresis': 667,
  27720. 'Dcroat': 722,
  27721. 'commaaccent': 250,
  27722. 'copyright': 747,
  27723. 'Emacron': 667,
  27724. 'ccaron': 444,
  27725. 'aring': 500,
  27726. 'Ncommaaccent': 722,
  27727. 'lacute': 278,
  27728. 'agrave': 500,
  27729. 'Tcommaaccent': 611,
  27730. 'Cacute': 667,
  27731. 'atilde': 500,
  27732. 'Edotaccent': 667,
  27733. 'scaron': 389,
  27734. 'scedilla': 389,
  27735. 'iacute': 278,
  27736. 'lozenge': 494,
  27737. 'Rcaron': 667,
  27738. 'Gcommaaccent': 722,
  27739. 'ucircumflex': 556,
  27740. 'acircumflex': 500,
  27741. 'Amacron': 667,
  27742. 'rcaron': 389,
  27743. 'ccedilla': 444,
  27744. 'Zdotaccent': 611,
  27745. 'Thorn': 611,
  27746. 'Omacron': 722,
  27747. 'Racute': 667,
  27748. 'Sacute': 556,
  27749. 'dcaron': 608,
  27750. 'Umacron': 722,
  27751. 'uring': 556,
  27752. 'threesuperior': 300,
  27753. 'Ograve': 722,
  27754. 'Agrave': 667,
  27755. 'Abreve': 667,
  27756. 'multiply': 570,
  27757. 'uacute': 556,
  27758. 'Tcaron': 611,
  27759. 'partialdiff': 494,
  27760. 'ydieresis': 444,
  27761. 'Nacute': 722,
  27762. 'icircumflex': 278,
  27763. 'Ecircumflex': 667,
  27764. 'adieresis': 500,
  27765. 'edieresis': 444,
  27766. 'cacute': 444,
  27767. 'nacute': 556,
  27768. 'umacron': 556,
  27769. 'Ncaron': 722,
  27770. 'Iacute': 389,
  27771. 'plusminus': 570,
  27772. 'brokenbar': 220,
  27773. 'registered': 747,
  27774. 'Gbreve': 722,
  27775. 'Idotaccent': 389,
  27776. 'summation': 600,
  27777. 'Egrave': 667,
  27778. 'racute': 389,
  27779. 'omacron': 500,
  27780. 'Zacute': 611,
  27781. 'Zcaron': 611,
  27782. 'greaterequal': 549,
  27783. 'Eth': 722,
  27784. 'Ccedilla': 667,
  27785. 'lcommaaccent': 278,
  27786. 'tcaron': 366,
  27787. 'eogonek': 444,
  27788. 'Uogonek': 722,
  27789. 'Aacute': 667,
  27790. 'Adieresis': 667,
  27791. 'egrave': 444,
  27792. 'zacute': 389,
  27793. 'iogonek': 278,
  27794. 'Oacute': 722,
  27795. 'oacute': 500,
  27796. 'amacron': 500,
  27797. 'sacute': 389,
  27798. 'idieresis': 278,
  27799. 'Ocircumflex': 722,
  27800. 'Ugrave': 722,
  27801. 'Delta': 612,
  27802. 'thorn': 500,
  27803. 'twosuperior': 300,
  27804. 'Odieresis': 722,
  27805. 'mu': 576,
  27806. 'igrave': 278,
  27807. 'ohungarumlaut': 500,
  27808. 'Eogonek': 667,
  27809. 'dcroat': 500,
  27810. 'threequarters': 750,
  27811. 'Scedilla': 556,
  27812. 'lcaron': 382,
  27813. 'Kcommaaccent': 667,
  27814. 'Lacute': 611,
  27815. 'trademark': 1000,
  27816. 'edotaccent': 444,
  27817. 'Igrave': 389,
  27818. 'Imacron': 389,
  27819. 'Lcaron': 611,
  27820. 'onehalf': 750,
  27821. 'lessequal': 549,
  27822. 'ocircumflex': 500,
  27823. 'ntilde': 556,
  27824. 'Uhungarumlaut': 722,
  27825. 'Eacute': 667,
  27826. 'emacron': 444,
  27827. 'gbreve': 500,
  27828. 'onequarter': 750,
  27829. 'Scaron': 556,
  27830. 'Scommaaccent': 556,
  27831. 'Ohungarumlaut': 722,
  27832. 'degree': 400,
  27833. 'ograve': 500,
  27834. 'Ccaron': 667,
  27835. 'ugrave': 556,
  27836. 'radical': 549,
  27837. 'Dcaron': 722,
  27838. 'rcommaaccent': 389,
  27839. 'Ntilde': 722,
  27840. 'otilde': 500,
  27841. 'Rcommaaccent': 667,
  27842. 'Lcommaaccent': 611,
  27843. 'Atilde': 667,
  27844. 'Aogonek': 667,
  27845. 'Aring': 667,
  27846. 'Otilde': 722,
  27847. 'zdotaccent': 389,
  27848. 'Ecaron': 667,
  27849. 'Iogonek': 389,
  27850. 'kcommaaccent': 500,
  27851. 'minus': 606,
  27852. 'Icircumflex': 389,
  27853. 'ncaron': 556,
  27854. 'tcommaaccent': 278,
  27855. 'logicalnot': 606,
  27856. 'odieresis': 500,
  27857. 'udieresis': 556,
  27858. 'notequal': 549,
  27859. 'gcommaaccent': 500,
  27860. 'eth': 500,
  27861. 'zcaron': 389,
  27862. 'ncommaaccent': 556,
  27863. 'onesuperior': 300,
  27864. 'imacron': 278,
  27865. 'Euro': 500
  27866. },
  27867. 'Times-Italic': {
  27868. 'space': 250,
  27869. 'exclam': 333,
  27870. 'quotedbl': 420,
  27871. 'numbersign': 500,
  27872. 'dollar': 500,
  27873. 'percent': 833,
  27874. 'ampersand': 778,
  27875. 'quoteright': 333,
  27876. 'parenleft': 333,
  27877. 'parenright': 333,
  27878. 'asterisk': 500,
  27879. 'plus': 675,
  27880. 'comma': 250,
  27881. 'hyphen': 333,
  27882. 'period': 250,
  27883. 'slash': 278,
  27884. 'zero': 500,
  27885. 'one': 500,
  27886. 'two': 500,
  27887. 'three': 500,
  27888. 'four': 500,
  27889. 'five': 500,
  27890. 'six': 500,
  27891. 'seven': 500,
  27892. 'eight': 500,
  27893. 'nine': 500,
  27894. 'colon': 333,
  27895. 'semicolon': 333,
  27896. 'less': 675,
  27897. 'equal': 675,
  27898. 'greater': 675,
  27899. 'question': 500,
  27900. 'at': 920,
  27901. 'A': 611,
  27902. 'B': 611,
  27903. 'C': 667,
  27904. 'D': 722,
  27905. 'E': 611,
  27906. 'F': 611,
  27907. 'G': 722,
  27908. 'H': 722,
  27909. 'I': 333,
  27910. 'J': 444,
  27911. 'K': 667,
  27912. 'L': 556,
  27913. 'M': 833,
  27914. 'N': 667,
  27915. 'O': 722,
  27916. 'P': 611,
  27917. 'Q': 722,
  27918. 'R': 611,
  27919. 'S': 500,
  27920. 'T': 556,
  27921. 'U': 722,
  27922. 'V': 611,
  27923. 'W': 833,
  27924. 'X': 611,
  27925. 'Y': 556,
  27926. 'Z': 556,
  27927. 'bracketleft': 389,
  27928. 'backslash': 278,
  27929. 'bracketright': 389,
  27930. 'asciicircum': 422,
  27931. 'underscore': 500,
  27932. 'quoteleft': 333,
  27933. 'a': 500,
  27934. 'b': 500,
  27935. 'c': 444,
  27936. 'd': 500,
  27937. 'e': 444,
  27938. 'f': 278,
  27939. 'g': 500,
  27940. 'h': 500,
  27941. 'i': 278,
  27942. 'j': 278,
  27943. 'k': 444,
  27944. 'l': 278,
  27945. 'm': 722,
  27946. 'n': 500,
  27947. 'o': 500,
  27948. 'p': 500,
  27949. 'q': 500,
  27950. 'r': 389,
  27951. 's': 389,
  27952. 't': 278,
  27953. 'u': 500,
  27954. 'v': 444,
  27955. 'w': 667,
  27956. 'x': 444,
  27957. 'y': 444,
  27958. 'z': 389,
  27959. 'braceleft': 400,
  27960. 'bar': 275,
  27961. 'braceright': 400,
  27962. 'asciitilde': 541,
  27963. 'exclamdown': 389,
  27964. 'cent': 500,
  27965. 'sterling': 500,
  27966. 'fraction': 167,
  27967. 'yen': 500,
  27968. 'florin': 500,
  27969. 'section': 500,
  27970. 'currency': 500,
  27971. 'quotesingle': 214,
  27972. 'quotedblleft': 556,
  27973. 'guillemotleft': 500,
  27974. 'guilsinglleft': 333,
  27975. 'guilsinglright': 333,
  27976. 'fi': 500,
  27977. 'fl': 500,
  27978. 'endash': 500,
  27979. 'dagger': 500,
  27980. 'daggerdbl': 500,
  27981. 'periodcentered': 250,
  27982. 'paragraph': 523,
  27983. 'bullet': 350,
  27984. 'quotesinglbase': 333,
  27985. 'quotedblbase': 556,
  27986. 'quotedblright': 556,
  27987. 'guillemotright': 500,
  27988. 'ellipsis': 889,
  27989. 'perthousand': 1000,
  27990. 'questiondown': 500,
  27991. 'grave': 333,
  27992. 'acute': 333,
  27993. 'circumflex': 333,
  27994. 'tilde': 333,
  27995. 'macron': 333,
  27996. 'breve': 333,
  27997. 'dotaccent': 333,
  27998. 'dieresis': 333,
  27999. 'ring': 333,
  28000. 'cedilla': 333,
  28001. 'hungarumlaut': 333,
  28002. 'ogonek': 333,
  28003. 'caron': 333,
  28004. 'emdash': 889,
  28005. 'AE': 889,
  28006. 'ordfeminine': 276,
  28007. 'Lslash': 556,
  28008. 'Oslash': 722,
  28009. 'OE': 944,
  28010. 'ordmasculine': 310,
  28011. 'ae': 667,
  28012. 'dotlessi': 278,
  28013. 'lslash': 278,
  28014. 'oslash': 500,
  28015. 'oe': 667,
  28016. 'germandbls': 500,
  28017. 'Idieresis': 333,
  28018. 'eacute': 444,
  28019. 'abreve': 500,
  28020. 'uhungarumlaut': 500,
  28021. 'ecaron': 444,
  28022. 'Ydieresis': 556,
  28023. 'divide': 675,
  28024. 'Yacute': 556,
  28025. 'Acircumflex': 611,
  28026. 'aacute': 500,
  28027. 'Ucircumflex': 722,
  28028. 'yacute': 444,
  28029. 'scommaaccent': 389,
  28030. 'ecircumflex': 444,
  28031. 'Uring': 722,
  28032. 'Udieresis': 722,
  28033. 'aogonek': 500,
  28034. 'Uacute': 722,
  28035. 'uogonek': 500,
  28036. 'Edieresis': 611,
  28037. 'Dcroat': 722,
  28038. 'commaaccent': 250,
  28039. 'copyright': 760,
  28040. 'Emacron': 611,
  28041. 'ccaron': 444,
  28042. 'aring': 500,
  28043. 'Ncommaaccent': 667,
  28044. 'lacute': 278,
  28045. 'agrave': 500,
  28046. 'Tcommaaccent': 556,
  28047. 'Cacute': 667,
  28048. 'atilde': 500,
  28049. 'Edotaccent': 611,
  28050. 'scaron': 389,
  28051. 'scedilla': 389,
  28052. 'iacute': 278,
  28053. 'lozenge': 471,
  28054. 'Rcaron': 611,
  28055. 'Gcommaaccent': 722,
  28056. 'ucircumflex': 500,
  28057. 'acircumflex': 500,
  28058. 'Amacron': 611,
  28059. 'rcaron': 389,
  28060. 'ccedilla': 444,
  28061. 'Zdotaccent': 556,
  28062. 'Thorn': 611,
  28063. 'Omacron': 722,
  28064. 'Racute': 611,
  28065. 'Sacute': 500,
  28066. 'dcaron': 544,
  28067. 'Umacron': 722,
  28068. 'uring': 500,
  28069. 'threesuperior': 300,
  28070. 'Ograve': 722,
  28071. 'Agrave': 611,
  28072. 'Abreve': 611,
  28073. 'multiply': 675,
  28074. 'uacute': 500,
  28075. 'Tcaron': 556,
  28076. 'partialdiff': 476,
  28077. 'ydieresis': 444,
  28078. 'Nacute': 667,
  28079. 'icircumflex': 278,
  28080. 'Ecircumflex': 611,
  28081. 'adieresis': 500,
  28082. 'edieresis': 444,
  28083. 'cacute': 444,
  28084. 'nacute': 500,
  28085. 'umacron': 500,
  28086. 'Ncaron': 667,
  28087. 'Iacute': 333,
  28088. 'plusminus': 675,
  28089. 'brokenbar': 275,
  28090. 'registered': 760,
  28091. 'Gbreve': 722,
  28092. 'Idotaccent': 333,
  28093. 'summation': 600,
  28094. 'Egrave': 611,
  28095. 'racute': 389,
  28096. 'omacron': 500,
  28097. 'Zacute': 556,
  28098. 'Zcaron': 556,
  28099. 'greaterequal': 549,
  28100. 'Eth': 722,
  28101. 'Ccedilla': 667,
  28102. 'lcommaaccent': 278,
  28103. 'tcaron': 300,
  28104. 'eogonek': 444,
  28105. 'Uogonek': 722,
  28106. 'Aacute': 611,
  28107. 'Adieresis': 611,
  28108. 'egrave': 444,
  28109. 'zacute': 389,
  28110. 'iogonek': 278,
  28111. 'Oacute': 722,
  28112. 'oacute': 500,
  28113. 'amacron': 500,
  28114. 'sacute': 389,
  28115. 'idieresis': 278,
  28116. 'Ocircumflex': 722,
  28117. 'Ugrave': 722,
  28118. 'Delta': 612,
  28119. 'thorn': 500,
  28120. 'twosuperior': 300,
  28121. 'Odieresis': 722,
  28122. 'mu': 500,
  28123. 'igrave': 278,
  28124. 'ohungarumlaut': 500,
  28125. 'Eogonek': 611,
  28126. 'dcroat': 500,
  28127. 'threequarters': 750,
  28128. 'Scedilla': 500,
  28129. 'lcaron': 300,
  28130. 'Kcommaaccent': 667,
  28131. 'Lacute': 556,
  28132. 'trademark': 980,
  28133. 'edotaccent': 444,
  28134. 'Igrave': 333,
  28135. 'Imacron': 333,
  28136. 'Lcaron': 611,
  28137. 'onehalf': 750,
  28138. 'lessequal': 549,
  28139. 'ocircumflex': 500,
  28140. 'ntilde': 500,
  28141. 'Uhungarumlaut': 722,
  28142. 'Eacute': 611,
  28143. 'emacron': 444,
  28144. 'gbreve': 500,
  28145. 'onequarter': 750,
  28146. 'Scaron': 500,
  28147. 'Scommaaccent': 500,
  28148. 'Ohungarumlaut': 722,
  28149. 'degree': 400,
  28150. 'ograve': 500,
  28151. 'Ccaron': 667,
  28152. 'ugrave': 500,
  28153. 'radical': 453,
  28154. 'Dcaron': 722,
  28155. 'rcommaaccent': 389,
  28156. 'Ntilde': 667,
  28157. 'otilde': 500,
  28158. 'Rcommaaccent': 611,
  28159. 'Lcommaaccent': 556,
  28160. 'Atilde': 611,
  28161. 'Aogonek': 611,
  28162. 'Aring': 611,
  28163. 'Otilde': 722,
  28164. 'zdotaccent': 389,
  28165. 'Ecaron': 611,
  28166. 'Iogonek': 333,
  28167. 'kcommaaccent': 444,
  28168. 'minus': 675,
  28169. 'Icircumflex': 333,
  28170. 'ncaron': 500,
  28171. 'tcommaaccent': 278,
  28172. 'logicalnot': 675,
  28173. 'odieresis': 500,
  28174. 'udieresis': 500,
  28175. 'notequal': 549,
  28176. 'gcommaaccent': 500,
  28177. 'eth': 500,
  28178. 'zcaron': 389,
  28179. 'ncommaaccent': 500,
  28180. 'onesuperior': 300,
  28181. 'imacron': 278,
  28182. 'Euro': 500
  28183. },
  28184. 'ZapfDingbats': {
  28185. 'space': 278,
  28186. 'a1': 974,
  28187. 'a2': 961,
  28188. 'a202': 974,
  28189. 'a3': 980,
  28190. 'a4': 719,
  28191. 'a5': 789,
  28192. 'a119': 790,
  28193. 'a118': 791,
  28194. 'a117': 690,
  28195. 'a11': 960,
  28196. 'a12': 939,
  28197. 'a13': 549,
  28198. 'a14': 855,
  28199. 'a15': 911,
  28200. 'a16': 933,
  28201. 'a105': 911,
  28202. 'a17': 945,
  28203. 'a18': 974,
  28204. 'a19': 755,
  28205. 'a20': 846,
  28206. 'a21': 762,
  28207. 'a22': 761,
  28208. 'a23': 571,
  28209. 'a24': 677,
  28210. 'a25': 763,
  28211. 'a26': 760,
  28212. 'a27': 759,
  28213. 'a28': 754,
  28214. 'a6': 494,
  28215. 'a7': 552,
  28216. 'a8': 537,
  28217. 'a9': 577,
  28218. 'a10': 692,
  28219. 'a29': 786,
  28220. 'a30': 788,
  28221. 'a31': 788,
  28222. 'a32': 790,
  28223. 'a33': 793,
  28224. 'a34': 794,
  28225. 'a35': 816,
  28226. 'a36': 823,
  28227. 'a37': 789,
  28228. 'a38': 841,
  28229. 'a39': 823,
  28230. 'a40': 833,
  28231. 'a41': 816,
  28232. 'a42': 831,
  28233. 'a43': 923,
  28234. 'a44': 744,
  28235. 'a45': 723,
  28236. 'a46': 749,
  28237. 'a47': 790,
  28238. 'a48': 792,
  28239. 'a49': 695,
  28240. 'a50': 776,
  28241. 'a51': 768,
  28242. 'a52': 792,
  28243. 'a53': 759,
  28244. 'a54': 707,
  28245. 'a55': 708,
  28246. 'a56': 682,
  28247. 'a57': 701,
  28248. 'a58': 826,
  28249. 'a59': 815,
  28250. 'a60': 789,
  28251. 'a61': 789,
  28252. 'a62': 707,
  28253. 'a63': 687,
  28254. 'a64': 696,
  28255. 'a65': 689,
  28256. 'a66': 786,
  28257. 'a67': 787,
  28258. 'a68': 713,
  28259. 'a69': 791,
  28260. 'a70': 785,
  28261. 'a71': 791,
  28262. 'a72': 873,
  28263. 'a73': 761,
  28264. 'a74': 762,
  28265. 'a203': 762,
  28266. 'a75': 759,
  28267. 'a204': 759,
  28268. 'a76': 892,
  28269. 'a77': 892,
  28270. 'a78': 788,
  28271. 'a79': 784,
  28272. 'a81': 438,
  28273. 'a82': 138,
  28274. 'a83': 277,
  28275. 'a84': 415,
  28276. 'a97': 392,
  28277. 'a98': 392,
  28278. 'a99': 668,
  28279. 'a100': 668,
  28280. 'a89': 390,
  28281. 'a90': 390,
  28282. 'a93': 317,
  28283. 'a94': 317,
  28284. 'a91': 276,
  28285. 'a92': 276,
  28286. 'a205': 509,
  28287. 'a85': 509,
  28288. 'a206': 410,
  28289. 'a86': 410,
  28290. 'a87': 234,
  28291. 'a88': 234,
  28292. 'a95': 334,
  28293. 'a96': 334,
  28294. 'a101': 732,
  28295. 'a102': 544,
  28296. 'a103': 544,
  28297. 'a104': 910,
  28298. 'a106': 667,
  28299. 'a107': 760,
  28300. 'a108': 760,
  28301. 'a112': 776,
  28302. 'a111': 595,
  28303. 'a110': 694,
  28304. 'a109': 626,
  28305. 'a120': 788,
  28306. 'a121': 788,
  28307. 'a122': 788,
  28308. 'a123': 788,
  28309. 'a124': 788,
  28310. 'a125': 788,
  28311. 'a126': 788,
  28312. 'a127': 788,
  28313. 'a128': 788,
  28314. 'a129': 788,
  28315. 'a130': 788,
  28316. 'a131': 788,
  28317. 'a132': 788,
  28318. 'a133': 788,
  28319. 'a134': 788,
  28320. 'a135': 788,
  28321. 'a136': 788,
  28322. 'a137': 788,
  28323. 'a138': 788,
  28324. 'a139': 788,
  28325. 'a140': 788,
  28326. 'a141': 788,
  28327. 'a142': 788,
  28328. 'a143': 788,
  28329. 'a144': 788,
  28330. 'a145': 788,
  28331. 'a146': 788,
  28332. 'a147': 788,
  28333. 'a148': 788,
  28334. 'a149': 788,
  28335. 'a150': 788,
  28336. 'a151': 788,
  28337. 'a152': 788,
  28338. 'a153': 788,
  28339. 'a154': 788,
  28340. 'a155': 788,
  28341. 'a156': 788,
  28342. 'a157': 788,
  28343. 'a158': 788,
  28344. 'a159': 788,
  28345. 'a160': 894,
  28346. 'a161': 838,
  28347. 'a163': 1016,
  28348. 'a164': 458,
  28349. 'a196': 748,
  28350. 'a165': 924,
  28351. 'a192': 748,
  28352. 'a166': 918,
  28353. 'a167': 927,
  28354. 'a168': 928,
  28355. 'a169': 928,
  28356. 'a170': 834,
  28357. 'a171': 873,
  28358. 'a172': 828,
  28359. 'a173': 924,
  28360. 'a162': 924,
  28361. 'a174': 917,
  28362. 'a175': 930,
  28363. 'a176': 931,
  28364. 'a177': 463,
  28365. 'a178': 883,
  28366. 'a179': 836,
  28367. 'a193': 836,
  28368. 'a180': 867,
  28369. 'a199': 867,
  28370. 'a181': 696,
  28371. 'a200': 696,
  28372. 'a182': 874,
  28373. 'a201': 874,
  28374. 'a183': 760,
  28375. 'a184': 946,
  28376. 'a197': 771,
  28377. 'a185': 865,
  28378. 'a194': 771,
  28379. 'a198': 888,
  28380. 'a186': 967,
  28381. 'a195': 888,
  28382. 'a187': 831,
  28383. 'a188': 873,
  28384. 'a189': 927,
  28385. 'a190': 970,
  28386. 'a191': 918
  28387. }
  28388. };
  28389. var EOF = {};
  28390. function isEOF(v) {
  28391. return (v === EOF);
  28392. }
  28393. var MAX_LENGTH_TO_CACHE = 1000;
  28394. var Parser = (function ParserClosure() {
  28395. function Parser(lexer, allowStreams, xref) {
  28396. this.lexer = lexer;
  28397. this.allowStreams = allowStreams;
  28398. this.xref = xref;
  28399. this.imageCache = {};
  28400. this.refill();
  28401. }
  28402. Parser.prototype = {
  28403. refill: function Parser_refill() {
  28404. this.buf1 = this.lexer.getObj();
  28405. this.buf2 = this.lexer.getObj();
  28406. },
  28407. shift: function Parser_shift() {
  28408. if (isCmd(this.buf2, 'ID')) {
  28409. this.buf1 = this.buf2;
  28410. this.buf2 = null;
  28411. } else {
  28412. this.buf1 = this.buf2;
  28413. this.buf2 = this.lexer.getObj();
  28414. }
  28415. },
  28416. getObj: function Parser_getObj(cipherTransform) {
  28417. var buf1 = this.buf1;
  28418. this.shift();
  28419. if (buf1 instanceof Cmd) {
  28420. switch (buf1.cmd) {
  28421. case 'BI': // inline image
  28422. return this.makeInlineImage(cipherTransform);
  28423. case '[': // array
  28424. var array = [];
  28425. while (!isCmd(this.buf1, ']') && !isEOF(this.buf1)) {
  28426. array.push(this.getObj(cipherTransform));
  28427. }
  28428. if (isEOF(this.buf1)) {
  28429. error('End of file inside array');
  28430. }
  28431. this.shift();
  28432. return array;
  28433. case '<<': // dictionary or stream
  28434. var dict = new Dict(this.xref);
  28435. while (!isCmd(this.buf1, '>>') && !isEOF(this.buf1)) {
  28436. if (!isName(this.buf1)) {
  28437. info('Malformed dictionary: key must be a name object');
  28438. this.shift();
  28439. continue;
  28440. }
  28441. var key = this.buf1.name;
  28442. this.shift();
  28443. if (isEOF(this.buf1)) {
  28444. break;
  28445. }
  28446. dict.set(key, this.getObj(cipherTransform));
  28447. }
  28448. if (isEOF(this.buf1)) {
  28449. error('End of file inside dictionary');
  28450. }
  28451. // Stream objects are not allowed inside content streams or
  28452. // object streams.
  28453. if (isCmd(this.buf2, 'stream')) {
  28454. return (this.allowStreams ?
  28455. this.makeStream(dict, cipherTransform) : dict);
  28456. }
  28457. this.shift();
  28458. return dict;
  28459. default: // simple object
  28460. return buf1;
  28461. }
  28462. }
  28463. if (isInt(buf1)) { // indirect reference or integer
  28464. var num = buf1;
  28465. if (isInt(this.buf1) && isCmd(this.buf2, 'R')) {
  28466. var ref = new Ref(num, this.buf1);
  28467. this.shift();
  28468. this.shift();
  28469. return ref;
  28470. }
  28471. return num;
  28472. }
  28473. if (isString(buf1)) { // string
  28474. var str = buf1;
  28475. if (cipherTransform) {
  28476. str = cipherTransform.decryptString(str);
  28477. }
  28478. return str;
  28479. }
  28480. // simple object
  28481. return buf1;
  28482. },
  28483. /**
  28484. * Find the end of the stream by searching for the /EI\s/.
  28485. * @returns {number} The inline stream length.
  28486. */
  28487. findDefaultInlineStreamEnd:
  28488. function Parser_findDefaultInlineStreamEnd(stream) {
  28489. var E = 0x45, I = 0x49, SPACE = 0x20, LF = 0xA, CR = 0xD;
  28490. var startPos = stream.pos, state = 0, ch, i, n, followingBytes;
  28491. while ((ch = stream.getByte()) !== -1) {
  28492. if (state === 0) {
  28493. state = (ch === E) ? 1 : 0;
  28494. } else if (state === 1) {
  28495. state = (ch === I) ? 2 : 0;
  28496. } else {
  28497. assert(state === 2);
  28498. if (ch === SPACE || ch === LF || ch === CR) {
  28499. // Let's check the next five bytes are ASCII... just be sure.
  28500. n = 5;
  28501. followingBytes = stream.peekBytes(n);
  28502. for (i = 0; i < n; i++) {
  28503. ch = followingBytes[i];
  28504. if (ch !== LF && ch !== CR && (ch < SPACE || ch > 0x7F)) {
  28505. // Not a LF, CR, SPACE or any visible ASCII character, i.e.
  28506. // it's binary stuff. Resetting the state.
  28507. state = 0;
  28508. break;
  28509. }
  28510. }
  28511. if (state === 2) {
  28512. break; // Finished!
  28513. }
  28514. } else {
  28515. state = 0;
  28516. }
  28517. }
  28518. }
  28519. return ((stream.pos - 4) - startPos);
  28520. },
  28521. /**
  28522. * Find the EOI (end-of-image) marker 0xFFD9 of the stream.
  28523. * @returns {number} The inline stream length.
  28524. */
  28525. findDCTDecodeInlineStreamEnd:
  28526. function Parser_findDCTDecodeInlineStreamEnd(stream) {
  28527. var startPos = stream.pos, foundEOI = false, b, markerLength, length;
  28528. while ((b = stream.getByte()) !== -1) {
  28529. if (b !== 0xFF) { // Not a valid marker.
  28530. continue;
  28531. }
  28532. switch (stream.getByte()) {
  28533. case 0x00: // Byte stuffing.
  28534. // 0xFF00 appears to be a very common byte sequence in JPEG images.
  28535. break;
  28536. case 0xFF: // Fill byte.
  28537. // Avoid skipping a valid marker, resetting the stream position.
  28538. stream.skip(-1);
  28539. break;
  28540. case 0xD9: // EOI
  28541. foundEOI = true;
  28542. break;
  28543. case 0xC0: // SOF0
  28544. case 0xC1: // SOF1
  28545. case 0xC2: // SOF2
  28546. case 0xC3: // SOF3
  28547. case 0xC5: // SOF5
  28548. case 0xC6: // SOF6
  28549. case 0xC7: // SOF7
  28550. case 0xC9: // SOF9
  28551. case 0xCA: // SOF10
  28552. case 0xCB: // SOF11
  28553. case 0xCD: // SOF13
  28554. case 0xCE: // SOF14
  28555. case 0xCF: // SOF15
  28556. case 0xC4: // DHT
  28557. case 0xCC: // DAC
  28558. case 0xDA: // SOS
  28559. case 0xDB: // DQT
  28560. case 0xDC: // DNL
  28561. case 0xDD: // DRI
  28562. case 0xDE: // DHP
  28563. case 0xDF: // EXP
  28564. case 0xE0: // APP0
  28565. case 0xE1: // APP1
  28566. case 0xE2: // APP2
  28567. case 0xE3: // APP3
  28568. case 0xE4: // APP4
  28569. case 0xE5: // APP5
  28570. case 0xE6: // APP6
  28571. case 0xE7: // APP7
  28572. case 0xE8: // APP8
  28573. case 0xE9: // APP9
  28574. case 0xEA: // APP10
  28575. case 0xEB: // APP11
  28576. case 0xEC: // APP12
  28577. case 0xED: // APP13
  28578. case 0xEE: // APP14
  28579. case 0xEF: // APP15
  28580. case 0xFE: // COM
  28581. // The marker should be followed by the length of the segment.
  28582. markerLength = stream.getUint16();
  28583. if (markerLength > 2) {
  28584. // |markerLength| contains the byte length of the marker segment,
  28585. // including its own length (2 bytes) and excluding the marker.
  28586. stream.skip(markerLength - 2); // Jump to the next marker.
  28587. } else {
  28588. // The marker length is invalid, resetting the stream position.
  28589. stream.skip(-2);
  28590. }
  28591. break;
  28592. }
  28593. if (foundEOI) {
  28594. break;
  28595. }
  28596. }
  28597. length = stream.pos - startPos;
  28598. if (b === -1) {
  28599. warn('Inline DCTDecode image stream: ' +
  28600. 'EOI marker not found, searching for /EI/ instead.');
  28601. stream.skip(-length); // Reset the stream position.
  28602. return this.findDefaultInlineStreamEnd(stream);
  28603. }
  28604. this.inlineStreamSkipEI(stream);
  28605. return length;
  28606. },
  28607. /**
  28608. * Find the EOD (end-of-data) marker '~>' (i.e. TILDE + GT) of the stream.
  28609. * @returns {number} The inline stream length.
  28610. */
  28611. findASCII85DecodeInlineStreamEnd:
  28612. function Parser_findASCII85DecodeInlineStreamEnd(stream) {
  28613. var TILDE = 0x7E, GT = 0x3E;
  28614. var startPos = stream.pos, ch, length;
  28615. while ((ch = stream.getByte()) !== -1) {
  28616. if (ch === TILDE && stream.peekByte() === GT) {
  28617. stream.skip();
  28618. break;
  28619. }
  28620. }
  28621. length = stream.pos - startPos;
  28622. if (ch === -1) {
  28623. warn('Inline ASCII85Decode image stream: ' +
  28624. 'EOD marker not found, searching for /EI/ instead.');
  28625. stream.skip(-length); // Reset the stream position.
  28626. return this.findDefaultInlineStreamEnd(stream);
  28627. }
  28628. this.inlineStreamSkipEI(stream);
  28629. return length;
  28630. },
  28631. /**
  28632. * Find the EOD (end-of-data) marker '>' (i.e. GT) of the stream.
  28633. * @returns {number} The inline stream length.
  28634. */
  28635. findASCIIHexDecodeInlineStreamEnd:
  28636. function Parser_findASCIIHexDecodeInlineStreamEnd(stream) {
  28637. var GT = 0x3E;
  28638. var startPos = stream.pos, ch, length;
  28639. while ((ch = stream.getByte()) !== -1) {
  28640. if (ch === GT) {
  28641. break;
  28642. }
  28643. }
  28644. length = stream.pos - startPos;
  28645. if (ch === -1) {
  28646. warn('Inline ASCIIHexDecode image stream: ' +
  28647. 'EOD marker not found, searching for /EI/ instead.');
  28648. stream.skip(-length); // Reset the stream position.
  28649. return this.findDefaultInlineStreamEnd(stream);
  28650. }
  28651. this.inlineStreamSkipEI(stream);
  28652. return length;
  28653. },
  28654. /**
  28655. * Skip over the /EI/ for streams where we search for an EOD marker.
  28656. */
  28657. inlineStreamSkipEI: function Parser_inlineStreamSkipEI(stream) {
  28658. var E = 0x45, I = 0x49;
  28659. var state = 0, ch;
  28660. while ((ch = stream.getByte()) !== -1) {
  28661. if (state === 0) {
  28662. state = (ch === E) ? 1 : 0;
  28663. } else if (state === 1) {
  28664. state = (ch === I) ? 2 : 0;
  28665. } else if (state === 2) {
  28666. break;
  28667. }
  28668. }
  28669. },
  28670. makeInlineImage: function Parser_makeInlineImage(cipherTransform) {
  28671. var lexer = this.lexer;
  28672. var stream = lexer.stream;
  28673. // Parse dictionary.
  28674. var dict = new Dict(null);
  28675. while (!isCmd(this.buf1, 'ID') && !isEOF(this.buf1)) {
  28676. if (!isName(this.buf1)) {
  28677. error('Dictionary key must be a name object');
  28678. }
  28679. var key = this.buf1.name;
  28680. this.shift();
  28681. if (isEOF(this.buf1)) {
  28682. break;
  28683. }
  28684. dict.set(key, this.getObj(cipherTransform));
  28685. }
  28686. // Extract the name of the first (i.e. the current) image filter.
  28687. var filter = this.fetchIfRef(dict.get('Filter', 'F')), filterName;
  28688. if (isName(filter)) {
  28689. filterName = filter.name;
  28690. } else if (isArray(filter) && isName(filter[0])) {
  28691. filterName = filter[0].name;
  28692. }
  28693. // Parse image stream.
  28694. var startPos = stream.pos, length, i, ii;
  28695. if (filterName === 'DCTDecode' || filterName === 'DCT') {
  28696. length = this.findDCTDecodeInlineStreamEnd(stream);
  28697. } else if (filterName === 'ASCII85Decide' || filterName === 'A85') {
  28698. length = this.findASCII85DecodeInlineStreamEnd(stream);
  28699. } else if (filterName === 'ASCIIHexDecode' || filterName === 'AHx') {
  28700. length = this.findASCIIHexDecodeInlineStreamEnd(stream);
  28701. } else {
  28702. length = this.findDefaultInlineStreamEnd(stream);
  28703. }
  28704. var imageStream = stream.makeSubStream(startPos, length, dict);
  28705. // Cache all images below the MAX_LENGTH_TO_CACHE threshold by their
  28706. // adler32 checksum.
  28707. var adler32;
  28708. if (length < MAX_LENGTH_TO_CACHE) {
  28709. var imageBytes = imageStream.getBytes();
  28710. imageStream.reset();
  28711. var a = 1;
  28712. var b = 0;
  28713. for (i = 0, ii = imageBytes.length; i < ii; ++i) {
  28714. // No modulo required in the loop if imageBytes.length < 5552.
  28715. a += imageBytes[i] & 0xff;
  28716. b += a;
  28717. }
  28718. adler32 = ((b % 65521) << 16) | (a % 65521);
  28719. if (this.imageCache.adler32 === adler32) {
  28720. this.buf2 = Cmd.get('EI');
  28721. this.shift();
  28722. this.imageCache[adler32].reset();
  28723. return this.imageCache[adler32];
  28724. }
  28725. }
  28726. if (cipherTransform) {
  28727. imageStream = cipherTransform.createStream(imageStream, length);
  28728. }
  28729. imageStream = this.filter(imageStream, dict, length);
  28730. imageStream.dict = dict;
  28731. if (adler32 !== undefined) {
  28732. imageStream.cacheKey = 'inline_' + length + '_' + adler32;
  28733. this.imageCache[adler32] = imageStream;
  28734. }
  28735. this.buf2 = Cmd.get('EI');
  28736. this.shift();
  28737. return imageStream;
  28738. },
  28739. fetchIfRef: function Parser_fetchIfRef(obj) {
  28740. // not relying on the xref.fetchIfRef -- xref might not be set
  28741. return (isRef(obj) ? this.xref.fetch(obj) : obj);
  28742. },
  28743. makeStream: function Parser_makeStream(dict, cipherTransform) {
  28744. var lexer = this.lexer;
  28745. var stream = lexer.stream;
  28746. // get stream start position
  28747. lexer.skipToNextLine();
  28748. var pos = stream.pos - 1;
  28749. // get length
  28750. var length = this.fetchIfRef(dict.get('Length'));
  28751. if (!isInt(length)) {
  28752. info('Bad ' + length + ' attribute in stream');
  28753. length = 0;
  28754. }
  28755. // skip over the stream data
  28756. stream.pos = pos + length;
  28757. lexer.nextChar();
  28758. this.shift(); // '>>'
  28759. this.shift(); // 'stream'
  28760. if (!isCmd(this.buf1, 'endstream')) {
  28761. // bad stream length, scanning for endstream
  28762. stream.pos = pos;
  28763. var SCAN_BLOCK_SIZE = 2048;
  28764. var ENDSTREAM_SIGNATURE_LENGTH = 9;
  28765. var ENDSTREAM_SIGNATURE = [0x65, 0x6E, 0x64, 0x73, 0x74, 0x72, 0x65,
  28766. 0x61, 0x6D];
  28767. var skipped = 0, found = false, i, j;
  28768. while (stream.pos < stream.end) {
  28769. var scanBytes = stream.peekBytes(SCAN_BLOCK_SIZE);
  28770. var scanLength = scanBytes.length - ENDSTREAM_SIGNATURE_LENGTH;
  28771. if (scanLength <= 0) {
  28772. break;
  28773. }
  28774. found = false;
  28775. for (i = 0, j = 0; i < scanLength; i++) {
  28776. var b = scanBytes[i];
  28777. if (b !== ENDSTREAM_SIGNATURE[j]) {
  28778. i -= j;
  28779. j = 0;
  28780. } else {
  28781. j++;
  28782. if (j >= ENDSTREAM_SIGNATURE_LENGTH) {
  28783. i++;
  28784. found = true;
  28785. break;
  28786. }
  28787. }
  28788. }
  28789. if (found) {
  28790. skipped += i - ENDSTREAM_SIGNATURE_LENGTH;
  28791. stream.pos += i - ENDSTREAM_SIGNATURE_LENGTH;
  28792. break;
  28793. }
  28794. skipped += scanLength;
  28795. stream.pos += scanLength;
  28796. }
  28797. if (!found) {
  28798. error('Missing endstream');
  28799. }
  28800. length = skipped;
  28801. lexer.nextChar();
  28802. this.shift();
  28803. this.shift();
  28804. }
  28805. this.shift(); // 'endstream'
  28806. stream = stream.makeSubStream(pos, length, dict);
  28807. if (cipherTransform) {
  28808. stream = cipherTransform.createStream(stream, length);
  28809. }
  28810. stream = this.filter(stream, dict, length);
  28811. stream.dict = dict;
  28812. return stream;
  28813. },
  28814. filter: function Parser_filter(stream, dict, length) {
  28815. var filter = this.fetchIfRef(dict.get('Filter', 'F'));
  28816. var params = this.fetchIfRef(dict.get('DecodeParms', 'DP'));
  28817. if (isName(filter)) {
  28818. return this.makeFilter(stream, filter.name, length, params);
  28819. }
  28820. var maybeLength = length;
  28821. if (isArray(filter)) {
  28822. var filterArray = filter;
  28823. var paramsArray = params;
  28824. for (var i = 0, ii = filterArray.length; i < ii; ++i) {
  28825. filter = filterArray[i];
  28826. if (!isName(filter)) {
  28827. error('Bad filter name: ' + filter);
  28828. }
  28829. params = null;
  28830. if (isArray(paramsArray) && (i in paramsArray)) {
  28831. params = paramsArray[i];
  28832. }
  28833. stream = this.makeFilter(stream, filter.name, maybeLength, params);
  28834. // after the first stream the length variable is invalid
  28835. maybeLength = null;
  28836. }
  28837. }
  28838. return stream;
  28839. },
  28840. makeFilter: function Parser_makeFilter(stream, name, maybeLength, params) {
  28841. if (stream.dict.get('Length') === 0) {
  28842. return new NullStream(stream);
  28843. }
  28844. try {
  28845. if (params) {
  28846. params = this.fetchIfRef(params);
  28847. }
  28848. var xrefStreamStats = this.xref.stats.streamTypes;
  28849. if (name === 'FlateDecode' || name === 'Fl') {
  28850. xrefStreamStats[StreamType.FLATE] = true;
  28851. if (params) {
  28852. return new PredictorStream(new FlateStream(stream, maybeLength),
  28853. maybeLength, params);
  28854. }
  28855. return new FlateStream(stream, maybeLength);
  28856. }
  28857. if (name === 'LZWDecode' || name === 'LZW') {
  28858. xrefStreamStats[StreamType.LZW] = true;
  28859. var earlyChange = 1;
  28860. if (params) {
  28861. if (params.has('EarlyChange')) {
  28862. earlyChange = params.get('EarlyChange');
  28863. }
  28864. return new PredictorStream(
  28865. new LZWStream(stream, maybeLength, earlyChange),
  28866. maybeLength, params);
  28867. }
  28868. return new LZWStream(stream, maybeLength, earlyChange);
  28869. }
  28870. if (name === 'DCTDecode' || name === 'DCT') {
  28871. xrefStreamStats[StreamType.DCT] = true;
  28872. return new JpegStream(stream, maybeLength, stream.dict, this.xref);
  28873. }
  28874. if (name === 'JPXDecode' || name === 'JPX') {
  28875. xrefStreamStats[StreamType.JPX] = true;
  28876. return new JpxStream(stream, maybeLength, stream.dict);
  28877. }
  28878. if (name === 'ASCII85Decode' || name === 'A85') {
  28879. xrefStreamStats[StreamType.A85] = true;
  28880. return new Ascii85Stream(stream, maybeLength);
  28881. }
  28882. if (name === 'ASCIIHexDecode' || name === 'AHx') {
  28883. xrefStreamStats[StreamType.AHX] = true;
  28884. return new AsciiHexStream(stream, maybeLength);
  28885. }
  28886. if (name === 'CCITTFaxDecode' || name === 'CCF') {
  28887. xrefStreamStats[StreamType.CCF] = true;
  28888. return new CCITTFaxStream(stream, maybeLength, params);
  28889. }
  28890. if (name === 'RunLengthDecode' || name === 'RL') {
  28891. xrefStreamStats[StreamType.RL] = true;
  28892. return new RunLengthStream(stream, maybeLength);
  28893. }
  28894. if (name === 'JBIG2Decode') {
  28895. xrefStreamStats[StreamType.JBIG] = true;
  28896. return new Jbig2Stream(stream, maybeLength, stream.dict);
  28897. }
  28898. warn('filter "' + name + '" not supported yet');
  28899. return stream;
  28900. } catch (ex) {
  28901. if (ex instanceof MissingDataException) {
  28902. throw ex;
  28903. }
  28904. warn('Invalid stream: \"' + ex + '\"');
  28905. return new NullStream(stream);
  28906. }
  28907. }
  28908. };
  28909. return Parser;
  28910. })();
  28911. var Lexer = (function LexerClosure() {
  28912. function Lexer(stream, knownCommands) {
  28913. this.stream = stream;
  28914. this.nextChar();
  28915. // While lexing, we build up many strings one char at a time. Using += for
  28916. // this can result in lots of garbage strings. It's better to build an
  28917. // array of single-char strings and then join() them together at the end.
  28918. // And reusing a single array (i.e. |this.strBuf|) over and over for this
  28919. // purpose uses less memory than using a new array for each string.
  28920. this.strBuf = [];
  28921. // The PDFs might have "glued" commands with other commands, operands or
  28922. // literals, e.g. "q1". The knownCommands is a dictionary of the valid
  28923. // commands and their prefixes. The prefixes are built the following way:
  28924. // if there a command that is a prefix of the other valid command or
  28925. // literal (e.g. 'f' and 'false') the following prefixes must be included,
  28926. // 'fa', 'fal', 'fals'. The prefixes are not needed, if the command has no
  28927. // other commands or literals as a prefix. The knowCommands is optional.
  28928. this.knownCommands = knownCommands;
  28929. }
  28930. Lexer.isSpace = function Lexer_isSpace(ch) {
  28931. // Space is one of the following characters: SPACE, TAB, CR or LF.
  28932. return (ch === 0x20 || ch === 0x09 || ch === 0x0D || ch === 0x0A);
  28933. };
  28934. // A '1' in this array means the character is white space. A '1' or
  28935. // '2' means the character ends a name or command.
  28936. var specialChars = [
  28937. 1, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 1, 1, 0, 0, // 0x
  28938. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // 1x
  28939. 1, 0, 0, 0, 0, 2, 0, 0, 2, 2, 0, 0, 0, 0, 0, 2, // 2x
  28940. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 2, 0, 2, 0, // 3x
  28941. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // 4x
  28942. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 2, 0, 2, 0, 0, // 5x
  28943. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // 6x
  28944. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 2, 0, 2, 0, 0, // 7x
  28945. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // 8x
  28946. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // 9x
  28947. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // ax
  28948. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // bx
  28949. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // cx
  28950. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // dx
  28951. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // ex
  28952. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 // fx
  28953. ];
  28954. function toHexDigit(ch) {
  28955. if (ch >= 0x30 && ch <= 0x39) { // '0'-'9'
  28956. return ch & 0x0F;
  28957. }
  28958. if ((ch >= 0x41 && ch <= 0x46) || (ch >= 0x61 && ch <= 0x66)) {
  28959. // 'A'-'F', 'a'-'f'
  28960. return (ch & 0x0F) + 9;
  28961. }
  28962. return -1;
  28963. }
  28964. Lexer.prototype = {
  28965. nextChar: function Lexer_nextChar() {
  28966. return (this.currentChar = this.stream.getByte());
  28967. },
  28968. peekChar: function Lexer_peekChar() {
  28969. return this.stream.peekByte();
  28970. },
  28971. getNumber: function Lexer_getNumber() {
  28972. var ch = this.currentChar;
  28973. var eNotation = false;
  28974. var divideBy = 0; // different from 0 if it's a floating point value
  28975. var sign = 1;
  28976. if (ch === 0x2D) { // '-'
  28977. sign = -1;
  28978. ch = this.nextChar();
  28979. } else if (ch === 0x2B) { // '+'
  28980. ch = this.nextChar();
  28981. }
  28982. if (ch === 0x2E) { // '.'
  28983. divideBy = 10;
  28984. ch = this.nextChar();
  28985. }
  28986. if (ch < 0x30 || ch > 0x39) { // '0' - '9'
  28987. error('Invalid number: ' + String.fromCharCode(ch));
  28988. return 0;
  28989. }
  28990. var baseValue = ch - 0x30; // '0'
  28991. var powerValue = 0;
  28992. var powerValueSign = 1;
  28993. while ((ch = this.nextChar()) >= 0) {
  28994. if (0x30 <= ch && ch <= 0x39) { // '0' - '9'
  28995. var currentDigit = ch - 0x30; // '0'
  28996. if (eNotation) { // We are after an 'e' or 'E'
  28997. powerValue = powerValue * 10 + currentDigit;
  28998. } else {
  28999. if (divideBy !== 0) { // We are after a point
  29000. divideBy *= 10;
  29001. }
  29002. baseValue = baseValue * 10 + currentDigit;
  29003. }
  29004. } else if (ch === 0x2E) { // '.'
  29005. if (divideBy === 0) {
  29006. divideBy = 1;
  29007. } else {
  29008. // A number can have only one '.'
  29009. break;
  29010. }
  29011. } else if (ch === 0x2D) { // '-'
  29012. // ignore minus signs in the middle of numbers to match
  29013. // Adobe's behavior
  29014. warn('Badly formated number');
  29015. } else if (ch === 0x45 || ch === 0x65) { // 'E', 'e'
  29016. // 'E' can be either a scientific notation or the beginning of a new
  29017. // operator
  29018. ch = this.peekChar();
  29019. if (ch === 0x2B || ch === 0x2D) { // '+', '-'
  29020. powerValueSign = (ch === 0x2D) ? -1 : 1;
  29021. this.nextChar(); // Consume the sign character
  29022. } else if (ch < 0x30 || ch > 0x39) { // '0' - '9'
  29023. // The 'E' must be the beginning of a new operator
  29024. break;
  29025. }
  29026. eNotation = true;
  29027. } else {
  29028. // the last character doesn't belong to us
  29029. break;
  29030. }
  29031. }
  29032. if (divideBy !== 0) {
  29033. baseValue /= divideBy;
  29034. }
  29035. if (eNotation) {
  29036. baseValue *= Math.pow(10, powerValueSign * powerValue);
  29037. }
  29038. return sign * baseValue;
  29039. },
  29040. getString: function Lexer_getString() {
  29041. var numParen = 1;
  29042. var done = false;
  29043. var strBuf = this.strBuf;
  29044. strBuf.length = 0;
  29045. var ch = this.nextChar();
  29046. while (true) {
  29047. var charBuffered = false;
  29048. switch (ch | 0) {
  29049. case -1:
  29050. warn('Unterminated string');
  29051. done = true;
  29052. break;
  29053. case 0x28: // '('
  29054. ++numParen;
  29055. strBuf.push('(');
  29056. break;
  29057. case 0x29: // ')'
  29058. if (--numParen === 0) {
  29059. this.nextChar(); // consume strings ')'
  29060. done = true;
  29061. } else {
  29062. strBuf.push(')');
  29063. }
  29064. break;
  29065. case 0x5C: // '\\'
  29066. ch = this.nextChar();
  29067. switch (ch) {
  29068. case -1:
  29069. warn('Unterminated string');
  29070. done = true;
  29071. break;
  29072. case 0x6E: // 'n'
  29073. strBuf.push('\n');
  29074. break;
  29075. case 0x72: // 'r'
  29076. strBuf.push('\r');
  29077. break;
  29078. case 0x74: // 't'
  29079. strBuf.push('\t');
  29080. break;
  29081. case 0x62: // 'b'
  29082. strBuf.push('\b');
  29083. break;
  29084. case 0x66: // 'f'
  29085. strBuf.push('\f');
  29086. break;
  29087. case 0x5C: // '\'
  29088. case 0x28: // '('
  29089. case 0x29: // ')'
  29090. strBuf.push(String.fromCharCode(ch));
  29091. break;
  29092. case 0x30: case 0x31: case 0x32: case 0x33: // '0'-'3'
  29093. case 0x34: case 0x35: case 0x36: case 0x37: // '4'-'7'
  29094. var x = ch & 0x0F;
  29095. ch = this.nextChar();
  29096. charBuffered = true;
  29097. if (ch >= 0x30 && ch <= 0x37) { // '0'-'7'
  29098. x = (x << 3) + (ch & 0x0F);
  29099. ch = this.nextChar();
  29100. if (ch >= 0x30 && ch <= 0x37) { // '0'-'7'
  29101. charBuffered = false;
  29102. x = (x << 3) + (ch & 0x0F);
  29103. }
  29104. }
  29105. strBuf.push(String.fromCharCode(x));
  29106. break;
  29107. case 0x0D: // CR
  29108. if (this.peekChar() === 0x0A) { // LF
  29109. this.nextChar();
  29110. }
  29111. break;
  29112. case 0x0A: // LF
  29113. break;
  29114. default:
  29115. strBuf.push(String.fromCharCode(ch));
  29116. break;
  29117. }
  29118. break;
  29119. default:
  29120. strBuf.push(String.fromCharCode(ch));
  29121. break;
  29122. }
  29123. if (done) {
  29124. break;
  29125. }
  29126. if (!charBuffered) {
  29127. ch = this.nextChar();
  29128. }
  29129. }
  29130. return strBuf.join('');
  29131. },
  29132. getName: function Lexer_getName() {
  29133. var ch;
  29134. var strBuf = this.strBuf;
  29135. strBuf.length = 0;
  29136. while ((ch = this.nextChar()) >= 0 && !specialChars[ch]) {
  29137. if (ch === 0x23) { // '#'
  29138. ch = this.nextChar();
  29139. var x = toHexDigit(ch);
  29140. if (x !== -1) {
  29141. var x2 = toHexDigit(this.nextChar());
  29142. if (x2 === -1) {
  29143. error('Illegal digit in hex char in name: ' + x2);
  29144. }
  29145. strBuf.push(String.fromCharCode((x << 4) | x2));
  29146. } else {
  29147. strBuf.push('#', String.fromCharCode(ch));
  29148. }
  29149. } else {
  29150. strBuf.push(String.fromCharCode(ch));
  29151. }
  29152. }
  29153. if (strBuf.length > 128) {
  29154. error('Warning: name token is longer than allowed by the spec: ' +
  29155. strBuf.length);
  29156. }
  29157. return Name.get(strBuf.join(''));
  29158. },
  29159. getHexString: function Lexer_getHexString() {
  29160. var strBuf = this.strBuf;
  29161. strBuf.length = 0;
  29162. var ch = this.currentChar;
  29163. var isFirstHex = true;
  29164. var firstDigit;
  29165. var secondDigit;
  29166. while (true) {
  29167. if (ch < 0) {
  29168. warn('Unterminated hex string');
  29169. break;
  29170. } else if (ch === 0x3E) { // '>'
  29171. this.nextChar();
  29172. break;
  29173. } else if (specialChars[ch] === 1) {
  29174. ch = this.nextChar();
  29175. continue;
  29176. } else {
  29177. if (isFirstHex) {
  29178. firstDigit = toHexDigit(ch);
  29179. if (firstDigit === -1) {
  29180. warn('Ignoring invalid character "' + ch + '" in hex string');
  29181. ch = this.nextChar();
  29182. continue;
  29183. }
  29184. } else {
  29185. secondDigit = toHexDigit(ch);
  29186. if (secondDigit === -1) {
  29187. warn('Ignoring invalid character "' + ch + '" in hex string');
  29188. ch = this.nextChar();
  29189. continue;
  29190. }
  29191. strBuf.push(String.fromCharCode((firstDigit << 4) | secondDigit));
  29192. }
  29193. isFirstHex = !isFirstHex;
  29194. ch = this.nextChar();
  29195. }
  29196. }
  29197. return strBuf.join('');
  29198. },
  29199. getObj: function Lexer_getObj() {
  29200. // skip whitespace and comments
  29201. var comment = false;
  29202. var ch = this.currentChar;
  29203. while (true) {
  29204. if (ch < 0) {
  29205. return EOF;
  29206. }
  29207. if (comment) {
  29208. if (ch === 0x0A || ch === 0x0D) { // LF, CR
  29209. comment = false;
  29210. }
  29211. } else if (ch === 0x25) { // '%'
  29212. comment = true;
  29213. } else if (specialChars[ch] !== 1) {
  29214. break;
  29215. }
  29216. ch = this.nextChar();
  29217. }
  29218. // start reading token
  29219. switch (ch | 0) {
  29220. case 0x30: case 0x31: case 0x32: case 0x33: case 0x34: // '0'-'4'
  29221. case 0x35: case 0x36: case 0x37: case 0x38: case 0x39: // '5'-'9'
  29222. case 0x2B: case 0x2D: case 0x2E: // '+', '-', '.'
  29223. return this.getNumber();
  29224. case 0x28: // '('
  29225. return this.getString();
  29226. case 0x2F: // '/'
  29227. return this.getName();
  29228. // array punctuation
  29229. case 0x5B: // '['
  29230. this.nextChar();
  29231. return Cmd.get('[');
  29232. case 0x5D: // ']'
  29233. this.nextChar();
  29234. return Cmd.get(']');
  29235. // hex string or dict punctuation
  29236. case 0x3C: // '<'
  29237. ch = this.nextChar();
  29238. if (ch === 0x3C) {
  29239. // dict punctuation
  29240. this.nextChar();
  29241. return Cmd.get('<<');
  29242. }
  29243. return this.getHexString();
  29244. // dict punctuation
  29245. case 0x3E: // '>'
  29246. ch = this.nextChar();
  29247. if (ch === 0x3E) {
  29248. this.nextChar();
  29249. return Cmd.get('>>');
  29250. }
  29251. return Cmd.get('>');
  29252. case 0x7B: // '{'
  29253. this.nextChar();
  29254. return Cmd.get('{');
  29255. case 0x7D: // '}'
  29256. this.nextChar();
  29257. return Cmd.get('}');
  29258. case 0x29: // ')'
  29259. error('Illegal character: ' + ch);
  29260. break;
  29261. }
  29262. // command
  29263. var str = String.fromCharCode(ch);
  29264. var knownCommands = this.knownCommands;
  29265. var knownCommandFound = knownCommands && knownCommands[str] !== undefined;
  29266. while ((ch = this.nextChar()) >= 0 && !specialChars[ch]) {
  29267. // stop if known command is found and next character does not make
  29268. // the str a command
  29269. var possibleCommand = str + String.fromCharCode(ch);
  29270. if (knownCommandFound && knownCommands[possibleCommand] === undefined) {
  29271. break;
  29272. }
  29273. if (str.length === 128) {
  29274. error('Command token too long: ' + str.length);
  29275. }
  29276. str = possibleCommand;
  29277. knownCommandFound = knownCommands && knownCommands[str] !== undefined;
  29278. }
  29279. if (str === 'true') {
  29280. return true;
  29281. }
  29282. if (str === 'false') {
  29283. return false;
  29284. }
  29285. if (str === 'null') {
  29286. return null;
  29287. }
  29288. return Cmd.get(str);
  29289. },
  29290. skipToNextLine: function Lexer_skipToNextLine() {
  29291. var ch = this.currentChar;
  29292. while (ch >= 0) {
  29293. if (ch === 0x0D) { // CR
  29294. ch = this.nextChar();
  29295. if (ch === 0x0A) { // LF
  29296. this.nextChar();
  29297. }
  29298. break;
  29299. } else if (ch === 0x0A) { // LF
  29300. this.nextChar();
  29301. break;
  29302. }
  29303. ch = this.nextChar();
  29304. }
  29305. }
  29306. };
  29307. return Lexer;
  29308. })();
  29309. var Linearization = {
  29310. create: function LinearizationCreate(stream) {
  29311. function getInt(name, allowZeroValue) {
  29312. var obj = linDict.get(name);
  29313. if (isInt(obj) && (allowZeroValue ? obj >= 0 : obj > 0)) {
  29314. return obj;
  29315. }
  29316. throw new Error('The "' + name + '" parameter in the linearization ' +
  29317. 'dictionary is invalid.');
  29318. }
  29319. function getHints() {
  29320. var hints = linDict.get('H'), hintsLength, item;
  29321. if (isArray(hints) &&
  29322. ((hintsLength = hints.length) === 2 || hintsLength === 4)) {
  29323. for (var index = 0; index < hintsLength; index++) {
  29324. if (!(isInt(item = hints[index]) && item > 0)) {
  29325. throw new Error('Hint (' + index +
  29326. ') in the linearization dictionary is invalid.');
  29327. }
  29328. }
  29329. return hints;
  29330. }
  29331. throw new Error('Hint array in the linearization dictionary is invalid.');
  29332. }
  29333. var parser = new Parser(new Lexer(stream), false, null);
  29334. var obj1 = parser.getObj();
  29335. var obj2 = parser.getObj();
  29336. var obj3 = parser.getObj();
  29337. var linDict = parser.getObj();
  29338. var obj, length;
  29339. if (!(isInt(obj1) && isInt(obj2) && isCmd(obj3, 'obj') && isDict(linDict) &&
  29340. isNum(obj = linDict.get('Linearized')) && obj > 0)) {
  29341. return null; // No valid linearization dictionary found.
  29342. } else if ((length = getInt('L')) !== stream.length) {
  29343. throw new Error('The "L" parameter in the linearization dictionary ' +
  29344. 'does not equal the stream length.');
  29345. }
  29346. return {
  29347. length: length,
  29348. hints: getHints(),
  29349. objectNumberFirst: getInt('O'),
  29350. endFirst: getInt('E'),
  29351. numPages: getInt('N'),
  29352. mainXRefEntriesOffset: getInt('T'),
  29353. pageFirst: (linDict.has('P') ? getInt('P', true) : 0)
  29354. };
  29355. }
  29356. };
  29357. var PostScriptParser = (function PostScriptParserClosure() {
  29358. function PostScriptParser(lexer) {
  29359. this.lexer = lexer;
  29360. this.operators = [];
  29361. this.token = null;
  29362. this.prev = null;
  29363. }
  29364. PostScriptParser.prototype = {
  29365. nextToken: function PostScriptParser_nextToken() {
  29366. this.prev = this.token;
  29367. this.token = this.lexer.getToken();
  29368. },
  29369. accept: function PostScriptParser_accept(type) {
  29370. if (this.token.type === type) {
  29371. this.nextToken();
  29372. return true;
  29373. }
  29374. return false;
  29375. },
  29376. expect: function PostScriptParser_expect(type) {
  29377. if (this.accept(type)) {
  29378. return true;
  29379. }
  29380. error('Unexpected symbol: found ' + this.token.type + ' expected ' +
  29381. type + '.');
  29382. },
  29383. parse: function PostScriptParser_parse() {
  29384. this.nextToken();
  29385. this.expect(PostScriptTokenTypes.LBRACE);
  29386. this.parseBlock();
  29387. this.expect(PostScriptTokenTypes.RBRACE);
  29388. return this.operators;
  29389. },
  29390. parseBlock: function PostScriptParser_parseBlock() {
  29391. while (true) {
  29392. if (this.accept(PostScriptTokenTypes.NUMBER)) {
  29393. this.operators.push(this.prev.value);
  29394. } else if (this.accept(PostScriptTokenTypes.OPERATOR)) {
  29395. this.operators.push(this.prev.value);
  29396. } else if (this.accept(PostScriptTokenTypes.LBRACE)) {
  29397. this.parseCondition();
  29398. } else {
  29399. return;
  29400. }
  29401. }
  29402. },
  29403. parseCondition: function PostScriptParser_parseCondition() {
  29404. // Add two place holders that will be updated later
  29405. var conditionLocation = this.operators.length;
  29406. this.operators.push(null, null);
  29407. this.parseBlock();
  29408. this.expect(PostScriptTokenTypes.RBRACE);
  29409. if (this.accept(PostScriptTokenTypes.IF)) {
  29410. // The true block is right after the 'if' so it just falls through on
  29411. // true else it jumps and skips the true block.
  29412. this.operators[conditionLocation] = this.operators.length;
  29413. this.operators[conditionLocation + 1] = 'jz';
  29414. } else if (this.accept(PostScriptTokenTypes.LBRACE)) {
  29415. var jumpLocation = this.operators.length;
  29416. this.operators.push(null, null);
  29417. var endOfTrue = this.operators.length;
  29418. this.parseBlock();
  29419. this.expect(PostScriptTokenTypes.RBRACE);
  29420. this.expect(PostScriptTokenTypes.IFELSE);
  29421. // The jump is added at the end of the true block to skip the false
  29422. // block.
  29423. this.operators[jumpLocation] = this.operators.length;
  29424. this.operators[jumpLocation + 1] = 'j';
  29425. this.operators[conditionLocation] = endOfTrue;
  29426. this.operators[conditionLocation + 1] = 'jz';
  29427. } else {
  29428. error('PS Function: error parsing conditional.');
  29429. }
  29430. }
  29431. };
  29432. return PostScriptParser;
  29433. })();
  29434. var PostScriptTokenTypes = {
  29435. LBRACE: 0,
  29436. RBRACE: 1,
  29437. NUMBER: 2,
  29438. OPERATOR: 3,
  29439. IF: 4,
  29440. IFELSE: 5
  29441. };
  29442. var PostScriptToken = (function PostScriptTokenClosure() {
  29443. function PostScriptToken(type, value) {
  29444. this.type = type;
  29445. this.value = value;
  29446. }
  29447. var opCache = {};
  29448. PostScriptToken.getOperator = function PostScriptToken_getOperator(op) {
  29449. var opValue = opCache[op];
  29450. if (opValue) {
  29451. return opValue;
  29452. }
  29453. return opCache[op] = new PostScriptToken(PostScriptTokenTypes.OPERATOR, op);
  29454. };
  29455. PostScriptToken.LBRACE = new PostScriptToken(PostScriptTokenTypes.LBRACE,
  29456. '{');
  29457. PostScriptToken.RBRACE = new PostScriptToken(PostScriptTokenTypes.RBRACE,
  29458. '}');
  29459. PostScriptToken.IF = new PostScriptToken(PostScriptTokenTypes.IF, 'IF');
  29460. PostScriptToken.IFELSE = new PostScriptToken(PostScriptTokenTypes.IFELSE,
  29461. 'IFELSE');
  29462. return PostScriptToken;
  29463. })();
  29464. var PostScriptLexer = (function PostScriptLexerClosure() {
  29465. function PostScriptLexer(stream) {
  29466. this.stream = stream;
  29467. this.nextChar();
  29468. this.strBuf = [];
  29469. }
  29470. PostScriptLexer.prototype = {
  29471. nextChar: function PostScriptLexer_nextChar() {
  29472. return (this.currentChar = this.stream.getByte());
  29473. },
  29474. getToken: function PostScriptLexer_getToken() {
  29475. var comment = false;
  29476. var ch = this.currentChar;
  29477. // skip comments
  29478. while (true) {
  29479. if (ch < 0) {
  29480. return EOF;
  29481. }
  29482. if (comment) {
  29483. if (ch === 0x0A || ch === 0x0D) {
  29484. comment = false;
  29485. }
  29486. } else if (ch === 0x25) { // '%'
  29487. comment = true;
  29488. } else if (!Lexer.isSpace(ch)) {
  29489. break;
  29490. }
  29491. ch = this.nextChar();
  29492. }
  29493. switch (ch | 0) {
  29494. case 0x30: case 0x31: case 0x32: case 0x33: case 0x34: // '0'-'4'
  29495. case 0x35: case 0x36: case 0x37: case 0x38: case 0x39: // '5'-'9'
  29496. case 0x2B: case 0x2D: case 0x2E: // '+', '-', '.'
  29497. return new PostScriptToken(PostScriptTokenTypes.NUMBER,
  29498. this.getNumber());
  29499. case 0x7B: // '{'
  29500. this.nextChar();
  29501. return PostScriptToken.LBRACE;
  29502. case 0x7D: // '}'
  29503. this.nextChar();
  29504. return PostScriptToken.RBRACE;
  29505. }
  29506. // operator
  29507. var strBuf = this.strBuf;
  29508. strBuf.length = 0;
  29509. strBuf[0] = String.fromCharCode(ch);
  29510. while ((ch = this.nextChar()) >= 0 && // and 'A'-'Z', 'a'-'z'
  29511. ((ch >= 0x41 && ch <= 0x5A) || (ch >= 0x61 && ch <= 0x7A))) {
  29512. strBuf.push(String.fromCharCode(ch));
  29513. }
  29514. var str = strBuf.join('');
  29515. switch (str.toLowerCase()) {
  29516. case 'if':
  29517. return PostScriptToken.IF;
  29518. case 'ifelse':
  29519. return PostScriptToken.IFELSE;
  29520. default:
  29521. return PostScriptToken.getOperator(str);
  29522. }
  29523. },
  29524. getNumber: function PostScriptLexer_getNumber() {
  29525. var ch = this.currentChar;
  29526. var strBuf = this.strBuf;
  29527. strBuf.length = 0;
  29528. strBuf[0] = String.fromCharCode(ch);
  29529. while ((ch = this.nextChar()) >= 0) {
  29530. if ((ch >= 0x30 && ch <= 0x39) || // '0'-'9'
  29531. ch === 0x2D || ch === 0x2E) { // '-', '.'
  29532. strBuf.push(String.fromCharCode(ch));
  29533. } else {
  29534. break;
  29535. }
  29536. }
  29537. var value = parseFloat(strBuf.join(''));
  29538. if (isNaN(value)) {
  29539. error('Invalid floating point number: ' + value);
  29540. }
  29541. return value;
  29542. }
  29543. };
  29544. return PostScriptLexer;
  29545. })();
  29546. var Stream = (function StreamClosure() {
  29547. function Stream(arrayBuffer, start, length, dict) {
  29548. this.bytes = (arrayBuffer instanceof Uint8Array ?
  29549. arrayBuffer : new Uint8Array(arrayBuffer));
  29550. this.start = start || 0;
  29551. this.pos = this.start;
  29552. this.end = (start + length) || this.bytes.length;
  29553. this.dict = dict;
  29554. }
  29555. // required methods for a stream. if a particular stream does not
  29556. // implement these, an error should be thrown
  29557. Stream.prototype = {
  29558. get length() {
  29559. return this.end - this.start;
  29560. },
  29561. get isEmpty() {
  29562. return this.length === 0;
  29563. },
  29564. getByte: function Stream_getByte() {
  29565. if (this.pos >= this.end) {
  29566. return -1;
  29567. }
  29568. return this.bytes[this.pos++];
  29569. },
  29570. getUint16: function Stream_getUint16() {
  29571. var b0 = this.getByte();
  29572. var b1 = this.getByte();
  29573. if (b0 === -1 || b1 === -1) {
  29574. return -1;
  29575. }
  29576. return (b0 << 8) + b1;
  29577. },
  29578. getInt32: function Stream_getInt32() {
  29579. var b0 = this.getByte();
  29580. var b1 = this.getByte();
  29581. var b2 = this.getByte();
  29582. var b3 = this.getByte();
  29583. return (b0 << 24) + (b1 << 16) + (b2 << 8) + b3;
  29584. },
  29585. // returns subarray of original buffer
  29586. // should only be read
  29587. getBytes: function Stream_getBytes(length) {
  29588. var bytes = this.bytes;
  29589. var pos = this.pos;
  29590. var strEnd = this.end;
  29591. if (!length) {
  29592. return bytes.subarray(pos, strEnd);
  29593. }
  29594. var end = pos + length;
  29595. if (end > strEnd) {
  29596. end = strEnd;
  29597. }
  29598. this.pos = end;
  29599. return bytes.subarray(pos, end);
  29600. },
  29601. peekByte: function Stream_peekByte() {
  29602. var peekedByte = this.getByte();
  29603. this.pos--;
  29604. return peekedByte;
  29605. },
  29606. peekBytes: function Stream_peekBytes(length) {
  29607. var bytes = this.getBytes(length);
  29608. this.pos -= bytes.length;
  29609. return bytes;
  29610. },
  29611. skip: function Stream_skip(n) {
  29612. if (!n) {
  29613. n = 1;
  29614. }
  29615. this.pos += n;
  29616. },
  29617. reset: function Stream_reset() {
  29618. this.pos = this.start;
  29619. },
  29620. moveStart: function Stream_moveStart() {
  29621. this.start = this.pos;
  29622. },
  29623. makeSubStream: function Stream_makeSubStream(start, length, dict) {
  29624. return new Stream(this.bytes.buffer, start, length, dict);
  29625. },
  29626. isStream: true
  29627. };
  29628. return Stream;
  29629. })();
  29630. var StringStream = (function StringStreamClosure() {
  29631. function StringStream(str) {
  29632. var length = str.length;
  29633. var bytes = new Uint8Array(length);
  29634. for (var n = 0; n < length; ++n) {
  29635. bytes[n] = str.charCodeAt(n);
  29636. }
  29637. Stream.call(this, bytes);
  29638. }
  29639. StringStream.prototype = Stream.prototype;
  29640. return StringStream;
  29641. })();
  29642. // super class for the decoding streams
  29643. var DecodeStream = (function DecodeStreamClosure() {
  29644. // Lots of DecodeStreams are created whose buffers are never used. For these
  29645. // we share a single empty buffer. This is (a) space-efficient and (b) avoids
  29646. // having special cases that would be required if we used |null| for an empty
  29647. // buffer.
  29648. var emptyBuffer = new Uint8Array(0);
  29649. function DecodeStream(maybeMinBufferLength) {
  29650. this.pos = 0;
  29651. this.bufferLength = 0;
  29652. this.eof = false;
  29653. this.buffer = emptyBuffer;
  29654. this.minBufferLength = 512;
  29655. if (maybeMinBufferLength) {
  29656. // Compute the first power of two that is as big as maybeMinBufferLength.
  29657. while (this.minBufferLength < maybeMinBufferLength) {
  29658. this.minBufferLength *= 2;
  29659. }
  29660. }
  29661. }
  29662. DecodeStream.prototype = {
  29663. get isEmpty() {
  29664. while (!this.eof && this.bufferLength === 0) {
  29665. this.readBlock();
  29666. }
  29667. return this.bufferLength === 0;
  29668. },
  29669. ensureBuffer: function DecodeStream_ensureBuffer(requested) {
  29670. var buffer = this.buffer;
  29671. if (requested <= buffer.byteLength) {
  29672. return buffer;
  29673. }
  29674. var size = this.minBufferLength;
  29675. while (size < requested) {
  29676. size *= 2;
  29677. }
  29678. var buffer2 = new Uint8Array(size);
  29679. buffer2.set(buffer);
  29680. return (this.buffer = buffer2);
  29681. },
  29682. getByte: function DecodeStream_getByte() {
  29683. var pos = this.pos;
  29684. while (this.bufferLength <= pos) {
  29685. if (this.eof) {
  29686. return -1;
  29687. }
  29688. this.readBlock();
  29689. }
  29690. return this.buffer[this.pos++];
  29691. },
  29692. getUint16: function DecodeStream_getUint16() {
  29693. var b0 = this.getByte();
  29694. var b1 = this.getByte();
  29695. if (b0 === -1 || b1 === -1) {
  29696. return -1;
  29697. }
  29698. return (b0 << 8) + b1;
  29699. },
  29700. getInt32: function DecodeStream_getInt32() {
  29701. var b0 = this.getByte();
  29702. var b1 = this.getByte();
  29703. var b2 = this.getByte();
  29704. var b3 = this.getByte();
  29705. return (b0 << 24) + (b1 << 16) + (b2 << 8) + b3;
  29706. },
  29707. getBytes: function DecodeStream_getBytes(length) {
  29708. var end, pos = this.pos;
  29709. if (length) {
  29710. this.ensureBuffer(pos + length);
  29711. end = pos + length;
  29712. while (!this.eof && this.bufferLength < end) {
  29713. this.readBlock();
  29714. }
  29715. var bufEnd = this.bufferLength;
  29716. if (end > bufEnd) {
  29717. end = bufEnd;
  29718. }
  29719. } else {
  29720. while (!this.eof) {
  29721. this.readBlock();
  29722. }
  29723. end = this.bufferLength;
  29724. }
  29725. this.pos = end;
  29726. return this.buffer.subarray(pos, end);
  29727. },
  29728. peekByte: function DecodeStream_peekByte() {
  29729. var peekedByte = this.getByte();
  29730. this.pos--;
  29731. return peekedByte;
  29732. },
  29733. peekBytes: function DecodeStream_peekBytes(length) {
  29734. var bytes = this.getBytes(length);
  29735. this.pos -= bytes.length;
  29736. return bytes;
  29737. },
  29738. makeSubStream: function DecodeStream_makeSubStream(start, length, dict) {
  29739. var end = start + length;
  29740. while (this.bufferLength <= end && !this.eof) {
  29741. this.readBlock();
  29742. }
  29743. return new Stream(this.buffer, start, length, dict);
  29744. },
  29745. skip: function DecodeStream_skip(n) {
  29746. if (!n) {
  29747. n = 1;
  29748. }
  29749. this.pos += n;
  29750. },
  29751. reset: function DecodeStream_reset() {
  29752. this.pos = 0;
  29753. },
  29754. getBaseStreams: function DecodeStream_getBaseStreams() {
  29755. if (this.str && this.str.getBaseStreams) {
  29756. return this.str.getBaseStreams();
  29757. }
  29758. return [];
  29759. }
  29760. };
  29761. return DecodeStream;
  29762. })();
  29763. var StreamsSequenceStream = (function StreamsSequenceStreamClosure() {
  29764. function StreamsSequenceStream(streams) {
  29765. this.streams = streams;
  29766. DecodeStream.call(this, /* maybeLength = */ null);
  29767. }
  29768. StreamsSequenceStream.prototype = Object.create(DecodeStream.prototype);
  29769. StreamsSequenceStream.prototype.readBlock =
  29770. function streamSequenceStreamReadBlock() {
  29771. var streams = this.streams;
  29772. if (streams.length === 0) {
  29773. this.eof = true;
  29774. return;
  29775. }
  29776. var stream = streams.shift();
  29777. var chunk = stream.getBytes();
  29778. var bufferLength = this.bufferLength;
  29779. var newLength = bufferLength + chunk.length;
  29780. var buffer = this.ensureBuffer(newLength);
  29781. buffer.set(chunk, bufferLength);
  29782. this.bufferLength = newLength;
  29783. };
  29784. StreamsSequenceStream.prototype.getBaseStreams =
  29785. function StreamsSequenceStream_getBaseStreams() {
  29786. var baseStreams = [];
  29787. for (var i = 0, ii = this.streams.length; i < ii; i++) {
  29788. var stream = this.streams[i];
  29789. if (stream.getBaseStreams) {
  29790. Util.appendToArray(baseStreams, stream.getBaseStreams());
  29791. }
  29792. }
  29793. return baseStreams;
  29794. };
  29795. return StreamsSequenceStream;
  29796. })();
  29797. var FlateStream = (function FlateStreamClosure() {
  29798. var codeLenCodeMap = new Int32Array([
  29799. 16, 17, 18, 0, 8, 7, 9, 6, 10, 5, 11, 4, 12, 3, 13, 2, 14, 1, 15
  29800. ]);
  29801. var lengthDecode = new Int32Array([
  29802. 0x00003, 0x00004, 0x00005, 0x00006, 0x00007, 0x00008, 0x00009, 0x0000a,
  29803. 0x1000b, 0x1000d, 0x1000f, 0x10011, 0x20013, 0x20017, 0x2001b, 0x2001f,
  29804. 0x30023, 0x3002b, 0x30033, 0x3003b, 0x40043, 0x40053, 0x40063, 0x40073,
  29805. 0x50083, 0x500a3, 0x500c3, 0x500e3, 0x00102, 0x00102, 0x00102
  29806. ]);
  29807. var distDecode = new Int32Array([
  29808. 0x00001, 0x00002, 0x00003, 0x00004, 0x10005, 0x10007, 0x20009, 0x2000d,
  29809. 0x30011, 0x30019, 0x40021, 0x40031, 0x50041, 0x50061, 0x60081, 0x600c1,
  29810. 0x70101, 0x70181, 0x80201, 0x80301, 0x90401, 0x90601, 0xa0801, 0xa0c01,
  29811. 0xb1001, 0xb1801, 0xc2001, 0xc3001, 0xd4001, 0xd6001
  29812. ]);
  29813. var fixedLitCodeTab = [new Int32Array([
  29814. 0x70100, 0x80050, 0x80010, 0x80118, 0x70110, 0x80070, 0x80030, 0x900c0,
  29815. 0x70108, 0x80060, 0x80020, 0x900a0, 0x80000, 0x80080, 0x80040, 0x900e0,
  29816. 0x70104, 0x80058, 0x80018, 0x90090, 0x70114, 0x80078, 0x80038, 0x900d0,
  29817. 0x7010c, 0x80068, 0x80028, 0x900b0, 0x80008, 0x80088, 0x80048, 0x900f0,
  29818. 0x70102, 0x80054, 0x80014, 0x8011c, 0x70112, 0x80074, 0x80034, 0x900c8,
  29819. 0x7010a, 0x80064, 0x80024, 0x900a8, 0x80004, 0x80084, 0x80044, 0x900e8,
  29820. 0x70106, 0x8005c, 0x8001c, 0x90098, 0x70116, 0x8007c, 0x8003c, 0x900d8,
  29821. 0x7010e, 0x8006c, 0x8002c, 0x900b8, 0x8000c, 0x8008c, 0x8004c, 0x900f8,
  29822. 0x70101, 0x80052, 0x80012, 0x8011a, 0x70111, 0x80072, 0x80032, 0x900c4,
  29823. 0x70109, 0x80062, 0x80022, 0x900a4, 0x80002, 0x80082, 0x80042, 0x900e4,
  29824. 0x70105, 0x8005a, 0x8001a, 0x90094, 0x70115, 0x8007a, 0x8003a, 0x900d4,
  29825. 0x7010d, 0x8006a, 0x8002a, 0x900b4, 0x8000a, 0x8008a, 0x8004a, 0x900f4,
  29826. 0x70103, 0x80056, 0x80016, 0x8011e, 0x70113, 0x80076, 0x80036, 0x900cc,
  29827. 0x7010b, 0x80066, 0x80026, 0x900ac, 0x80006, 0x80086, 0x80046, 0x900ec,
  29828. 0x70107, 0x8005e, 0x8001e, 0x9009c, 0x70117, 0x8007e, 0x8003e, 0x900dc,
  29829. 0x7010f, 0x8006e, 0x8002e, 0x900bc, 0x8000e, 0x8008e, 0x8004e, 0x900fc,
  29830. 0x70100, 0x80051, 0x80011, 0x80119, 0x70110, 0x80071, 0x80031, 0x900c2,
  29831. 0x70108, 0x80061, 0x80021, 0x900a2, 0x80001, 0x80081, 0x80041, 0x900e2,
  29832. 0x70104, 0x80059, 0x80019, 0x90092, 0x70114, 0x80079, 0x80039, 0x900d2,
  29833. 0x7010c, 0x80069, 0x80029, 0x900b2, 0x80009, 0x80089, 0x80049, 0x900f2,
  29834. 0x70102, 0x80055, 0x80015, 0x8011d, 0x70112, 0x80075, 0x80035, 0x900ca,
  29835. 0x7010a, 0x80065, 0x80025, 0x900aa, 0x80005, 0x80085, 0x80045, 0x900ea,
  29836. 0x70106, 0x8005d, 0x8001d, 0x9009a, 0x70116, 0x8007d, 0x8003d, 0x900da,
  29837. 0x7010e, 0x8006d, 0x8002d, 0x900ba, 0x8000d, 0x8008d, 0x8004d, 0x900fa,
  29838. 0x70101, 0x80053, 0x80013, 0x8011b, 0x70111, 0x80073, 0x80033, 0x900c6,
  29839. 0x70109, 0x80063, 0x80023, 0x900a6, 0x80003, 0x80083, 0x80043, 0x900e6,
  29840. 0x70105, 0x8005b, 0x8001b, 0x90096, 0x70115, 0x8007b, 0x8003b, 0x900d6,
  29841. 0x7010d, 0x8006b, 0x8002b, 0x900b6, 0x8000b, 0x8008b, 0x8004b, 0x900f6,
  29842. 0x70103, 0x80057, 0x80017, 0x8011f, 0x70113, 0x80077, 0x80037, 0x900ce,
  29843. 0x7010b, 0x80067, 0x80027, 0x900ae, 0x80007, 0x80087, 0x80047, 0x900ee,
  29844. 0x70107, 0x8005f, 0x8001f, 0x9009e, 0x70117, 0x8007f, 0x8003f, 0x900de,
  29845. 0x7010f, 0x8006f, 0x8002f, 0x900be, 0x8000f, 0x8008f, 0x8004f, 0x900fe,
  29846. 0x70100, 0x80050, 0x80010, 0x80118, 0x70110, 0x80070, 0x80030, 0x900c1,
  29847. 0x70108, 0x80060, 0x80020, 0x900a1, 0x80000, 0x80080, 0x80040, 0x900e1,
  29848. 0x70104, 0x80058, 0x80018, 0x90091, 0x70114, 0x80078, 0x80038, 0x900d1,
  29849. 0x7010c, 0x80068, 0x80028, 0x900b1, 0x80008, 0x80088, 0x80048, 0x900f1,
  29850. 0x70102, 0x80054, 0x80014, 0x8011c, 0x70112, 0x80074, 0x80034, 0x900c9,
  29851. 0x7010a, 0x80064, 0x80024, 0x900a9, 0x80004, 0x80084, 0x80044, 0x900e9,
  29852. 0x70106, 0x8005c, 0x8001c, 0x90099, 0x70116, 0x8007c, 0x8003c, 0x900d9,
  29853. 0x7010e, 0x8006c, 0x8002c, 0x900b9, 0x8000c, 0x8008c, 0x8004c, 0x900f9,
  29854. 0x70101, 0x80052, 0x80012, 0x8011a, 0x70111, 0x80072, 0x80032, 0x900c5,
  29855. 0x70109, 0x80062, 0x80022, 0x900a5, 0x80002, 0x80082, 0x80042, 0x900e5,
  29856. 0x70105, 0x8005a, 0x8001a, 0x90095, 0x70115, 0x8007a, 0x8003a, 0x900d5,
  29857. 0x7010d, 0x8006a, 0x8002a, 0x900b5, 0x8000a, 0x8008a, 0x8004a, 0x900f5,
  29858. 0x70103, 0x80056, 0x80016, 0x8011e, 0x70113, 0x80076, 0x80036, 0x900cd,
  29859. 0x7010b, 0x80066, 0x80026, 0x900ad, 0x80006, 0x80086, 0x80046, 0x900ed,
  29860. 0x70107, 0x8005e, 0x8001e, 0x9009d, 0x70117, 0x8007e, 0x8003e, 0x900dd,
  29861. 0x7010f, 0x8006e, 0x8002e, 0x900bd, 0x8000e, 0x8008e, 0x8004e, 0x900fd,
  29862. 0x70100, 0x80051, 0x80011, 0x80119, 0x70110, 0x80071, 0x80031, 0x900c3,
  29863. 0x70108, 0x80061, 0x80021, 0x900a3, 0x80001, 0x80081, 0x80041, 0x900e3,
  29864. 0x70104, 0x80059, 0x80019, 0x90093, 0x70114, 0x80079, 0x80039, 0x900d3,
  29865. 0x7010c, 0x80069, 0x80029, 0x900b3, 0x80009, 0x80089, 0x80049, 0x900f3,
  29866. 0x70102, 0x80055, 0x80015, 0x8011d, 0x70112, 0x80075, 0x80035, 0x900cb,
  29867. 0x7010a, 0x80065, 0x80025, 0x900ab, 0x80005, 0x80085, 0x80045, 0x900eb,
  29868. 0x70106, 0x8005d, 0x8001d, 0x9009b, 0x70116, 0x8007d, 0x8003d, 0x900db,
  29869. 0x7010e, 0x8006d, 0x8002d, 0x900bb, 0x8000d, 0x8008d, 0x8004d, 0x900fb,
  29870. 0x70101, 0x80053, 0x80013, 0x8011b, 0x70111, 0x80073, 0x80033, 0x900c7,
  29871. 0x70109, 0x80063, 0x80023, 0x900a7, 0x80003, 0x80083, 0x80043, 0x900e7,
  29872. 0x70105, 0x8005b, 0x8001b, 0x90097, 0x70115, 0x8007b, 0x8003b, 0x900d7,
  29873. 0x7010d, 0x8006b, 0x8002b, 0x900b7, 0x8000b, 0x8008b, 0x8004b, 0x900f7,
  29874. 0x70103, 0x80057, 0x80017, 0x8011f, 0x70113, 0x80077, 0x80037, 0x900cf,
  29875. 0x7010b, 0x80067, 0x80027, 0x900af, 0x80007, 0x80087, 0x80047, 0x900ef,
  29876. 0x70107, 0x8005f, 0x8001f, 0x9009f, 0x70117, 0x8007f, 0x8003f, 0x900df,
  29877. 0x7010f, 0x8006f, 0x8002f, 0x900bf, 0x8000f, 0x8008f, 0x8004f, 0x900ff
  29878. ]), 9];
  29879. var fixedDistCodeTab = [new Int32Array([
  29880. 0x50000, 0x50010, 0x50008, 0x50018, 0x50004, 0x50014, 0x5000c, 0x5001c,
  29881. 0x50002, 0x50012, 0x5000a, 0x5001a, 0x50006, 0x50016, 0x5000e, 0x00000,
  29882. 0x50001, 0x50011, 0x50009, 0x50019, 0x50005, 0x50015, 0x5000d, 0x5001d,
  29883. 0x50003, 0x50013, 0x5000b, 0x5001b, 0x50007, 0x50017, 0x5000f, 0x00000
  29884. ]), 5];
  29885. function FlateStream(str, maybeLength) {
  29886. this.str = str;
  29887. this.dict = str.dict;
  29888. var cmf = str.getByte();
  29889. var flg = str.getByte();
  29890. if (cmf === -1 || flg === -1) {
  29891. error('Invalid header in flate stream: ' + cmf + ', ' + flg);
  29892. }
  29893. if ((cmf & 0x0f) !== 0x08) {
  29894. error('Unknown compression method in flate stream: ' + cmf + ', ' + flg);
  29895. }
  29896. if ((((cmf << 8) + flg) % 31) !== 0) {
  29897. error('Bad FCHECK in flate stream: ' + cmf + ', ' + flg);
  29898. }
  29899. if (flg & 0x20) {
  29900. error('FDICT bit set in flate stream: ' + cmf + ', ' + flg);
  29901. }
  29902. this.codeSize = 0;
  29903. this.codeBuf = 0;
  29904. DecodeStream.call(this, maybeLength);
  29905. }
  29906. FlateStream.prototype = Object.create(DecodeStream.prototype);
  29907. FlateStream.prototype.getBits = function FlateStream_getBits(bits) {
  29908. var str = this.str;
  29909. var codeSize = this.codeSize;
  29910. var codeBuf = this.codeBuf;
  29911. var b;
  29912. while (codeSize < bits) {
  29913. if ((b = str.getByte()) === -1) {
  29914. error('Bad encoding in flate stream');
  29915. }
  29916. codeBuf |= b << codeSize;
  29917. codeSize += 8;
  29918. }
  29919. b = codeBuf & ((1 << bits) - 1);
  29920. this.codeBuf = codeBuf >> bits;
  29921. this.codeSize = codeSize -= bits;
  29922. return b;
  29923. };
  29924. FlateStream.prototype.getCode = function FlateStream_getCode(table) {
  29925. var str = this.str;
  29926. var codes = table[0];
  29927. var maxLen = table[1];
  29928. var codeSize = this.codeSize;
  29929. var codeBuf = this.codeBuf;
  29930. var b;
  29931. while (codeSize < maxLen) {
  29932. if ((b = str.getByte()) === -1) {
  29933. // premature end of stream. code might however still be valid.
  29934. // codeSize < codeLen check below guards against incomplete codeVal.
  29935. break;
  29936. }
  29937. codeBuf |= (b << codeSize);
  29938. codeSize += 8;
  29939. }
  29940. var code = codes[codeBuf & ((1 << maxLen) - 1)];
  29941. var codeLen = code >> 16;
  29942. var codeVal = code & 0xffff;
  29943. if (codeLen < 1 || codeSize < codeLen) {
  29944. error('Bad encoding in flate stream');
  29945. }
  29946. this.codeBuf = (codeBuf >> codeLen);
  29947. this.codeSize = (codeSize - codeLen);
  29948. return codeVal;
  29949. };
  29950. FlateStream.prototype.generateHuffmanTable =
  29951. function flateStreamGenerateHuffmanTable(lengths) {
  29952. var n = lengths.length;
  29953. // find max code length
  29954. var maxLen = 0;
  29955. var i;
  29956. for (i = 0; i < n; ++i) {
  29957. if (lengths[i] > maxLen) {
  29958. maxLen = lengths[i];
  29959. }
  29960. }
  29961. // build the table
  29962. var size = 1 << maxLen;
  29963. var codes = new Int32Array(size);
  29964. for (var len = 1, code = 0, skip = 2;
  29965. len <= maxLen;
  29966. ++len, code <<= 1, skip <<= 1) {
  29967. for (var val = 0; val < n; ++val) {
  29968. if (lengths[val] === len) {
  29969. // bit-reverse the code
  29970. var code2 = 0;
  29971. var t = code;
  29972. for (i = 0; i < len; ++i) {
  29973. code2 = (code2 << 1) | (t & 1);
  29974. t >>= 1;
  29975. }
  29976. // fill the table entries
  29977. for (i = code2; i < size; i += skip) {
  29978. codes[i] = (len << 16) | val;
  29979. }
  29980. ++code;
  29981. }
  29982. }
  29983. }
  29984. return [codes, maxLen];
  29985. };
  29986. FlateStream.prototype.readBlock = function FlateStream_readBlock() {
  29987. var buffer, len;
  29988. var str = this.str;
  29989. // read block header
  29990. var hdr = this.getBits(3);
  29991. if (hdr & 1) {
  29992. this.eof = true;
  29993. }
  29994. hdr >>= 1;
  29995. if (hdr === 0) { // uncompressed block
  29996. var b;
  29997. if ((b = str.getByte()) === -1) {
  29998. error('Bad block header in flate stream');
  29999. }
  30000. var blockLen = b;
  30001. if ((b = str.getByte()) === -1) {
  30002. error('Bad block header in flate stream');
  30003. }
  30004. blockLen |= (b << 8);
  30005. if ((b = str.getByte()) === -1) {
  30006. error('Bad block header in flate stream');
  30007. }
  30008. var check = b;
  30009. if ((b = str.getByte()) === -1) {
  30010. error('Bad block header in flate stream');
  30011. }
  30012. check |= (b << 8);
  30013. if (check !== (~blockLen & 0xffff) &&
  30014. (blockLen !== 0 || check !== 0)) {
  30015. // Ignoring error for bad "empty" block (see issue 1277)
  30016. error('Bad uncompressed block length in flate stream');
  30017. }
  30018. this.codeBuf = 0;
  30019. this.codeSize = 0;
  30020. var bufferLength = this.bufferLength;
  30021. buffer = this.ensureBuffer(bufferLength + blockLen);
  30022. var end = bufferLength + blockLen;
  30023. this.bufferLength = end;
  30024. if (blockLen === 0) {
  30025. if (str.peekByte() === -1) {
  30026. this.eof = true;
  30027. }
  30028. } else {
  30029. for (var n = bufferLength; n < end; ++n) {
  30030. if ((b = str.getByte()) === -1) {
  30031. this.eof = true;
  30032. break;
  30033. }
  30034. buffer[n] = b;
  30035. }
  30036. }
  30037. return;
  30038. }
  30039. var litCodeTable;
  30040. var distCodeTable;
  30041. if (hdr === 1) { // compressed block, fixed codes
  30042. litCodeTable = fixedLitCodeTab;
  30043. distCodeTable = fixedDistCodeTab;
  30044. } else if (hdr === 2) { // compressed block, dynamic codes
  30045. var numLitCodes = this.getBits(5) + 257;
  30046. var numDistCodes = this.getBits(5) + 1;
  30047. var numCodeLenCodes = this.getBits(4) + 4;
  30048. // build the code lengths code table
  30049. var codeLenCodeLengths = new Uint8Array(codeLenCodeMap.length);
  30050. var i;
  30051. for (i = 0; i < numCodeLenCodes; ++i) {
  30052. codeLenCodeLengths[codeLenCodeMap[i]] = this.getBits(3);
  30053. }
  30054. var codeLenCodeTab = this.generateHuffmanTable(codeLenCodeLengths);
  30055. // build the literal and distance code tables
  30056. len = 0;
  30057. i = 0;
  30058. var codes = numLitCodes + numDistCodes;
  30059. var codeLengths = new Uint8Array(codes);
  30060. var bitsLength, bitsOffset, what;
  30061. while (i < codes) {
  30062. var code = this.getCode(codeLenCodeTab);
  30063. if (code === 16) {
  30064. bitsLength = 2; bitsOffset = 3; what = len;
  30065. } else if (code === 17) {
  30066. bitsLength = 3; bitsOffset = 3; what = (len = 0);
  30067. } else if (code === 18) {
  30068. bitsLength = 7; bitsOffset = 11; what = (len = 0);
  30069. } else {
  30070. codeLengths[i++] = len = code;
  30071. continue;
  30072. }
  30073. var repeatLength = this.getBits(bitsLength) + bitsOffset;
  30074. while (repeatLength-- > 0) {
  30075. codeLengths[i++] = what;
  30076. }
  30077. }
  30078. litCodeTable =
  30079. this.generateHuffmanTable(codeLengths.subarray(0, numLitCodes));
  30080. distCodeTable =
  30081. this.generateHuffmanTable(codeLengths.subarray(numLitCodes, codes));
  30082. } else {
  30083. error('Unknown block type in flate stream');
  30084. }
  30085. buffer = this.buffer;
  30086. var limit = buffer ? buffer.length : 0;
  30087. var pos = this.bufferLength;
  30088. while (true) {
  30089. var code1 = this.getCode(litCodeTable);
  30090. if (code1 < 256) {
  30091. if (pos + 1 >= limit) {
  30092. buffer = this.ensureBuffer(pos + 1);
  30093. limit = buffer.length;
  30094. }
  30095. buffer[pos++] = code1;
  30096. continue;
  30097. }
  30098. if (code1 === 256) {
  30099. this.bufferLength = pos;
  30100. return;
  30101. }
  30102. code1 -= 257;
  30103. code1 = lengthDecode[code1];
  30104. var code2 = code1 >> 16;
  30105. if (code2 > 0) {
  30106. code2 = this.getBits(code2);
  30107. }
  30108. len = (code1 & 0xffff) + code2;
  30109. code1 = this.getCode(distCodeTable);
  30110. code1 = distDecode[code1];
  30111. code2 = code1 >> 16;
  30112. if (code2 > 0) {
  30113. code2 = this.getBits(code2);
  30114. }
  30115. var dist = (code1 & 0xffff) + code2;
  30116. if (pos + len >= limit) {
  30117. buffer = this.ensureBuffer(pos + len);
  30118. limit = buffer.length;
  30119. }
  30120. for (var k = 0; k < len; ++k, ++pos) {
  30121. buffer[pos] = buffer[pos - dist];
  30122. }
  30123. }
  30124. };
  30125. return FlateStream;
  30126. })();
  30127. var PredictorStream = (function PredictorStreamClosure() {
  30128. function PredictorStream(str, maybeLength, params) {
  30129. var predictor = this.predictor = params.get('Predictor') || 1;
  30130. if (predictor <= 1) {
  30131. return str; // no prediction
  30132. }
  30133. if (predictor !== 2 && (predictor < 10 || predictor > 15)) {
  30134. error('Unsupported predictor: ' + predictor);
  30135. }
  30136. if (predictor === 2) {
  30137. this.readBlock = this.readBlockTiff;
  30138. } else {
  30139. this.readBlock = this.readBlockPng;
  30140. }
  30141. this.str = str;
  30142. this.dict = str.dict;
  30143. var colors = this.colors = params.get('Colors') || 1;
  30144. var bits = this.bits = params.get('BitsPerComponent') || 8;
  30145. var columns = this.columns = params.get('Columns') || 1;
  30146. this.pixBytes = (colors * bits + 7) >> 3;
  30147. this.rowBytes = (columns * colors * bits + 7) >> 3;
  30148. DecodeStream.call(this, maybeLength);
  30149. return this;
  30150. }
  30151. PredictorStream.prototype = Object.create(DecodeStream.prototype);
  30152. PredictorStream.prototype.readBlockTiff =
  30153. function predictorStreamReadBlockTiff() {
  30154. var rowBytes = this.rowBytes;
  30155. var bufferLength = this.bufferLength;
  30156. var buffer = this.ensureBuffer(bufferLength + rowBytes);
  30157. var bits = this.bits;
  30158. var colors = this.colors;
  30159. var rawBytes = this.str.getBytes(rowBytes);
  30160. this.eof = !rawBytes.length;
  30161. if (this.eof) {
  30162. return;
  30163. }
  30164. var inbuf = 0, outbuf = 0;
  30165. var inbits = 0, outbits = 0;
  30166. var pos = bufferLength;
  30167. var i;
  30168. if (bits === 1) {
  30169. for (i = 0; i < rowBytes; ++i) {
  30170. var c = rawBytes[i];
  30171. inbuf = (inbuf << 8) | c;
  30172. // bitwise addition is exclusive or
  30173. // first shift inbuf and then add
  30174. buffer[pos++] = (c ^ (inbuf >> colors)) & 0xFF;
  30175. // truncate inbuf (assumes colors < 16)
  30176. inbuf &= 0xFFFF;
  30177. }
  30178. } else if (bits === 8) {
  30179. for (i = 0; i < colors; ++i) {
  30180. buffer[pos++] = rawBytes[i];
  30181. }
  30182. for (; i < rowBytes; ++i) {
  30183. buffer[pos] = buffer[pos - colors] + rawBytes[i];
  30184. pos++;
  30185. }
  30186. } else {
  30187. var compArray = new Uint8Array(colors + 1);
  30188. var bitMask = (1 << bits) - 1;
  30189. var j = 0, k = bufferLength;
  30190. var columns = this.columns;
  30191. for (i = 0; i < columns; ++i) {
  30192. for (var kk = 0; kk < colors; ++kk) {
  30193. if (inbits < bits) {
  30194. inbuf = (inbuf << 8) | (rawBytes[j++] & 0xFF);
  30195. inbits += 8;
  30196. }
  30197. compArray[kk] = (compArray[kk] +
  30198. (inbuf >> (inbits - bits))) & bitMask;
  30199. inbits -= bits;
  30200. outbuf = (outbuf << bits) | compArray[kk];
  30201. outbits += bits;
  30202. if (outbits >= 8) {
  30203. buffer[k++] = (outbuf >> (outbits - 8)) & 0xFF;
  30204. outbits -= 8;
  30205. }
  30206. }
  30207. }
  30208. if (outbits > 0) {
  30209. buffer[k++] = (outbuf << (8 - outbits)) +
  30210. (inbuf & ((1 << (8 - outbits)) - 1));
  30211. }
  30212. }
  30213. this.bufferLength += rowBytes;
  30214. };
  30215. PredictorStream.prototype.readBlockPng =
  30216. function predictorStreamReadBlockPng() {
  30217. var rowBytes = this.rowBytes;
  30218. var pixBytes = this.pixBytes;
  30219. var predictor = this.str.getByte();
  30220. var rawBytes = this.str.getBytes(rowBytes);
  30221. this.eof = !rawBytes.length;
  30222. if (this.eof) {
  30223. return;
  30224. }
  30225. var bufferLength = this.bufferLength;
  30226. var buffer = this.ensureBuffer(bufferLength + rowBytes);
  30227. var prevRow = buffer.subarray(bufferLength - rowBytes, bufferLength);
  30228. if (prevRow.length === 0) {
  30229. prevRow = new Uint8Array(rowBytes);
  30230. }
  30231. var i, j = bufferLength, up, c;
  30232. switch (predictor) {
  30233. case 0:
  30234. for (i = 0; i < rowBytes; ++i) {
  30235. buffer[j++] = rawBytes[i];
  30236. }
  30237. break;
  30238. case 1:
  30239. for (i = 0; i < pixBytes; ++i) {
  30240. buffer[j++] = rawBytes[i];
  30241. }
  30242. for (; i < rowBytes; ++i) {
  30243. buffer[j] = (buffer[j - pixBytes] + rawBytes[i]) & 0xFF;
  30244. j++;
  30245. }
  30246. break;
  30247. case 2:
  30248. for (i = 0; i < rowBytes; ++i) {
  30249. buffer[j++] = (prevRow[i] + rawBytes[i]) & 0xFF;
  30250. }
  30251. break;
  30252. case 3:
  30253. for (i = 0; i < pixBytes; ++i) {
  30254. buffer[j++] = (prevRow[i] >> 1) + rawBytes[i];
  30255. }
  30256. for (; i < rowBytes; ++i) {
  30257. buffer[j] = (((prevRow[i] + buffer[j - pixBytes]) >> 1) +
  30258. rawBytes[i]) & 0xFF;
  30259. j++;
  30260. }
  30261. break;
  30262. case 4:
  30263. // we need to save the up left pixels values. the simplest way
  30264. // is to create a new buffer
  30265. for (i = 0; i < pixBytes; ++i) {
  30266. up = prevRow[i];
  30267. c = rawBytes[i];
  30268. buffer[j++] = up + c;
  30269. }
  30270. for (; i < rowBytes; ++i) {
  30271. up = prevRow[i];
  30272. var upLeft = prevRow[i - pixBytes];
  30273. var left = buffer[j - pixBytes];
  30274. var p = left + up - upLeft;
  30275. var pa = p - left;
  30276. if (pa < 0) {
  30277. pa = -pa;
  30278. }
  30279. var pb = p - up;
  30280. if (pb < 0) {
  30281. pb = -pb;
  30282. }
  30283. var pc = p - upLeft;
  30284. if (pc < 0) {
  30285. pc = -pc;
  30286. }
  30287. c = rawBytes[i];
  30288. if (pa <= pb && pa <= pc) {
  30289. buffer[j++] = left + c;
  30290. } else if (pb <= pc) {
  30291. buffer[j++] = up + c;
  30292. } else {
  30293. buffer[j++] = upLeft + c;
  30294. }
  30295. }
  30296. break;
  30297. default:
  30298. error('Unsupported predictor: ' + predictor);
  30299. }
  30300. this.bufferLength += rowBytes;
  30301. };
  30302. return PredictorStream;
  30303. })();
  30304. /**
  30305. * Depending on the type of JPEG a JpegStream is handled in different ways. For
  30306. * JPEG's that are supported natively such as DeviceGray and DeviceRGB the image
  30307. * data is stored and then loaded by the browser. For unsupported JPEG's we use
  30308. * a library to decode these images and the stream behaves like all the other
  30309. * DecodeStreams.
  30310. */
  30311. var JpegStream = (function JpegStreamClosure() {
  30312. function JpegStream(stream, maybeLength, dict, xref) {
  30313. // Some images may contain 'junk' before the SOI (start-of-image) marker.
  30314. // Note: this seems to mainly affect inline images.
  30315. var ch;
  30316. while ((ch = stream.getByte()) !== -1) {
  30317. if (ch === 0xFF) { // Find the first byte of the SOI marker (0xFFD8).
  30318. stream.skip(-1); // Reset the stream position to the SOI.
  30319. break;
  30320. }
  30321. }
  30322. this.stream = stream;
  30323. this.maybeLength = maybeLength;
  30324. this.dict = dict;
  30325. DecodeStream.call(this, maybeLength);
  30326. }
  30327. JpegStream.prototype = Object.create(DecodeStream.prototype);
  30328. Object.defineProperty(JpegStream.prototype, 'bytes', {
  30329. get: function JpegStream_bytes() {
  30330. // If this.maybeLength is null, we'll get the entire stream.
  30331. return shadow(this, 'bytes', this.stream.getBytes(this.maybeLength));
  30332. },
  30333. configurable: true
  30334. });
  30335. JpegStream.prototype.ensureBuffer = function JpegStream_ensureBuffer(req) {
  30336. if (this.bufferLength) {
  30337. return;
  30338. }
  30339. try {
  30340. var jpegImage = new JpegImage();
  30341. // checking if values needs to be transformed before conversion
  30342. if (this.forceRGB && this.dict && isArray(this.dict.get('Decode'))) {
  30343. var decodeArr = this.dict.get('Decode');
  30344. var bitsPerComponent = this.dict.get('BitsPerComponent') || 8;
  30345. var decodeArrLength = decodeArr.length;
  30346. var transform = new Int32Array(decodeArrLength);
  30347. var transformNeeded = false;
  30348. var maxValue = (1 << bitsPerComponent) - 1;
  30349. for (var i = 0; i < decodeArrLength; i += 2) {
  30350. transform[i] = ((decodeArr[i + 1] - decodeArr[i]) * 256) | 0;
  30351. transform[i + 1] = (decodeArr[i] * maxValue) | 0;
  30352. if (transform[i] !== 256 || transform[i + 1] !== 0) {
  30353. transformNeeded = true;
  30354. }
  30355. }
  30356. if (transformNeeded) {
  30357. jpegImage.decodeTransform = transform;
  30358. }
  30359. }
  30360. jpegImage.parse(this.bytes);
  30361. var data = jpegImage.getData(this.drawWidth, this.drawHeight,
  30362. this.forceRGB);
  30363. this.buffer = data;
  30364. this.bufferLength = data.length;
  30365. this.eof = true;
  30366. } catch (e) {
  30367. error('JPEG error: ' + e);
  30368. }
  30369. };
  30370. JpegStream.prototype.getBytes = function JpegStream_getBytes(length) {
  30371. this.ensureBuffer();
  30372. return this.buffer;
  30373. };
  30374. JpegStream.prototype.getIR = function JpegStream_getIR() {
  30375. return PDFJS.createObjectURL(this.bytes, 'image/jpeg');
  30376. };
  30377. /**
  30378. * Checks if the image can be decoded and displayed by the browser without any
  30379. * further processing such as color space conversions.
  30380. */
  30381. JpegStream.prototype.isNativelySupported =
  30382. function JpegStream_isNativelySupported(xref, res) {
  30383. var cs = ColorSpace.parse(this.dict.get('ColorSpace', 'CS'), xref, res);
  30384. return cs.name === 'DeviceGray' || cs.name === 'DeviceRGB';
  30385. };
  30386. /**
  30387. * Checks if the image can be decoded by the browser.
  30388. */
  30389. JpegStream.prototype.isNativelyDecodable =
  30390. function JpegStream_isNativelyDecodable(xref, res) {
  30391. var cs = ColorSpace.parse(this.dict.get('ColorSpace', 'CS'), xref, res);
  30392. var numComps = cs.numComps;
  30393. return numComps === 1 || numComps === 3;
  30394. };
  30395. return JpegStream;
  30396. })();
  30397. /**
  30398. * For JPEG 2000's we use a library to decode these images and
  30399. * the stream behaves like all the other DecodeStreams.
  30400. */
  30401. var JpxStream = (function JpxStreamClosure() {
  30402. function JpxStream(stream, maybeLength, dict) {
  30403. this.stream = stream;
  30404. this.maybeLength = maybeLength;
  30405. this.dict = dict;
  30406. DecodeStream.call(this, maybeLength);
  30407. }
  30408. JpxStream.prototype = Object.create(DecodeStream.prototype);
  30409. Object.defineProperty(JpxStream.prototype, 'bytes', {
  30410. get: function JpxStream_bytes() {
  30411. // If this.maybeLength is null, we'll get the entire stream.
  30412. return shadow(this, 'bytes', this.stream.getBytes(this.maybeLength));
  30413. },
  30414. configurable: true
  30415. });
  30416. JpxStream.prototype.ensureBuffer = function JpxStream_ensureBuffer(req) {
  30417. if (this.bufferLength) {
  30418. return;
  30419. }
  30420. var jpxImage = new JpxImage();
  30421. jpxImage.parse(this.bytes);
  30422. var width = jpxImage.width;
  30423. var height = jpxImage.height;
  30424. var componentsCount = jpxImage.componentsCount;
  30425. var tileCount = jpxImage.tiles.length;
  30426. if (tileCount === 1) {
  30427. this.buffer = jpxImage.tiles[0].items;
  30428. } else {
  30429. var data = new Uint8Array(width * height * componentsCount);
  30430. for (var k = 0; k < tileCount; k++) {
  30431. var tileComponents = jpxImage.tiles[k];
  30432. var tileWidth = tileComponents.width;
  30433. var tileHeight = tileComponents.height;
  30434. var tileLeft = tileComponents.left;
  30435. var tileTop = tileComponents.top;
  30436. var src = tileComponents.items;
  30437. var srcPosition = 0;
  30438. var dataPosition = (width * tileTop + tileLeft) * componentsCount;
  30439. var imgRowSize = width * componentsCount;
  30440. var tileRowSize = tileWidth * componentsCount;
  30441. for (var j = 0; j < tileHeight; j++) {
  30442. var rowBytes = src.subarray(srcPosition, srcPosition + tileRowSize);
  30443. data.set(rowBytes, dataPosition);
  30444. srcPosition += tileRowSize;
  30445. dataPosition += imgRowSize;
  30446. }
  30447. }
  30448. this.buffer = data;
  30449. }
  30450. this.bufferLength = this.buffer.length;
  30451. this.eof = true;
  30452. };
  30453. return JpxStream;
  30454. })();
  30455. /**
  30456. * For JBIG2's we use a library to decode these images and
  30457. * the stream behaves like all the other DecodeStreams.
  30458. */
  30459. var Jbig2Stream = (function Jbig2StreamClosure() {
  30460. function Jbig2Stream(stream, maybeLength, dict) {
  30461. this.stream = stream;
  30462. this.maybeLength = maybeLength;
  30463. this.dict = dict;
  30464. DecodeStream.call(this, maybeLength);
  30465. }
  30466. Jbig2Stream.prototype = Object.create(DecodeStream.prototype);
  30467. Object.defineProperty(Jbig2Stream.prototype, 'bytes', {
  30468. get: function Jbig2Stream_bytes() {
  30469. // If this.maybeLength is null, we'll get the entire stream.
  30470. return shadow(this, 'bytes', this.stream.getBytes(this.maybeLength));
  30471. },
  30472. configurable: true
  30473. });
  30474. Jbig2Stream.prototype.ensureBuffer = function Jbig2Stream_ensureBuffer(req) {
  30475. if (this.bufferLength) {
  30476. return;
  30477. }
  30478. var jbig2Image = new Jbig2Image();
  30479. var chunks = [], xref = this.dict.xref;
  30480. var decodeParams = xref.fetchIfRef(this.dict.get('DecodeParms'));
  30481. // According to the PDF specification, DecodeParms can be either
  30482. // a dictionary, or an array whose elements are dictionaries.
  30483. if (isArray(decodeParams)) {
  30484. if (decodeParams.length > 1) {
  30485. warn('JBIG2 - \'DecodeParms\' array with multiple elements ' +
  30486. 'not supported.');
  30487. }
  30488. decodeParams = xref.fetchIfRef(decodeParams[0]);
  30489. }
  30490. if (decodeParams && decodeParams.has('JBIG2Globals')) {
  30491. var globalsStream = decodeParams.get('JBIG2Globals');
  30492. var globals = globalsStream.getBytes();
  30493. chunks.push({data: globals, start: 0, end: globals.length});
  30494. }
  30495. chunks.push({data: this.bytes, start: 0, end: this.bytes.length});
  30496. var data = jbig2Image.parseChunks(chunks);
  30497. var dataLength = data.length;
  30498. // JBIG2 had black as 1 and white as 0, inverting the colors
  30499. for (var i = 0; i < dataLength; i++) {
  30500. data[i] ^= 0xFF;
  30501. }
  30502. this.buffer = data;
  30503. this.bufferLength = dataLength;
  30504. this.eof = true;
  30505. };
  30506. return Jbig2Stream;
  30507. })();
  30508. var DecryptStream = (function DecryptStreamClosure() {
  30509. function DecryptStream(str, maybeLength, decrypt) {
  30510. this.str = str;
  30511. this.dict = str.dict;
  30512. this.decrypt = decrypt;
  30513. this.nextChunk = null;
  30514. this.initialized = false;
  30515. DecodeStream.call(this, maybeLength);
  30516. }
  30517. var chunkSize = 512;
  30518. DecryptStream.prototype = Object.create(DecodeStream.prototype);
  30519. DecryptStream.prototype.readBlock = function DecryptStream_readBlock() {
  30520. var chunk;
  30521. if (this.initialized) {
  30522. chunk = this.nextChunk;
  30523. } else {
  30524. chunk = this.str.getBytes(chunkSize);
  30525. this.initialized = true;
  30526. }
  30527. if (!chunk || chunk.length === 0) {
  30528. this.eof = true;
  30529. return;
  30530. }
  30531. this.nextChunk = this.str.getBytes(chunkSize);
  30532. var hasMoreData = this.nextChunk && this.nextChunk.length > 0;
  30533. var decrypt = this.decrypt;
  30534. chunk = decrypt(chunk, !hasMoreData);
  30535. var bufferLength = this.bufferLength;
  30536. var i, n = chunk.length;
  30537. var buffer = this.ensureBuffer(bufferLength + n);
  30538. for (i = 0; i < n; i++) {
  30539. buffer[bufferLength++] = chunk[i];
  30540. }
  30541. this.bufferLength = bufferLength;
  30542. };
  30543. return DecryptStream;
  30544. })();
  30545. var Ascii85Stream = (function Ascii85StreamClosure() {
  30546. function Ascii85Stream(str, maybeLength) {
  30547. this.str = str;
  30548. this.dict = str.dict;
  30549. this.input = new Uint8Array(5);
  30550. // Most streams increase in size when decoded, but Ascii85 streams
  30551. // typically shrink by ~20%.
  30552. if (maybeLength) {
  30553. maybeLength = 0.8 * maybeLength;
  30554. }
  30555. DecodeStream.call(this, maybeLength);
  30556. }
  30557. Ascii85Stream.prototype = Object.create(DecodeStream.prototype);
  30558. Ascii85Stream.prototype.readBlock = function Ascii85Stream_readBlock() {
  30559. var TILDA_CHAR = 0x7E; // '~'
  30560. var Z_LOWER_CHAR = 0x7A; // 'z'
  30561. var EOF = -1;
  30562. var str = this.str;
  30563. var c = str.getByte();
  30564. while (Lexer.isSpace(c)) {
  30565. c = str.getByte();
  30566. }
  30567. if (c === EOF || c === TILDA_CHAR) {
  30568. this.eof = true;
  30569. return;
  30570. }
  30571. var bufferLength = this.bufferLength, buffer;
  30572. var i;
  30573. // special code for z
  30574. if (c === Z_LOWER_CHAR) {
  30575. buffer = this.ensureBuffer(bufferLength + 4);
  30576. for (i = 0; i < 4; ++i) {
  30577. buffer[bufferLength + i] = 0;
  30578. }
  30579. this.bufferLength += 4;
  30580. } else {
  30581. var input = this.input;
  30582. input[0] = c;
  30583. for (i = 1; i < 5; ++i) {
  30584. c = str.getByte();
  30585. while (Lexer.isSpace(c)) {
  30586. c = str.getByte();
  30587. }
  30588. input[i] = c;
  30589. if (c === EOF || c === TILDA_CHAR) {
  30590. break;
  30591. }
  30592. }
  30593. buffer = this.ensureBuffer(bufferLength + i - 1);
  30594. this.bufferLength += i - 1;
  30595. // partial ending;
  30596. if (i < 5) {
  30597. for (; i < 5; ++i) {
  30598. input[i] = 0x21 + 84;
  30599. }
  30600. this.eof = true;
  30601. }
  30602. var t = 0;
  30603. for (i = 0; i < 5; ++i) {
  30604. t = t * 85 + (input[i] - 0x21);
  30605. }
  30606. for (i = 3; i >= 0; --i) {
  30607. buffer[bufferLength + i] = t & 0xFF;
  30608. t >>= 8;
  30609. }
  30610. }
  30611. };
  30612. return Ascii85Stream;
  30613. })();
  30614. var AsciiHexStream = (function AsciiHexStreamClosure() {
  30615. function AsciiHexStream(str, maybeLength) {
  30616. this.str = str;
  30617. this.dict = str.dict;
  30618. this.firstDigit = -1;
  30619. // Most streams increase in size when decoded, but AsciiHex streams shrink
  30620. // by 50%.
  30621. if (maybeLength) {
  30622. maybeLength = 0.5 * maybeLength;
  30623. }
  30624. DecodeStream.call(this, maybeLength);
  30625. }
  30626. AsciiHexStream.prototype = Object.create(DecodeStream.prototype);
  30627. AsciiHexStream.prototype.readBlock = function AsciiHexStream_readBlock() {
  30628. var UPSTREAM_BLOCK_SIZE = 8000;
  30629. var bytes = this.str.getBytes(UPSTREAM_BLOCK_SIZE);
  30630. if (!bytes.length) {
  30631. this.eof = true;
  30632. return;
  30633. }
  30634. var maxDecodeLength = (bytes.length + 1) >> 1;
  30635. var buffer = this.ensureBuffer(this.bufferLength + maxDecodeLength);
  30636. var bufferLength = this.bufferLength;
  30637. var firstDigit = this.firstDigit;
  30638. for (var i = 0, ii = bytes.length; i < ii; i++) {
  30639. var ch = bytes[i], digit;
  30640. if (ch >= 0x30 && ch <= 0x39) { // '0'-'9'
  30641. digit = ch & 0x0F;
  30642. } else if ((ch >= 0x41 && ch <= 0x46) || (ch >= 0x61 && ch <= 0x66)) {
  30643. // 'A'-'Z', 'a'-'z'
  30644. digit = (ch & 0x0F) + 9;
  30645. } else if (ch === 0x3E) { // '>'
  30646. this.eof = true;
  30647. break;
  30648. } else { // probably whitespace
  30649. continue; // ignoring
  30650. }
  30651. if (firstDigit < 0) {
  30652. firstDigit = digit;
  30653. } else {
  30654. buffer[bufferLength++] = (firstDigit << 4) | digit;
  30655. firstDigit = -1;
  30656. }
  30657. }
  30658. if (firstDigit >= 0 && this.eof) {
  30659. // incomplete byte
  30660. buffer[bufferLength++] = (firstDigit << 4);
  30661. firstDigit = -1;
  30662. }
  30663. this.firstDigit = firstDigit;
  30664. this.bufferLength = bufferLength;
  30665. };
  30666. return AsciiHexStream;
  30667. })();
  30668. var RunLengthStream = (function RunLengthStreamClosure() {
  30669. function RunLengthStream(str, maybeLength) {
  30670. this.str = str;
  30671. this.dict = str.dict;
  30672. DecodeStream.call(this, maybeLength);
  30673. }
  30674. RunLengthStream.prototype = Object.create(DecodeStream.prototype);
  30675. RunLengthStream.prototype.readBlock = function RunLengthStream_readBlock() {
  30676. // The repeatHeader has following format. The first byte defines type of run
  30677. // and amount of bytes to repeat/copy: n = 0 through 127 - copy next n bytes
  30678. // (in addition to the second byte from the header), n = 129 through 255 -
  30679. // duplicate the second byte from the header (257 - n) times, n = 128 - end.
  30680. var repeatHeader = this.str.getBytes(2);
  30681. if (!repeatHeader || repeatHeader.length < 2 || repeatHeader[0] === 128) {
  30682. this.eof = true;
  30683. return;
  30684. }
  30685. var buffer;
  30686. var bufferLength = this.bufferLength;
  30687. var n = repeatHeader[0];
  30688. if (n < 128) {
  30689. // copy n bytes
  30690. buffer = this.ensureBuffer(bufferLength + n + 1);
  30691. buffer[bufferLength++] = repeatHeader[1];
  30692. if (n > 0) {
  30693. var source = this.str.getBytes(n);
  30694. buffer.set(source, bufferLength);
  30695. bufferLength += n;
  30696. }
  30697. } else {
  30698. n = 257 - n;
  30699. var b = repeatHeader[1];
  30700. buffer = this.ensureBuffer(bufferLength + n + 1);
  30701. for (var i = 0; i < n; i++) {
  30702. buffer[bufferLength++] = b;
  30703. }
  30704. }
  30705. this.bufferLength = bufferLength;
  30706. };
  30707. return RunLengthStream;
  30708. })();
  30709. var CCITTFaxStream = (function CCITTFaxStreamClosure() {
  30710. var ccittEOL = -2;
  30711. var twoDimPass = 0;
  30712. var twoDimHoriz = 1;
  30713. var twoDimVert0 = 2;
  30714. var twoDimVertR1 = 3;
  30715. var twoDimVertL1 = 4;
  30716. var twoDimVertR2 = 5;
  30717. var twoDimVertL2 = 6;
  30718. var twoDimVertR3 = 7;
  30719. var twoDimVertL3 = 8;
  30720. var twoDimTable = [
  30721. [-1, -1], [-1, -1], // 000000x
  30722. [7, twoDimVertL3], // 0000010
  30723. [7, twoDimVertR3], // 0000011
  30724. [6, twoDimVertL2], [6, twoDimVertL2], // 000010x
  30725. [6, twoDimVertR2], [6, twoDimVertR2], // 000011x
  30726. [4, twoDimPass], [4, twoDimPass], // 0001xxx
  30727. [4, twoDimPass], [4, twoDimPass],
  30728. [4, twoDimPass], [4, twoDimPass],
  30729. [4, twoDimPass], [4, twoDimPass],
  30730. [3, twoDimHoriz], [3, twoDimHoriz], // 001xxxx
  30731. [3, twoDimHoriz], [3, twoDimHoriz],
  30732. [3, twoDimHoriz], [3, twoDimHoriz],
  30733. [3, twoDimHoriz], [3, twoDimHoriz],
  30734. [3, twoDimHoriz], [3, twoDimHoriz],
  30735. [3, twoDimHoriz], [3, twoDimHoriz],
  30736. [3, twoDimHoriz], [3, twoDimHoriz],
  30737. [3, twoDimHoriz], [3, twoDimHoriz],
  30738. [3, twoDimVertL1], [3, twoDimVertL1], // 010xxxx
  30739. [3, twoDimVertL1], [3, twoDimVertL1],
  30740. [3, twoDimVertL1], [3, twoDimVertL1],
  30741. [3, twoDimVertL1], [3, twoDimVertL1],
  30742. [3, twoDimVertL1], [3, twoDimVertL1],
  30743. [3, twoDimVertL1], [3, twoDimVertL1],
  30744. [3, twoDimVertL1], [3, twoDimVertL1],
  30745. [3, twoDimVertL1], [3, twoDimVertL1],
  30746. [3, twoDimVertR1], [3, twoDimVertR1], // 011xxxx
  30747. [3, twoDimVertR1], [3, twoDimVertR1],
  30748. [3, twoDimVertR1], [3, twoDimVertR1],
  30749. [3, twoDimVertR1], [3, twoDimVertR1],
  30750. [3, twoDimVertR1], [3, twoDimVertR1],
  30751. [3, twoDimVertR1], [3, twoDimVertR1],
  30752. [3, twoDimVertR1], [3, twoDimVertR1],
  30753. [3, twoDimVertR1], [3, twoDimVertR1],
  30754. [1, twoDimVert0], [1, twoDimVert0], // 1xxxxxx
  30755. [1, twoDimVert0], [1, twoDimVert0],
  30756. [1, twoDimVert0], [1, twoDimVert0],
  30757. [1, twoDimVert0], [1, twoDimVert0],
  30758. [1, twoDimVert0], [1, twoDimVert0],
  30759. [1, twoDimVert0], [1, twoDimVert0],
  30760. [1, twoDimVert0], [1, twoDimVert0],
  30761. [1, twoDimVert0], [1, twoDimVert0],
  30762. [1, twoDimVert0], [1, twoDimVert0],
  30763. [1, twoDimVert0], [1, twoDimVert0],
  30764. [1, twoDimVert0], [1, twoDimVert0],
  30765. [1, twoDimVert0], [1, twoDimVert0],
  30766. [1, twoDimVert0], [1, twoDimVert0],
  30767. [1, twoDimVert0], [1, twoDimVert0],
  30768. [1, twoDimVert0], [1, twoDimVert0],
  30769. [1, twoDimVert0], [1, twoDimVert0],
  30770. [1, twoDimVert0], [1, twoDimVert0],
  30771. [1, twoDimVert0], [1, twoDimVert0],
  30772. [1, twoDimVert0], [1, twoDimVert0],
  30773. [1, twoDimVert0], [1, twoDimVert0],
  30774. [1, twoDimVert0], [1, twoDimVert0],
  30775. [1, twoDimVert0], [1, twoDimVert0],
  30776. [1, twoDimVert0], [1, twoDimVert0],
  30777. [1, twoDimVert0], [1, twoDimVert0],
  30778. [1, twoDimVert0], [1, twoDimVert0],
  30779. [1, twoDimVert0], [1, twoDimVert0],
  30780. [1, twoDimVert0], [1, twoDimVert0],
  30781. [1, twoDimVert0], [1, twoDimVert0],
  30782. [1, twoDimVert0], [1, twoDimVert0],
  30783. [1, twoDimVert0], [1, twoDimVert0],
  30784. [1, twoDimVert0], [1, twoDimVert0],
  30785. [1, twoDimVert0], [1, twoDimVert0]
  30786. ];
  30787. var whiteTable1 = [
  30788. [-1, -1], // 00000
  30789. [12, ccittEOL], // 00001
  30790. [-1, -1], [-1, -1], // 0001x
  30791. [-1, -1], [-1, -1], [-1, -1], [-1, -1], // 001xx
  30792. [-1, -1], [-1, -1], [-1, -1], [-1, -1], // 010xx
  30793. [-1, -1], [-1, -1], [-1, -1], [-1, -1], // 011xx
  30794. [11, 1792], [11, 1792], // 1000x
  30795. [12, 1984], // 10010
  30796. [12, 2048], // 10011
  30797. [12, 2112], // 10100
  30798. [12, 2176], // 10101
  30799. [12, 2240], // 10110
  30800. [12, 2304], // 10111
  30801. [11, 1856], [11, 1856], // 1100x
  30802. [11, 1920], [11, 1920], // 1101x
  30803. [12, 2368], // 11100
  30804. [12, 2432], // 11101
  30805. [12, 2496], // 11110
  30806. [12, 2560] // 11111
  30807. ];
  30808. var whiteTable2 = [
  30809. [-1, -1], [-1, -1], [-1, -1], [-1, -1], // 0000000xx
  30810. [8, 29], [8, 29], // 00000010x
  30811. [8, 30], [8, 30], // 00000011x
  30812. [8, 45], [8, 45], // 00000100x
  30813. [8, 46], [8, 46], // 00000101x
  30814. [7, 22], [7, 22], [7, 22], [7, 22], // 0000011xx
  30815. [7, 23], [7, 23], [7, 23], [7, 23], // 0000100xx
  30816. [8, 47], [8, 47], // 00001010x
  30817. [8, 48], [8, 48], // 00001011x
  30818. [6, 13], [6, 13], [6, 13], [6, 13], // 000011xxx
  30819. [6, 13], [6, 13], [6, 13], [6, 13],
  30820. [7, 20], [7, 20], [7, 20], [7, 20], // 0001000xx
  30821. [8, 33], [8, 33], // 00010010x
  30822. [8, 34], [8, 34], // 00010011x
  30823. [8, 35], [8, 35], // 00010100x
  30824. [8, 36], [8, 36], // 00010101x
  30825. [8, 37], [8, 37], // 00010110x
  30826. [8, 38], [8, 38], // 00010111x
  30827. [7, 19], [7, 19], [7, 19], [7, 19], // 0001100xx
  30828. [8, 31], [8, 31], // 00011010x
  30829. [8, 32], [8, 32], // 00011011x
  30830. [6, 1], [6, 1], [6, 1], [6, 1], // 000111xxx
  30831. [6, 1], [6, 1], [6, 1], [6, 1],
  30832. [6, 12], [6, 12], [6, 12], [6, 12], // 001000xxx
  30833. [6, 12], [6, 12], [6, 12], [6, 12],
  30834. [8, 53], [8, 53], // 00100100x
  30835. [8, 54], [8, 54], // 00100101x
  30836. [7, 26], [7, 26], [7, 26], [7, 26], // 0010011xx
  30837. [8, 39], [8, 39], // 00101000x
  30838. [8, 40], [8, 40], // 00101001x
  30839. [8, 41], [8, 41], // 00101010x
  30840. [8, 42], [8, 42], // 00101011x
  30841. [8, 43], [8, 43], // 00101100x
  30842. [8, 44], [8, 44], // 00101101x
  30843. [7, 21], [7, 21], [7, 21], [7, 21], // 0010111xx
  30844. [7, 28], [7, 28], [7, 28], [7, 28], // 0011000xx
  30845. [8, 61], [8, 61], // 00110010x
  30846. [8, 62], [8, 62], // 00110011x
  30847. [8, 63], [8, 63], // 00110100x
  30848. [8, 0], [8, 0], // 00110101x
  30849. [8, 320], [8, 320], // 00110110x
  30850. [8, 384], [8, 384], // 00110111x
  30851. [5, 10], [5, 10], [5, 10], [5, 10], // 00111xxxx
  30852. [5, 10], [5, 10], [5, 10], [5, 10],
  30853. [5, 10], [5, 10], [5, 10], [5, 10],
  30854. [5, 10], [5, 10], [5, 10], [5, 10],
  30855. [5, 11], [5, 11], [5, 11], [5, 11], // 01000xxxx
  30856. [5, 11], [5, 11], [5, 11], [5, 11],
  30857. [5, 11], [5, 11], [5, 11], [5, 11],
  30858. [5, 11], [5, 11], [5, 11], [5, 11],
  30859. [7, 27], [7, 27], [7, 27], [7, 27], // 0100100xx
  30860. [8, 59], [8, 59], // 01001010x
  30861. [8, 60], [8, 60], // 01001011x
  30862. [9, 1472], // 010011000
  30863. [9, 1536], // 010011001
  30864. [9, 1600], // 010011010
  30865. [9, 1728], // 010011011
  30866. [7, 18], [7, 18], [7, 18], [7, 18], // 0100111xx
  30867. [7, 24], [7, 24], [7, 24], [7, 24], // 0101000xx
  30868. [8, 49], [8, 49], // 01010010x
  30869. [8, 50], [8, 50], // 01010011x
  30870. [8, 51], [8, 51], // 01010100x
  30871. [8, 52], [8, 52], // 01010101x
  30872. [7, 25], [7, 25], [7, 25], [7, 25], // 0101011xx
  30873. [8, 55], [8, 55], // 01011000x
  30874. [8, 56], [8, 56], // 01011001x
  30875. [8, 57], [8, 57], // 01011010x
  30876. [8, 58], [8, 58], // 01011011x
  30877. [6, 192], [6, 192], [6, 192], [6, 192], // 010111xxx
  30878. [6, 192], [6, 192], [6, 192], [6, 192],
  30879. [6, 1664], [6, 1664], [6, 1664], [6, 1664], // 011000xxx
  30880. [6, 1664], [6, 1664], [6, 1664], [6, 1664],
  30881. [8, 448], [8, 448], // 01100100x
  30882. [8, 512], [8, 512], // 01100101x
  30883. [9, 704], // 011001100
  30884. [9, 768], // 011001101
  30885. [8, 640], [8, 640], // 01100111x
  30886. [8, 576], [8, 576], // 01101000x
  30887. [9, 832], // 011010010
  30888. [9, 896], // 011010011
  30889. [9, 960], // 011010100
  30890. [9, 1024], // 011010101
  30891. [9, 1088], // 011010110
  30892. [9, 1152], // 011010111
  30893. [9, 1216], // 011011000
  30894. [9, 1280], // 011011001
  30895. [9, 1344], // 011011010
  30896. [9, 1408], // 011011011
  30897. [7, 256], [7, 256], [7, 256], [7, 256], // 0110111xx
  30898. [4, 2], [4, 2], [4, 2], [4, 2], // 0111xxxxx
  30899. [4, 2], [4, 2], [4, 2], [4, 2],
  30900. [4, 2], [4, 2], [4, 2], [4, 2],
  30901. [4, 2], [4, 2], [4, 2], [4, 2],
  30902. [4, 2], [4, 2], [4, 2], [4, 2],
  30903. [4, 2], [4, 2], [4, 2], [4, 2],
  30904. [4, 2], [4, 2], [4, 2], [4, 2],
  30905. [4, 2], [4, 2], [4, 2], [4, 2],
  30906. [4, 3], [4, 3], [4, 3], [4, 3], // 1000xxxxx
  30907. [4, 3], [4, 3], [4, 3], [4, 3],
  30908. [4, 3], [4, 3], [4, 3], [4, 3],
  30909. [4, 3], [4, 3], [4, 3], [4, 3],
  30910. [4, 3], [4, 3], [4, 3], [4, 3],
  30911. [4, 3], [4, 3], [4, 3], [4, 3],
  30912. [4, 3], [4, 3], [4, 3], [4, 3],
  30913. [4, 3], [4, 3], [4, 3], [4, 3],
  30914. [5, 128], [5, 128], [5, 128], [5, 128], // 10010xxxx
  30915. [5, 128], [5, 128], [5, 128], [5, 128],
  30916. [5, 128], [5, 128], [5, 128], [5, 128],
  30917. [5, 128], [5, 128], [5, 128], [5, 128],
  30918. [5, 8], [5, 8], [5, 8], [5, 8], // 10011xxxx
  30919. [5, 8], [5, 8], [5, 8], [5, 8],
  30920. [5, 8], [5, 8], [5, 8], [5, 8],
  30921. [5, 8], [5, 8], [5, 8], [5, 8],
  30922. [5, 9], [5, 9], [5, 9], [5, 9], // 10100xxxx
  30923. [5, 9], [5, 9], [5, 9], [5, 9],
  30924. [5, 9], [5, 9], [5, 9], [5, 9],
  30925. [5, 9], [5, 9], [5, 9], [5, 9],
  30926. [6, 16], [6, 16], [6, 16], [6, 16], // 101010xxx
  30927. [6, 16], [6, 16], [6, 16], [6, 16],
  30928. [6, 17], [6, 17], [6, 17], [6, 17], // 101011xxx
  30929. [6, 17], [6, 17], [6, 17], [6, 17],
  30930. [4, 4], [4, 4], [4, 4], [4, 4], // 1011xxxxx
  30931. [4, 4], [4, 4], [4, 4], [4, 4],
  30932. [4, 4], [4, 4], [4, 4], [4, 4],
  30933. [4, 4], [4, 4], [4, 4], [4, 4],
  30934. [4, 4], [4, 4], [4, 4], [4, 4],
  30935. [4, 4], [4, 4], [4, 4], [4, 4],
  30936. [4, 4], [4, 4], [4, 4], [4, 4],
  30937. [4, 4], [4, 4], [4, 4], [4, 4],
  30938. [4, 5], [4, 5], [4, 5], [4, 5], // 1100xxxxx
  30939. [4, 5], [4, 5], [4, 5], [4, 5],
  30940. [4, 5], [4, 5], [4, 5], [4, 5],
  30941. [4, 5], [4, 5], [4, 5], [4, 5],
  30942. [4, 5], [4, 5], [4, 5], [4, 5],
  30943. [4, 5], [4, 5], [4, 5], [4, 5],
  30944. [4, 5], [4, 5], [4, 5], [4, 5],
  30945. [4, 5], [4, 5], [4, 5], [4, 5],
  30946. [6, 14], [6, 14], [6, 14], [6, 14], // 110100xxx
  30947. [6, 14], [6, 14], [6, 14], [6, 14],
  30948. [6, 15], [6, 15], [6, 15], [6, 15], // 110101xxx
  30949. [6, 15], [6, 15], [6, 15], [6, 15],
  30950. [5, 64], [5, 64], [5, 64], [5, 64], // 11011xxxx
  30951. [5, 64], [5, 64], [5, 64], [5, 64],
  30952. [5, 64], [5, 64], [5, 64], [5, 64],
  30953. [5, 64], [5, 64], [5, 64], [5, 64],
  30954. [4, 6], [4, 6], [4, 6], [4, 6], // 1110xxxxx
  30955. [4, 6], [4, 6], [4, 6], [4, 6],
  30956. [4, 6], [4, 6], [4, 6], [4, 6],
  30957. [4, 6], [4, 6], [4, 6], [4, 6],
  30958. [4, 6], [4, 6], [4, 6], [4, 6],
  30959. [4, 6], [4, 6], [4, 6], [4, 6],
  30960. [4, 6], [4, 6], [4, 6], [4, 6],
  30961. [4, 6], [4, 6], [4, 6], [4, 6],
  30962. [4, 7], [4, 7], [4, 7], [4, 7], // 1111xxxxx
  30963. [4, 7], [4, 7], [4, 7], [4, 7],
  30964. [4, 7], [4, 7], [4, 7], [4, 7],
  30965. [4, 7], [4, 7], [4, 7], [4, 7],
  30966. [4, 7], [4, 7], [4, 7], [4, 7],
  30967. [4, 7], [4, 7], [4, 7], [4, 7],
  30968. [4, 7], [4, 7], [4, 7], [4, 7],
  30969. [4, 7], [4, 7], [4, 7], [4, 7]
  30970. ];
  30971. var blackTable1 = [
  30972. [-1, -1], [-1, -1], // 000000000000x
  30973. [12, ccittEOL], [12, ccittEOL], // 000000000001x
  30974. [-1, -1], [-1, -1], [-1, -1], [-1, -1], // 00000000001xx
  30975. [-1, -1], [-1, -1], [-1, -1], [-1, -1], // 00000000010xx
  30976. [-1, -1], [-1, -1], [-1, -1], [-1, -1], // 00000000011xx
  30977. [-1, -1], [-1, -1], [-1, -1], [-1, -1], // 00000000100xx
  30978. [-1, -1], [-1, -1], [-1, -1], [-1, -1], // 00000000101xx
  30979. [-1, -1], [-1, -1], [-1, -1], [-1, -1], // 00000000110xx
  30980. [-1, -1], [-1, -1], [-1, -1], [-1, -1], // 00000000111xx
  30981. [11, 1792], [11, 1792], [11, 1792], [11, 1792], // 00000001000xx
  30982. [12, 1984], [12, 1984], // 000000010010x
  30983. [12, 2048], [12, 2048], // 000000010011x
  30984. [12, 2112], [12, 2112], // 000000010100x
  30985. [12, 2176], [12, 2176], // 000000010101x
  30986. [12, 2240], [12, 2240], // 000000010110x
  30987. [12, 2304], [12, 2304], // 000000010111x
  30988. [11, 1856], [11, 1856], [11, 1856], [11, 1856], // 00000001100xx
  30989. [11, 1920], [11, 1920], [11, 1920], [11, 1920], // 00000001101xx
  30990. [12, 2368], [12, 2368], // 000000011100x
  30991. [12, 2432], [12, 2432], // 000000011101x
  30992. [12, 2496], [12, 2496], // 000000011110x
  30993. [12, 2560], [12, 2560], // 000000011111x
  30994. [10, 18], [10, 18], [10, 18], [10, 18], // 0000001000xxx
  30995. [10, 18], [10, 18], [10, 18], [10, 18],
  30996. [12, 52], [12, 52], // 000000100100x
  30997. [13, 640], // 0000001001010
  30998. [13, 704], // 0000001001011
  30999. [13, 768], // 0000001001100
  31000. [13, 832], // 0000001001101
  31001. [12, 55], [12, 55], // 000000100111x
  31002. [12, 56], [12, 56], // 000000101000x
  31003. [13, 1280], // 0000001010010
  31004. [13, 1344], // 0000001010011
  31005. [13, 1408], // 0000001010100
  31006. [13, 1472], // 0000001010101
  31007. [12, 59], [12, 59], // 000000101011x
  31008. [12, 60], [12, 60], // 000000101100x
  31009. [13, 1536], // 0000001011010
  31010. [13, 1600], // 0000001011011
  31011. [11, 24], [11, 24], [11, 24], [11, 24], // 00000010111xx
  31012. [11, 25], [11, 25], [11, 25], [11, 25], // 00000011000xx
  31013. [13, 1664], // 0000001100100
  31014. [13, 1728], // 0000001100101
  31015. [12, 320], [12, 320], // 000000110011x
  31016. [12, 384], [12, 384], // 000000110100x
  31017. [12, 448], [12, 448], // 000000110101x
  31018. [13, 512], // 0000001101100
  31019. [13, 576], // 0000001101101
  31020. [12, 53], [12, 53], // 000000110111x
  31021. [12, 54], [12, 54], // 000000111000x
  31022. [13, 896], // 0000001110010
  31023. [13, 960], // 0000001110011
  31024. [13, 1024], // 0000001110100
  31025. [13, 1088], // 0000001110101
  31026. [13, 1152], // 0000001110110
  31027. [13, 1216], // 0000001110111
  31028. [10, 64], [10, 64], [10, 64], [10, 64], // 0000001111xxx
  31029. [10, 64], [10, 64], [10, 64], [10, 64]
  31030. ];
  31031. var blackTable2 = [
  31032. [8, 13], [8, 13], [8, 13], [8, 13], // 00000100xxxx
  31033. [8, 13], [8, 13], [8, 13], [8, 13],
  31034. [8, 13], [8, 13], [8, 13], [8, 13],
  31035. [8, 13], [8, 13], [8, 13], [8, 13],
  31036. [11, 23], [11, 23], // 00000101000x
  31037. [12, 50], // 000001010010
  31038. [12, 51], // 000001010011
  31039. [12, 44], // 000001010100
  31040. [12, 45], // 000001010101
  31041. [12, 46], // 000001010110
  31042. [12, 47], // 000001010111
  31043. [12, 57], // 000001011000
  31044. [12, 58], // 000001011001
  31045. [12, 61], // 000001011010
  31046. [12, 256], // 000001011011
  31047. [10, 16], [10, 16], [10, 16], [10, 16], // 0000010111xx
  31048. [10, 17], [10, 17], [10, 17], [10, 17], // 0000011000xx
  31049. [12, 48], // 000001100100
  31050. [12, 49], // 000001100101
  31051. [12, 62], // 000001100110
  31052. [12, 63], // 000001100111
  31053. [12, 30], // 000001101000
  31054. [12, 31], // 000001101001
  31055. [12, 32], // 000001101010
  31056. [12, 33], // 000001101011
  31057. [12, 40], // 000001101100
  31058. [12, 41], // 000001101101
  31059. [11, 22], [11, 22], // 00000110111x
  31060. [8, 14], [8, 14], [8, 14], [8, 14], // 00000111xxxx
  31061. [8, 14], [8, 14], [8, 14], [8, 14],
  31062. [8, 14], [8, 14], [8, 14], [8, 14],
  31063. [8, 14], [8, 14], [8, 14], [8, 14],
  31064. [7, 10], [7, 10], [7, 10], [7, 10], // 0000100xxxxx
  31065. [7, 10], [7, 10], [7, 10], [7, 10],
  31066. [7, 10], [7, 10], [7, 10], [7, 10],
  31067. [7, 10], [7, 10], [7, 10], [7, 10],
  31068. [7, 10], [7, 10], [7, 10], [7, 10],
  31069. [7, 10], [7, 10], [7, 10], [7, 10],
  31070. [7, 10], [7, 10], [7, 10], [7, 10],
  31071. [7, 10], [7, 10], [7, 10], [7, 10],
  31072. [7, 11], [7, 11], [7, 11], [7, 11], // 0000101xxxxx
  31073. [7, 11], [7, 11], [7, 11], [7, 11],
  31074. [7, 11], [7, 11], [7, 11], [7, 11],
  31075. [7, 11], [7, 11], [7, 11], [7, 11],
  31076. [7, 11], [7, 11], [7, 11], [7, 11],
  31077. [7, 11], [7, 11], [7, 11], [7, 11],
  31078. [7, 11], [7, 11], [7, 11], [7, 11],
  31079. [7, 11], [7, 11], [7, 11], [7, 11],
  31080. [9, 15], [9, 15], [9, 15], [9, 15], // 000011000xxx
  31081. [9, 15], [9, 15], [9, 15], [9, 15],
  31082. [12, 128], // 000011001000
  31083. [12, 192], // 000011001001
  31084. [12, 26], // 000011001010
  31085. [12, 27], // 000011001011
  31086. [12, 28], // 000011001100
  31087. [12, 29], // 000011001101
  31088. [11, 19], [11, 19], // 00001100111x
  31089. [11, 20], [11, 20], // 00001101000x
  31090. [12, 34], // 000011010010
  31091. [12, 35], // 000011010011
  31092. [12, 36], // 000011010100
  31093. [12, 37], // 000011010101
  31094. [12, 38], // 000011010110
  31095. [12, 39], // 000011010111
  31096. [11, 21], [11, 21], // 00001101100x
  31097. [12, 42], // 000011011010
  31098. [12, 43], // 000011011011
  31099. [10, 0], [10, 0], [10, 0], [10, 0], // 0000110111xx
  31100. [7, 12], [7, 12], [7, 12], [7, 12], // 0000111xxxxx
  31101. [7, 12], [7, 12], [7, 12], [7, 12],
  31102. [7, 12], [7, 12], [7, 12], [7, 12],
  31103. [7, 12], [7, 12], [7, 12], [7, 12],
  31104. [7, 12], [7, 12], [7, 12], [7, 12],
  31105. [7, 12], [7, 12], [7, 12], [7, 12],
  31106. [7, 12], [7, 12], [7, 12], [7, 12],
  31107. [7, 12], [7, 12], [7, 12], [7, 12]
  31108. ];
  31109. var blackTable3 = [
  31110. [-1, -1], [-1, -1], [-1, -1], [-1, -1], // 0000xx
  31111. [6, 9], // 000100
  31112. [6, 8], // 000101
  31113. [5, 7], [5, 7], // 00011x
  31114. [4, 6], [4, 6], [4, 6], [4, 6], // 0010xx
  31115. [4, 5], [4, 5], [4, 5], [4, 5], // 0011xx
  31116. [3, 1], [3, 1], [3, 1], [3, 1], // 010xxx
  31117. [3, 1], [3, 1], [3, 1], [3, 1],
  31118. [3, 4], [3, 4], [3, 4], [3, 4], // 011xxx
  31119. [3, 4], [3, 4], [3, 4], [3, 4],
  31120. [2, 3], [2, 3], [2, 3], [2, 3], // 10xxxx
  31121. [2, 3], [2, 3], [2, 3], [2, 3],
  31122. [2, 3], [2, 3], [2, 3], [2, 3],
  31123. [2, 3], [2, 3], [2, 3], [2, 3],
  31124. [2, 2], [2, 2], [2, 2], [2, 2], // 11xxxx
  31125. [2, 2], [2, 2], [2, 2], [2, 2],
  31126. [2, 2], [2, 2], [2, 2], [2, 2],
  31127. [2, 2], [2, 2], [2, 2], [2, 2]
  31128. ];
  31129. function CCITTFaxStream(str, maybeLength, params) {
  31130. this.str = str;
  31131. this.dict = str.dict;
  31132. params = params || Dict.empty;
  31133. this.encoding = params.get('K') || 0;
  31134. this.eoline = params.get('EndOfLine') || false;
  31135. this.byteAlign = params.get('EncodedByteAlign') || false;
  31136. this.columns = params.get('Columns') || 1728;
  31137. this.rows = params.get('Rows') || 0;
  31138. var eoblock = params.get('EndOfBlock');
  31139. if (eoblock === null || eoblock === undefined) {
  31140. eoblock = true;
  31141. }
  31142. this.eoblock = eoblock;
  31143. this.black = params.get('BlackIs1') || false;
  31144. this.codingLine = new Uint32Array(this.columns + 1);
  31145. this.refLine = new Uint32Array(this.columns + 2);
  31146. this.codingLine[0] = this.columns;
  31147. this.codingPos = 0;
  31148. this.row = 0;
  31149. this.nextLine2D = this.encoding < 0;
  31150. this.inputBits = 0;
  31151. this.inputBuf = 0;
  31152. this.outputBits = 0;
  31153. var code1;
  31154. while ((code1 = this.lookBits(12)) === 0) {
  31155. this.eatBits(1);
  31156. }
  31157. if (code1 === 1) {
  31158. this.eatBits(12);
  31159. }
  31160. if (this.encoding > 0) {
  31161. this.nextLine2D = !this.lookBits(1);
  31162. this.eatBits(1);
  31163. }
  31164. DecodeStream.call(this, maybeLength);
  31165. }
  31166. CCITTFaxStream.prototype = Object.create(DecodeStream.prototype);
  31167. CCITTFaxStream.prototype.readBlock = function CCITTFaxStream_readBlock() {
  31168. while (!this.eof) {
  31169. var c = this.lookChar();
  31170. this.ensureBuffer(this.bufferLength + 1);
  31171. this.buffer[this.bufferLength++] = c;
  31172. }
  31173. };
  31174. CCITTFaxStream.prototype.addPixels =
  31175. function ccittFaxStreamAddPixels(a1, blackPixels) {
  31176. var codingLine = this.codingLine;
  31177. var codingPos = this.codingPos;
  31178. if (a1 > codingLine[codingPos]) {
  31179. if (a1 > this.columns) {
  31180. info('row is wrong length');
  31181. this.err = true;
  31182. a1 = this.columns;
  31183. }
  31184. if ((codingPos & 1) ^ blackPixels) {
  31185. ++codingPos;
  31186. }
  31187. codingLine[codingPos] = a1;
  31188. }
  31189. this.codingPos = codingPos;
  31190. };
  31191. CCITTFaxStream.prototype.addPixelsNeg =
  31192. function ccittFaxStreamAddPixelsNeg(a1, blackPixels) {
  31193. var codingLine = this.codingLine;
  31194. var codingPos = this.codingPos;
  31195. if (a1 > codingLine[codingPos]) {
  31196. if (a1 > this.columns) {
  31197. info('row is wrong length');
  31198. this.err = true;
  31199. a1 = this.columns;
  31200. }
  31201. if ((codingPos & 1) ^ blackPixels) {
  31202. ++codingPos;
  31203. }
  31204. codingLine[codingPos] = a1;
  31205. } else if (a1 < codingLine[codingPos]) {
  31206. if (a1 < 0) {
  31207. info('invalid code');
  31208. this.err = true;
  31209. a1 = 0;
  31210. }
  31211. while (codingPos > 0 && a1 < codingLine[codingPos - 1]) {
  31212. --codingPos;
  31213. }
  31214. codingLine[codingPos] = a1;
  31215. }
  31216. this.codingPos = codingPos;
  31217. };
  31218. CCITTFaxStream.prototype.lookChar = function CCITTFaxStream_lookChar() {
  31219. var refLine = this.refLine;
  31220. var codingLine = this.codingLine;
  31221. var columns = this.columns;
  31222. var refPos, blackPixels, bits, i;
  31223. if (this.outputBits === 0) {
  31224. if (this.eof) {
  31225. return null;
  31226. }
  31227. this.err = false;
  31228. var code1, code2, code3;
  31229. if (this.nextLine2D) {
  31230. for (i = 0; codingLine[i] < columns; ++i) {
  31231. refLine[i] = codingLine[i];
  31232. }
  31233. refLine[i++] = columns;
  31234. refLine[i] = columns;
  31235. codingLine[0] = 0;
  31236. this.codingPos = 0;
  31237. refPos = 0;
  31238. blackPixels = 0;
  31239. while (codingLine[this.codingPos] < columns) {
  31240. code1 = this.getTwoDimCode();
  31241. switch (code1) {
  31242. case twoDimPass:
  31243. this.addPixels(refLine[refPos + 1], blackPixels);
  31244. if (refLine[refPos + 1] < columns) {
  31245. refPos += 2;
  31246. }
  31247. break;
  31248. case twoDimHoriz:
  31249. code1 = code2 = 0;
  31250. if (blackPixels) {
  31251. do {
  31252. code1 += (code3 = this.getBlackCode());
  31253. } while (code3 >= 64);
  31254. do {
  31255. code2 += (code3 = this.getWhiteCode());
  31256. } while (code3 >= 64);
  31257. } else {
  31258. do {
  31259. code1 += (code3 = this.getWhiteCode());
  31260. } while (code3 >= 64);
  31261. do {
  31262. code2 += (code3 = this.getBlackCode());
  31263. } while (code3 >= 64);
  31264. }
  31265. this.addPixels(codingLine[this.codingPos] +
  31266. code1, blackPixels);
  31267. if (codingLine[this.codingPos] < columns) {
  31268. this.addPixels(codingLine[this.codingPos] + code2,
  31269. blackPixels ^ 1);
  31270. }
  31271. while (refLine[refPos] <= codingLine[this.codingPos] &&
  31272. refLine[refPos] < columns) {
  31273. refPos += 2;
  31274. }
  31275. break;
  31276. case twoDimVertR3:
  31277. this.addPixels(refLine[refPos] + 3, blackPixels);
  31278. blackPixels ^= 1;
  31279. if (codingLine[this.codingPos] < columns) {
  31280. ++refPos;
  31281. while (refLine[refPos] <= codingLine[this.codingPos] &&
  31282. refLine[refPos] < columns) {
  31283. refPos += 2;
  31284. }
  31285. }
  31286. break;
  31287. case twoDimVertR2:
  31288. this.addPixels(refLine[refPos] + 2, blackPixels);
  31289. blackPixels ^= 1;
  31290. if (codingLine[this.codingPos] < columns) {
  31291. ++refPos;
  31292. while (refLine[refPos] <= codingLine[this.codingPos] &&
  31293. refLine[refPos] < columns) {
  31294. refPos += 2;
  31295. }
  31296. }
  31297. break;
  31298. case twoDimVertR1:
  31299. this.addPixels(refLine[refPos] + 1, blackPixels);
  31300. blackPixels ^= 1;
  31301. if (codingLine[this.codingPos] < columns) {
  31302. ++refPos;
  31303. while (refLine[refPos] <= codingLine[this.codingPos] &&
  31304. refLine[refPos] < columns) {
  31305. refPos += 2;
  31306. }
  31307. }
  31308. break;
  31309. case twoDimVert0:
  31310. this.addPixels(refLine[refPos], blackPixels);
  31311. blackPixels ^= 1;
  31312. if (codingLine[this.codingPos] < columns) {
  31313. ++refPos;
  31314. while (refLine[refPos] <= codingLine[this.codingPos] &&
  31315. refLine[refPos] < columns) {
  31316. refPos += 2;
  31317. }
  31318. }
  31319. break;
  31320. case twoDimVertL3:
  31321. this.addPixelsNeg(refLine[refPos] - 3, blackPixels);
  31322. blackPixels ^= 1;
  31323. if (codingLine[this.codingPos] < columns) {
  31324. if (refPos > 0) {
  31325. --refPos;
  31326. } else {
  31327. ++refPos;
  31328. }
  31329. while (refLine[refPos] <= codingLine[this.codingPos] &&
  31330. refLine[refPos] < columns) {
  31331. refPos += 2;
  31332. }
  31333. }
  31334. break;
  31335. case twoDimVertL2:
  31336. this.addPixelsNeg(refLine[refPos] - 2, blackPixels);
  31337. blackPixels ^= 1;
  31338. if (codingLine[this.codingPos] < columns) {
  31339. if (refPos > 0) {
  31340. --refPos;
  31341. } else {
  31342. ++refPos;
  31343. }
  31344. while (refLine[refPos] <= codingLine[this.codingPos] &&
  31345. refLine[refPos] < columns) {
  31346. refPos += 2;
  31347. }
  31348. }
  31349. break;
  31350. case twoDimVertL1:
  31351. this.addPixelsNeg(refLine[refPos] - 1, blackPixels);
  31352. blackPixels ^= 1;
  31353. if (codingLine[this.codingPos] < columns) {
  31354. if (refPos > 0) {
  31355. --refPos;
  31356. } else {
  31357. ++refPos;
  31358. }
  31359. while (refLine[refPos] <= codingLine[this.codingPos] &&
  31360. refLine[refPos] < columns) {
  31361. refPos += 2;
  31362. }
  31363. }
  31364. break;
  31365. case EOF:
  31366. this.addPixels(columns, 0);
  31367. this.eof = true;
  31368. break;
  31369. default:
  31370. info('bad 2d code');
  31371. this.addPixels(columns, 0);
  31372. this.err = true;
  31373. }
  31374. }
  31375. } else {
  31376. codingLine[0] = 0;
  31377. this.codingPos = 0;
  31378. blackPixels = 0;
  31379. while (codingLine[this.codingPos] < columns) {
  31380. code1 = 0;
  31381. if (blackPixels) {
  31382. do {
  31383. code1 += (code3 = this.getBlackCode());
  31384. } while (code3 >= 64);
  31385. } else {
  31386. do {
  31387. code1 += (code3 = this.getWhiteCode());
  31388. } while (code3 >= 64);
  31389. }
  31390. this.addPixels(codingLine[this.codingPos] + code1, blackPixels);
  31391. blackPixels ^= 1;
  31392. }
  31393. }
  31394. var gotEOL = false;
  31395. if (this.byteAlign) {
  31396. this.inputBits &= ~7;
  31397. }
  31398. if (!this.eoblock && this.row === this.rows - 1) {
  31399. this.eof = true;
  31400. } else {
  31401. code1 = this.lookBits(12);
  31402. if (this.eoline) {
  31403. while (code1 !== EOF && code1 !== 1) {
  31404. this.eatBits(1);
  31405. code1 = this.lookBits(12);
  31406. }
  31407. } else {
  31408. while (code1 === 0) {
  31409. this.eatBits(1);
  31410. code1 = this.lookBits(12);
  31411. }
  31412. }
  31413. if (code1 === 1) {
  31414. this.eatBits(12);
  31415. gotEOL = true;
  31416. } else if (code1 === EOF) {
  31417. this.eof = true;
  31418. }
  31419. }
  31420. if (!this.eof && this.encoding > 0) {
  31421. this.nextLine2D = !this.lookBits(1);
  31422. this.eatBits(1);
  31423. }
  31424. if (this.eoblock && gotEOL && this.byteAlign) {
  31425. code1 = this.lookBits(12);
  31426. if (code1 === 1) {
  31427. this.eatBits(12);
  31428. if (this.encoding > 0) {
  31429. this.lookBits(1);
  31430. this.eatBits(1);
  31431. }
  31432. if (this.encoding >= 0) {
  31433. for (i = 0; i < 4; ++i) {
  31434. code1 = this.lookBits(12);
  31435. if (code1 !== 1) {
  31436. info('bad rtc code: ' + code1);
  31437. }
  31438. this.eatBits(12);
  31439. if (this.encoding > 0) {
  31440. this.lookBits(1);
  31441. this.eatBits(1);
  31442. }
  31443. }
  31444. }
  31445. this.eof = true;
  31446. }
  31447. } else if (this.err && this.eoline) {
  31448. while (true) {
  31449. code1 = this.lookBits(13);
  31450. if (code1 === EOF) {
  31451. this.eof = true;
  31452. return null;
  31453. }
  31454. if ((code1 >> 1) === 1) {
  31455. break;
  31456. }
  31457. this.eatBits(1);
  31458. }
  31459. this.eatBits(12);
  31460. if (this.encoding > 0) {
  31461. this.eatBits(1);
  31462. this.nextLine2D = !(code1 & 1);
  31463. }
  31464. }
  31465. if (codingLine[0] > 0) {
  31466. this.outputBits = codingLine[this.codingPos = 0];
  31467. } else {
  31468. this.outputBits = codingLine[this.codingPos = 1];
  31469. }
  31470. this.row++;
  31471. }
  31472. var c;
  31473. if (this.outputBits >= 8) {
  31474. c = (this.codingPos & 1) ? 0 : 0xFF;
  31475. this.outputBits -= 8;
  31476. if (this.outputBits === 0 && codingLine[this.codingPos] < columns) {
  31477. this.codingPos++;
  31478. this.outputBits = (codingLine[this.codingPos] -
  31479. codingLine[this.codingPos - 1]);
  31480. }
  31481. } else {
  31482. bits = 8;
  31483. c = 0;
  31484. do {
  31485. if (this.outputBits > bits) {
  31486. c <<= bits;
  31487. if (!(this.codingPos & 1)) {
  31488. c |= 0xFF >> (8 - bits);
  31489. }
  31490. this.outputBits -= bits;
  31491. bits = 0;
  31492. } else {
  31493. c <<= this.outputBits;
  31494. if (!(this.codingPos & 1)) {
  31495. c |= 0xFF >> (8 - this.outputBits);
  31496. }
  31497. bits -= this.outputBits;
  31498. this.outputBits = 0;
  31499. if (codingLine[this.codingPos] < columns) {
  31500. this.codingPos++;
  31501. this.outputBits = (codingLine[this.codingPos] -
  31502. codingLine[this.codingPos - 1]);
  31503. } else if (bits > 0) {
  31504. c <<= bits;
  31505. bits = 0;
  31506. }
  31507. }
  31508. } while (bits);
  31509. }
  31510. if (this.black) {
  31511. c ^= 0xFF;
  31512. }
  31513. return c;
  31514. };
  31515. // This functions returns the code found from the table.
  31516. // The start and end parameters set the boundaries for searching the table.
  31517. // The limit parameter is optional. Function returns an array with three
  31518. // values. The first array element indicates whether a valid code is being
  31519. // returned. The second array element is the actual code. The third array
  31520. // element indicates whether EOF was reached.
  31521. CCITTFaxStream.prototype.findTableCode =
  31522. function ccittFaxStreamFindTableCode(start, end, table, limit) {
  31523. var limitValue = limit || 0;
  31524. for (var i = start; i <= end; ++i) {
  31525. var code = this.lookBits(i);
  31526. if (code === EOF) {
  31527. return [true, 1, false];
  31528. }
  31529. if (i < end) {
  31530. code <<= end - i;
  31531. }
  31532. if (!limitValue || code >= limitValue) {
  31533. var p = table[code - limitValue];
  31534. if (p[0] === i) {
  31535. this.eatBits(i);
  31536. return [true, p[1], true];
  31537. }
  31538. }
  31539. }
  31540. return [false, 0, false];
  31541. };
  31542. CCITTFaxStream.prototype.getTwoDimCode =
  31543. function ccittFaxStreamGetTwoDimCode() {
  31544. var code = 0;
  31545. var p;
  31546. if (this.eoblock) {
  31547. code = this.lookBits(7);
  31548. p = twoDimTable[code];
  31549. if (p && p[0] > 0) {
  31550. this.eatBits(p[0]);
  31551. return p[1];
  31552. }
  31553. } else {
  31554. var result = this.findTableCode(1, 7, twoDimTable);
  31555. if (result[0] && result[2]) {
  31556. return result[1];
  31557. }
  31558. }
  31559. info('Bad two dim code');
  31560. return EOF;
  31561. };
  31562. CCITTFaxStream.prototype.getWhiteCode =
  31563. function ccittFaxStreamGetWhiteCode() {
  31564. var code = 0;
  31565. var p;
  31566. if (this.eoblock) {
  31567. code = this.lookBits(12);
  31568. if (code === EOF) {
  31569. return 1;
  31570. }
  31571. if ((code >> 5) === 0) {
  31572. p = whiteTable1[code];
  31573. } else {
  31574. p = whiteTable2[code >> 3];
  31575. }
  31576. if (p[0] > 0) {
  31577. this.eatBits(p[0]);
  31578. return p[1];
  31579. }
  31580. } else {
  31581. var result = this.findTableCode(1, 9, whiteTable2);
  31582. if (result[0]) {
  31583. return result[1];
  31584. }
  31585. result = this.findTableCode(11, 12, whiteTable1);
  31586. if (result[0]) {
  31587. return result[1];
  31588. }
  31589. }
  31590. info('bad white code');
  31591. this.eatBits(1);
  31592. return 1;
  31593. };
  31594. CCITTFaxStream.prototype.getBlackCode =
  31595. function ccittFaxStreamGetBlackCode() {
  31596. var code, p;
  31597. if (this.eoblock) {
  31598. code = this.lookBits(13);
  31599. if (code === EOF) {
  31600. return 1;
  31601. }
  31602. if ((code >> 7) === 0) {
  31603. p = blackTable1[code];
  31604. } else if ((code >> 9) === 0 && (code >> 7) !== 0) {
  31605. p = blackTable2[(code >> 1) - 64];
  31606. } else {
  31607. p = blackTable3[code >> 7];
  31608. }
  31609. if (p[0] > 0) {
  31610. this.eatBits(p[0]);
  31611. return p[1];
  31612. }
  31613. } else {
  31614. var result = this.findTableCode(2, 6, blackTable3);
  31615. if (result[0]) {
  31616. return result[1];
  31617. }
  31618. result = this.findTableCode(7, 12, blackTable2, 64);
  31619. if (result[0]) {
  31620. return result[1];
  31621. }
  31622. result = this.findTableCode(10, 13, blackTable1);
  31623. if (result[0]) {
  31624. return result[1];
  31625. }
  31626. }
  31627. info('bad black code');
  31628. this.eatBits(1);
  31629. return 1;
  31630. };
  31631. CCITTFaxStream.prototype.lookBits = function CCITTFaxStream_lookBits(n) {
  31632. var c;
  31633. while (this.inputBits < n) {
  31634. if ((c = this.str.getByte()) === -1) {
  31635. if (this.inputBits === 0) {
  31636. return EOF;
  31637. }
  31638. return ((this.inputBuf << (n - this.inputBits)) &
  31639. (0xFFFF >> (16 - n)));
  31640. }
  31641. this.inputBuf = (this.inputBuf << 8) + c;
  31642. this.inputBits += 8;
  31643. }
  31644. return (this.inputBuf >> (this.inputBits - n)) & (0xFFFF >> (16 - n));
  31645. };
  31646. CCITTFaxStream.prototype.eatBits = function CCITTFaxStream_eatBits(n) {
  31647. if ((this.inputBits -= n) < 0) {
  31648. this.inputBits = 0;
  31649. }
  31650. };
  31651. return CCITTFaxStream;
  31652. })();
  31653. var LZWStream = (function LZWStreamClosure() {
  31654. function LZWStream(str, maybeLength, earlyChange) {
  31655. this.str = str;
  31656. this.dict = str.dict;
  31657. this.cachedData = 0;
  31658. this.bitsCached = 0;
  31659. var maxLzwDictionarySize = 4096;
  31660. var lzwState = {
  31661. earlyChange: earlyChange,
  31662. codeLength: 9,
  31663. nextCode: 258,
  31664. dictionaryValues: new Uint8Array(maxLzwDictionarySize),
  31665. dictionaryLengths: new Uint16Array(maxLzwDictionarySize),
  31666. dictionaryPrevCodes: new Uint16Array(maxLzwDictionarySize),
  31667. currentSequence: new Uint8Array(maxLzwDictionarySize),
  31668. currentSequenceLength: 0
  31669. };
  31670. for (var i = 0; i < 256; ++i) {
  31671. lzwState.dictionaryValues[i] = i;
  31672. lzwState.dictionaryLengths[i] = 1;
  31673. }
  31674. this.lzwState = lzwState;
  31675. DecodeStream.call(this, maybeLength);
  31676. }
  31677. LZWStream.prototype = Object.create(DecodeStream.prototype);
  31678. LZWStream.prototype.readBits = function LZWStream_readBits(n) {
  31679. var bitsCached = this.bitsCached;
  31680. var cachedData = this.cachedData;
  31681. while (bitsCached < n) {
  31682. var c = this.str.getByte();
  31683. if (c === -1) {
  31684. this.eof = true;
  31685. return null;
  31686. }
  31687. cachedData = (cachedData << 8) | c;
  31688. bitsCached += 8;
  31689. }
  31690. this.bitsCached = (bitsCached -= n);
  31691. this.cachedData = cachedData;
  31692. this.lastCode = null;
  31693. return (cachedData >>> bitsCached) & ((1 << n) - 1);
  31694. };
  31695. LZWStream.prototype.readBlock = function LZWStream_readBlock() {
  31696. var blockSize = 512;
  31697. var estimatedDecodedSize = blockSize * 2, decodedSizeDelta = blockSize;
  31698. var i, j, q;
  31699. var lzwState = this.lzwState;
  31700. if (!lzwState) {
  31701. return; // eof was found
  31702. }
  31703. var earlyChange = lzwState.earlyChange;
  31704. var nextCode = lzwState.nextCode;
  31705. var dictionaryValues = lzwState.dictionaryValues;
  31706. var dictionaryLengths = lzwState.dictionaryLengths;
  31707. var dictionaryPrevCodes = lzwState.dictionaryPrevCodes;
  31708. var codeLength = lzwState.codeLength;
  31709. var prevCode = lzwState.prevCode;
  31710. var currentSequence = lzwState.currentSequence;
  31711. var currentSequenceLength = lzwState.currentSequenceLength;
  31712. var decodedLength = 0;
  31713. var currentBufferLength = this.bufferLength;
  31714. var buffer = this.ensureBuffer(this.bufferLength + estimatedDecodedSize);
  31715. for (i = 0; i < blockSize; i++) {
  31716. var code = this.readBits(codeLength);
  31717. var hasPrev = currentSequenceLength > 0;
  31718. if (code < 256) {
  31719. currentSequence[0] = code;
  31720. currentSequenceLength = 1;
  31721. } else if (code >= 258) {
  31722. if (code < nextCode) {
  31723. currentSequenceLength = dictionaryLengths[code];
  31724. for (j = currentSequenceLength - 1, q = code; j >= 0; j--) {
  31725. currentSequence[j] = dictionaryValues[q];
  31726. q = dictionaryPrevCodes[q];
  31727. }
  31728. } else {
  31729. currentSequence[currentSequenceLength++] = currentSequence[0];
  31730. }
  31731. } else if (code === 256) {
  31732. codeLength = 9;
  31733. nextCode = 258;
  31734. currentSequenceLength = 0;
  31735. continue;
  31736. } else {
  31737. this.eof = true;
  31738. delete this.lzwState;
  31739. break;
  31740. }
  31741. if (hasPrev) {
  31742. dictionaryPrevCodes[nextCode] = prevCode;
  31743. dictionaryLengths[nextCode] = dictionaryLengths[prevCode] + 1;
  31744. dictionaryValues[nextCode] = currentSequence[0];
  31745. nextCode++;
  31746. codeLength = (nextCode + earlyChange) & (nextCode + earlyChange - 1) ?
  31747. codeLength : Math.min(Math.log(nextCode + earlyChange) /
  31748. 0.6931471805599453 + 1, 12) | 0;
  31749. }
  31750. prevCode = code;
  31751. decodedLength += currentSequenceLength;
  31752. if (estimatedDecodedSize < decodedLength) {
  31753. do {
  31754. estimatedDecodedSize += decodedSizeDelta;
  31755. } while (estimatedDecodedSize < decodedLength);
  31756. buffer = this.ensureBuffer(this.bufferLength + estimatedDecodedSize);
  31757. }
  31758. for (j = 0; j < currentSequenceLength; j++) {
  31759. buffer[currentBufferLength++] = currentSequence[j];
  31760. }
  31761. }
  31762. lzwState.nextCode = nextCode;
  31763. lzwState.codeLength = codeLength;
  31764. lzwState.prevCode = prevCode;
  31765. lzwState.currentSequenceLength = currentSequenceLength;
  31766. this.bufferLength = currentBufferLength;
  31767. };
  31768. return LZWStream;
  31769. })();
  31770. var NullStream = (function NullStreamClosure() {
  31771. function NullStream() {
  31772. Stream.call(this, new Uint8Array(0));
  31773. }
  31774. NullStream.prototype = Stream.prototype;
  31775. return NullStream;
  31776. })();
  31777. var WorkerMessageHandler = PDFJS.WorkerMessageHandler = {
  31778. setup: function wphSetup(handler) {
  31779. var pdfManager;
  31780. function loadDocument(recoveryMode) {
  31781. var loadDocumentCapability = createPromiseCapability();
  31782. var parseSuccess = function parseSuccess() {
  31783. var numPagesPromise = pdfManager.ensureDoc('numPages');
  31784. var fingerprintPromise = pdfManager.ensureDoc('fingerprint');
  31785. var encryptedPromise = pdfManager.ensureXRef('encrypt');
  31786. Promise.all([numPagesPromise, fingerprintPromise,
  31787. encryptedPromise]).then(function onDocReady(results) {
  31788. var doc = {
  31789. numPages: results[0],
  31790. fingerprint: results[1],
  31791. encrypted: !!results[2],
  31792. };
  31793. loadDocumentCapability.resolve(doc);
  31794. },
  31795. parseFailure);
  31796. };
  31797. var parseFailure = function parseFailure(e) {
  31798. loadDocumentCapability.reject(e);
  31799. };
  31800. pdfManager.ensureDoc('checkHeader', []).then(function() {
  31801. pdfManager.ensureDoc('parseStartXRef', []).then(function() {
  31802. pdfManager.ensureDoc('parse', [recoveryMode]).then(
  31803. parseSuccess, parseFailure);
  31804. }, parseFailure);
  31805. }, parseFailure);
  31806. return loadDocumentCapability.promise;
  31807. }
  31808. function getPdfManager(data) {
  31809. var pdfManagerCapability = createPromiseCapability();
  31810. var source = data.source;
  31811. var disableRange = data.disableRange;
  31812. if (source.data) {
  31813. try {
  31814. pdfManager = new LocalPdfManager(source.data, source.password);
  31815. pdfManagerCapability.resolve();
  31816. } catch (ex) {
  31817. pdfManagerCapability.reject(ex);
  31818. }
  31819. return pdfManagerCapability.promise;
  31820. } else if (source.chunkedViewerLoading) {
  31821. try {
  31822. pdfManager = new NetworkPdfManager(source, handler);
  31823. pdfManagerCapability.resolve();
  31824. } catch (ex) {
  31825. pdfManagerCapability.reject(ex);
  31826. }
  31827. return pdfManagerCapability.promise;
  31828. }
  31829. var networkManager = new NetworkManager(source.url, {
  31830. httpHeaders: source.httpHeaders,
  31831. withCredentials: source.withCredentials
  31832. });
  31833. var cachedChunks = [];
  31834. var fullRequestXhrId = networkManager.requestFull({
  31835. onHeadersReceived: function onHeadersReceived() {
  31836. if (disableRange) {
  31837. return;
  31838. }
  31839. var fullRequestXhr = networkManager.getRequestXhr(fullRequestXhrId);
  31840. if (fullRequestXhr.getResponseHeader('Accept-Ranges') !== 'bytes') {
  31841. return;
  31842. }
  31843. var contentEncoding =
  31844. fullRequestXhr.getResponseHeader('Content-Encoding') || 'identity';
  31845. if (contentEncoding !== 'identity') {
  31846. return;
  31847. }
  31848. var length = fullRequestXhr.getResponseHeader('Content-Length');
  31849. length = parseInt(length, 10);
  31850. if (!isInt(length)) {
  31851. return;
  31852. }
  31853. source.length = length;
  31854. if (length <= 2 * RANGE_CHUNK_SIZE) {
  31855. // The file size is smaller than the size of two chunks, so it does
  31856. // not make any sense to abort the request and retry with a range
  31857. // request.
  31858. return;
  31859. }
  31860. if (networkManager.isStreamingRequest(fullRequestXhrId)) {
  31861. // We can continue fetching when progressive loading is enabled,
  31862. // and we don't need the autoFetch feature.
  31863. source.disableAutoFetch = true;
  31864. } else {
  31865. // NOTE: by cancelling the full request, and then issuing range
  31866. // requests, there will be an issue for sites where you can only
  31867. // request the pdf once. However, if this is the case, then the
  31868. // server should not be returning that it can support range
  31869. // requests.
  31870. networkManager.abortRequest(fullRequestXhrId);
  31871. }
  31872. try {
  31873. pdfManager = new NetworkPdfManager(source, handler);
  31874. pdfManagerCapability.resolve(pdfManager);
  31875. } catch (ex) {
  31876. pdfManagerCapability.reject(ex);
  31877. }
  31878. },
  31879. onProgressiveData: source.disableStream ? null :
  31880. function onProgressiveData(chunk) {
  31881. if (!pdfManager) {
  31882. cachedChunks.push(chunk);
  31883. return;
  31884. }
  31885. pdfManager.sendProgressiveData(chunk);
  31886. },
  31887. onDone: function onDone(args) {
  31888. if (pdfManager) {
  31889. return; // already processed
  31890. }
  31891. var pdfFile;
  31892. if (args === null) {
  31893. // TODO add some streaming manager, e.g. for unknown length files.
  31894. // The data was returned in the onProgressiveData, combining...
  31895. var pdfFileLength = 0, pos = 0;
  31896. cachedChunks.forEach(function (chunk) {
  31897. pdfFileLength += chunk.byteLength;
  31898. });
  31899. if (source.length && pdfFileLength !== source.length) {
  31900. warn('reported HTTP length is different from actual');
  31901. }
  31902. var pdfFileArray = new Uint8Array(pdfFileLength);
  31903. cachedChunks.forEach(function (chunk) {
  31904. pdfFileArray.set(new Uint8Array(chunk), pos);
  31905. pos += chunk.byteLength;
  31906. });
  31907. pdfFile = pdfFileArray.buffer;
  31908. } else {
  31909. pdfFile = args.chunk;
  31910. }
  31911. // the data is array, instantiating directly from it
  31912. try {
  31913. pdfManager = new LocalPdfManager(pdfFile, source.password);
  31914. pdfManagerCapability.resolve();
  31915. } catch (ex) {
  31916. pdfManagerCapability.reject(ex);
  31917. }
  31918. },
  31919. onError: function onError(status) {
  31920. var exception;
  31921. if (status === 404) {
  31922. exception = new MissingPDFException('Missing PDF "' +
  31923. source.url + '".');
  31924. handler.send('MissingPDF', exception);
  31925. } else {
  31926. exception = new UnexpectedResponseException(
  31927. 'Unexpected server response (' + status +
  31928. ') while retrieving PDF "' + source.url + '".', status);
  31929. handler.send('UnexpectedResponse', exception);
  31930. }
  31931. },
  31932. onProgress: function onProgress(evt) {
  31933. handler.send('DocProgress', {
  31934. loaded: evt.loaded,
  31935. total: evt.lengthComputable ? evt.total : source.length
  31936. });
  31937. }
  31938. });
  31939. return pdfManagerCapability.promise;
  31940. }
  31941. handler.on('test', function wphSetupTest(data) {
  31942. // check if Uint8Array can be sent to worker
  31943. if (!(data instanceof Uint8Array)) {
  31944. handler.send('test', false);
  31945. return;
  31946. }
  31947. // making sure postMessage transfers are working
  31948. var supportTransfers = data[0] === 255;
  31949. handler.postMessageTransfers = supportTransfers;
  31950. // check if the response property is supported by xhr
  31951. var xhr = new XMLHttpRequest();
  31952. var responseExists = 'response' in xhr;
  31953. // check if the property is actually implemented
  31954. try {
  31955. var dummy = xhr.responseType;
  31956. } catch (e) {
  31957. responseExists = false;
  31958. }
  31959. if (!responseExists) {
  31960. handler.send('test', false);
  31961. return;
  31962. }
  31963. handler.send('test', {
  31964. supportTypedArray: true,
  31965. supportTransfers: supportTransfers
  31966. });
  31967. });
  31968. handler.on('GetDocRequest', function wphSetupDoc(data) {
  31969. var onSuccess = function(doc) {
  31970. handler.send('GetDoc', { pdfInfo: doc });
  31971. };
  31972. var onFailure = function(e) {
  31973. if (e instanceof PasswordException) {
  31974. if (e.code === PasswordResponses.NEED_PASSWORD) {
  31975. handler.send('NeedPassword', e);
  31976. } else if (e.code === PasswordResponses.INCORRECT_PASSWORD) {
  31977. handler.send('IncorrectPassword', e);
  31978. }
  31979. } else if (e instanceof InvalidPDFException) {
  31980. handler.send('InvalidPDF', e);
  31981. } else if (e instanceof MissingPDFException) {
  31982. handler.send('MissingPDF', e);
  31983. } else if (e instanceof UnexpectedResponseException) {
  31984. handler.send('UnexpectedResponse', e);
  31985. } else {
  31986. handler.send('UnknownError',
  31987. new UnknownErrorException(e.message, e.toString()));
  31988. }
  31989. };
  31990. PDFJS.maxImageSize = data.maxImageSize === undefined ?
  31991. -1 : data.maxImageSize;
  31992. PDFJS.disableFontFace = data.disableFontFace;
  31993. PDFJS.disableCreateObjectURL = data.disableCreateObjectURL;
  31994. PDFJS.verbosity = data.verbosity;
  31995. PDFJS.cMapUrl = data.cMapUrl === undefined ?
  31996. null : data.cMapUrl;
  31997. PDFJS.cMapPacked = data.cMapPacked === true;
  31998. getPdfManager(data).then(function () {
  31999. handler.send('PDFManagerReady', null);
  32000. pdfManager.onLoadedStream().then(function(stream) {
  32001. handler.send('DataLoaded', { length: stream.bytes.byteLength });
  32002. });
  32003. }).then(function pdfManagerReady() {
  32004. loadDocument(false).then(onSuccess, function loadFailure(ex) {
  32005. // Try again with recoveryMode == true
  32006. if (!(ex instanceof XRefParseException)) {
  32007. if (ex instanceof PasswordException) {
  32008. // after password exception prepare to receive a new password
  32009. // to repeat loading
  32010. pdfManager.passwordChanged().then(pdfManagerReady);
  32011. }
  32012. onFailure(ex);
  32013. return;
  32014. }
  32015. pdfManager.requestLoadedStream();
  32016. pdfManager.onLoadedStream().then(function() {
  32017. loadDocument(true).then(onSuccess, onFailure);
  32018. });
  32019. }, onFailure);
  32020. }, onFailure);
  32021. });
  32022. handler.on('GetPage', function wphSetupGetPage(data) {
  32023. return pdfManager.getPage(data.pageIndex).then(function(page) {
  32024. var rotatePromise = pdfManager.ensure(page, 'rotate');
  32025. var refPromise = pdfManager.ensure(page, 'ref');
  32026. var viewPromise = pdfManager.ensure(page, 'view');
  32027. return Promise.all([rotatePromise, refPromise, viewPromise]).then(
  32028. function(results) {
  32029. return {
  32030. rotate: results[0],
  32031. ref: results[1],
  32032. view: results[2]
  32033. };
  32034. });
  32035. });
  32036. });
  32037. handler.on('GetPageIndex', function wphSetupGetPageIndex(data) {
  32038. var ref = new Ref(data.ref.num, data.ref.gen);
  32039. var catalog = pdfManager.pdfDocument.catalog;
  32040. return catalog.getPageIndex(ref);
  32041. });
  32042. handler.on('GetDestinations',
  32043. function wphSetupGetDestinations(data) {
  32044. return pdfManager.ensureCatalog('destinations');
  32045. }
  32046. );
  32047. handler.on('GetDestination',
  32048. function wphSetupGetDestination(data) {
  32049. return pdfManager.ensureCatalog('getDestination', [ data.id ]);
  32050. }
  32051. );
  32052. handler.on('GetAttachments',
  32053. function wphSetupGetAttachments(data) {
  32054. return pdfManager.ensureCatalog('attachments');
  32055. }
  32056. );
  32057. handler.on('GetJavaScript',
  32058. function wphSetupGetJavaScript(data) {
  32059. return pdfManager.ensureCatalog('javaScript');
  32060. }
  32061. );
  32062. handler.on('GetOutline',
  32063. function wphSetupGetOutline(data) {
  32064. return pdfManager.ensureCatalog('documentOutline');
  32065. }
  32066. );
  32067. handler.on('GetMetadata',
  32068. function wphSetupGetMetadata(data) {
  32069. return Promise.all([pdfManager.ensureDoc('documentInfo'),
  32070. pdfManager.ensureCatalog('metadata')]);
  32071. }
  32072. );
  32073. handler.on('GetData', function wphSetupGetData(data) {
  32074. pdfManager.requestLoadedStream();
  32075. return pdfManager.onLoadedStream().then(function(stream) {
  32076. return stream.bytes;
  32077. });
  32078. });
  32079. handler.on('GetStats',
  32080. function wphSetupGetStats(data) {
  32081. return pdfManager.pdfDocument.xref.stats;
  32082. }
  32083. );
  32084. handler.on('UpdatePassword', function wphSetupUpdatePassword(data) {
  32085. pdfManager.updatePassword(data);
  32086. });
  32087. handler.on('GetAnnotations', function wphSetupGetAnnotations(data) {
  32088. return pdfManager.getPage(data.pageIndex).then(function(page) {
  32089. return pdfManager.ensure(page, 'getAnnotationsData', []);
  32090. });
  32091. });
  32092. handler.on('RenderPageRequest', function wphSetupRenderPage(data) {
  32093. pdfManager.getPage(data.pageIndex).then(function(page) {
  32094. var pageNum = data.pageIndex + 1;
  32095. var start = Date.now();
  32096. // Pre compile the pdf page and fetch the fonts/images.
  32097. page.getOperatorList(handler, data.intent).then(function(operatorList) {
  32098. info('page=' + pageNum + ' - getOperatorList: time=' +
  32099. (Date.now() - start) + 'ms, len=' + operatorList.fnArray.length);
  32100. }, function(e) {
  32101. var minimumStackMessage =
  32102. 'worker.js: while trying to getPage() and getOperatorList()';
  32103. var wrappedException;
  32104. // Turn the error into an obj that can be serialized
  32105. if (typeof e === 'string') {
  32106. wrappedException = {
  32107. message: e,
  32108. stack: minimumStackMessage
  32109. };
  32110. } else if (typeof e === 'object') {
  32111. wrappedException = {
  32112. message: e.message || e.toString(),
  32113. stack: e.stack || minimumStackMessage
  32114. };
  32115. } else {
  32116. wrappedException = {
  32117. message: 'Unknown exception type: ' + (typeof e),
  32118. stack: minimumStackMessage
  32119. };
  32120. }
  32121. handler.send('PageError', {
  32122. pageNum: pageNum,
  32123. error: wrappedException,
  32124. intent: data.intent
  32125. });
  32126. });
  32127. });
  32128. }, this);
  32129. handler.on('GetTextContent', function wphExtractText(data) {
  32130. return pdfManager.getPage(data.pageIndex).then(function(page) {
  32131. var pageNum = data.pageIndex + 1;
  32132. var start = Date.now();
  32133. return page.extractTextContent().then(function(textContent) {
  32134. info('text indexing: page=' + pageNum + ' - time=' +
  32135. (Date.now() - start) + 'ms');
  32136. return textContent;
  32137. });
  32138. });
  32139. });
  32140. handler.on('Cleanup', function wphCleanup(data) {
  32141. return pdfManager.cleanup();
  32142. });
  32143. handler.on('Terminate', function wphTerminate(data) {
  32144. pdfManager.terminate();
  32145. });
  32146. }
  32147. };
  32148. var consoleTimer = {};
  32149. var workerConsole = {
  32150. log: function log() {
  32151. var args = Array.prototype.slice.call(arguments);
  32152. globalScope.postMessage({
  32153. action: 'console_log',
  32154. data: args
  32155. });
  32156. },
  32157. error: function error() {
  32158. var args = Array.prototype.slice.call(arguments);
  32159. globalScope.postMessage({
  32160. action: 'console_error',
  32161. data: args
  32162. });
  32163. throw 'pdf.js execution error';
  32164. },
  32165. time: function time(name) {
  32166. consoleTimer[name] = Date.now();
  32167. },
  32168. timeEnd: function timeEnd(name) {
  32169. var time = consoleTimer[name];
  32170. if (!time) {
  32171. error('Unknown timer name ' + name);
  32172. }
  32173. this.log('Timer:', name, Date.now() - time);
  32174. }
  32175. };
  32176. // Worker thread?
  32177. if (typeof window === 'undefined') {
  32178. if (!('console' in globalScope)) {
  32179. globalScope.console = workerConsole;
  32180. }
  32181. // Listen for unsupported features so we can pass them on to the main thread.
  32182. PDFJS.UnsupportedManager.listen(function (msg) {
  32183. globalScope.postMessage({
  32184. action: '_unsupported_feature',
  32185. data: msg
  32186. });
  32187. });
  32188. var handler = new MessageHandler('worker_processor', this);
  32189. WorkerMessageHandler.setup(handler);
  32190. }
  32191. /* This class implements the QM Coder decoding as defined in
  32192. * JPEG 2000 Part I Final Committee Draft Version 1.0
  32193. * Annex C.3 Arithmetic decoding procedure
  32194. * available at http://www.jpeg.org/public/fcd15444-1.pdf
  32195. *
  32196. * The arithmetic decoder is used in conjunction with context models to decode
  32197. * JPEG2000 and JBIG2 streams.
  32198. */
  32199. var ArithmeticDecoder = (function ArithmeticDecoderClosure() {
  32200. // Table C-2
  32201. var QeTable = [
  32202. {qe: 0x5601, nmps: 1, nlps: 1, switchFlag: 1},
  32203. {qe: 0x3401, nmps: 2, nlps: 6, switchFlag: 0},
  32204. {qe: 0x1801, nmps: 3, nlps: 9, switchFlag: 0},
  32205. {qe: 0x0AC1, nmps: 4, nlps: 12, switchFlag: 0},
  32206. {qe: 0x0521, nmps: 5, nlps: 29, switchFlag: 0},
  32207. {qe: 0x0221, nmps: 38, nlps: 33, switchFlag: 0},
  32208. {qe: 0x5601, nmps: 7, nlps: 6, switchFlag: 1},
  32209. {qe: 0x5401, nmps: 8, nlps: 14, switchFlag: 0},
  32210. {qe: 0x4801, nmps: 9, nlps: 14, switchFlag: 0},
  32211. {qe: 0x3801, nmps: 10, nlps: 14, switchFlag: 0},
  32212. {qe: 0x3001, nmps: 11, nlps: 17, switchFlag: 0},
  32213. {qe: 0x2401, nmps: 12, nlps: 18, switchFlag: 0},
  32214. {qe: 0x1C01, nmps: 13, nlps: 20, switchFlag: 0},
  32215. {qe: 0x1601, nmps: 29, nlps: 21, switchFlag: 0},
  32216. {qe: 0x5601, nmps: 15, nlps: 14, switchFlag: 1},
  32217. {qe: 0x5401, nmps: 16, nlps: 14, switchFlag: 0},
  32218. {qe: 0x5101, nmps: 17, nlps: 15, switchFlag: 0},
  32219. {qe: 0x4801, nmps: 18, nlps: 16, switchFlag: 0},
  32220. {qe: 0x3801, nmps: 19, nlps: 17, switchFlag: 0},
  32221. {qe: 0x3401, nmps: 20, nlps: 18, switchFlag: 0},
  32222. {qe: 0x3001, nmps: 21, nlps: 19, switchFlag: 0},
  32223. {qe: 0x2801, nmps: 22, nlps: 19, switchFlag: 0},
  32224. {qe: 0x2401, nmps: 23, nlps: 20, switchFlag: 0},
  32225. {qe: 0x2201, nmps: 24, nlps: 21, switchFlag: 0},
  32226. {qe: 0x1C01, nmps: 25, nlps: 22, switchFlag: 0},
  32227. {qe: 0x1801, nmps: 26, nlps: 23, switchFlag: 0},
  32228. {qe: 0x1601, nmps: 27, nlps: 24, switchFlag: 0},
  32229. {qe: 0x1401, nmps: 28, nlps: 25, switchFlag: 0},
  32230. {qe: 0x1201, nmps: 29, nlps: 26, switchFlag: 0},
  32231. {qe: 0x1101, nmps: 30, nlps: 27, switchFlag: 0},
  32232. {qe: 0x0AC1, nmps: 31, nlps: 28, switchFlag: 0},
  32233. {qe: 0x09C1, nmps: 32, nlps: 29, switchFlag: 0},
  32234. {qe: 0x08A1, nmps: 33, nlps: 30, switchFlag: 0},
  32235. {qe: 0x0521, nmps: 34, nlps: 31, switchFlag: 0},
  32236. {qe: 0x0441, nmps: 35, nlps: 32, switchFlag: 0},
  32237. {qe: 0x02A1, nmps: 36, nlps: 33, switchFlag: 0},
  32238. {qe: 0x0221, nmps: 37, nlps: 34, switchFlag: 0},
  32239. {qe: 0x0141, nmps: 38, nlps: 35, switchFlag: 0},
  32240. {qe: 0x0111, nmps: 39, nlps: 36, switchFlag: 0},
  32241. {qe: 0x0085, nmps: 40, nlps: 37, switchFlag: 0},
  32242. {qe: 0x0049, nmps: 41, nlps: 38, switchFlag: 0},
  32243. {qe: 0x0025, nmps: 42, nlps: 39, switchFlag: 0},
  32244. {qe: 0x0015, nmps: 43, nlps: 40, switchFlag: 0},
  32245. {qe: 0x0009, nmps: 44, nlps: 41, switchFlag: 0},
  32246. {qe: 0x0005, nmps: 45, nlps: 42, switchFlag: 0},
  32247. {qe: 0x0001, nmps: 45, nlps: 43, switchFlag: 0},
  32248. {qe: 0x5601, nmps: 46, nlps: 46, switchFlag: 0}
  32249. ];
  32250. // C.3.5 Initialisation of the decoder (INITDEC)
  32251. function ArithmeticDecoder(data, start, end) {
  32252. this.data = data;
  32253. this.bp = start;
  32254. this.dataEnd = end;
  32255. this.chigh = data[start];
  32256. this.clow = 0;
  32257. this.byteIn();
  32258. this.chigh = ((this.chigh << 7) & 0xFFFF) | ((this.clow >> 9) & 0x7F);
  32259. this.clow = (this.clow << 7) & 0xFFFF;
  32260. this.ct -= 7;
  32261. this.a = 0x8000;
  32262. }
  32263. ArithmeticDecoder.prototype = {
  32264. // C.3.4 Compressed data input (BYTEIN)
  32265. byteIn: function ArithmeticDecoder_byteIn() {
  32266. var data = this.data;
  32267. var bp = this.bp;
  32268. if (data[bp] === 0xFF) {
  32269. var b1 = data[bp + 1];
  32270. if (b1 > 0x8F) {
  32271. this.clow += 0xFF00;
  32272. this.ct = 8;
  32273. } else {
  32274. bp++;
  32275. this.clow += (data[bp] << 9);
  32276. this.ct = 7;
  32277. this.bp = bp;
  32278. }
  32279. } else {
  32280. bp++;
  32281. this.clow += bp < this.dataEnd ? (data[bp] << 8) : 0xFF00;
  32282. this.ct = 8;
  32283. this.bp = bp;
  32284. }
  32285. if (this.clow > 0xFFFF) {
  32286. this.chigh += (this.clow >> 16);
  32287. this.clow &= 0xFFFF;
  32288. }
  32289. },
  32290. // C.3.2 Decoding a decision (DECODE)
  32291. readBit: function ArithmeticDecoder_readBit(contexts, pos) {
  32292. // contexts are packed into 1 byte:
  32293. // highest 7 bits carry cx.index, lowest bit carries cx.mps
  32294. var cx_index = contexts[pos] >> 1, cx_mps = contexts[pos] & 1;
  32295. var qeTableIcx = QeTable[cx_index];
  32296. var qeIcx = qeTableIcx.qe;
  32297. var d;
  32298. var a = this.a - qeIcx;
  32299. if (this.chigh < qeIcx) {
  32300. // exchangeLps
  32301. if (a < qeIcx) {
  32302. a = qeIcx;
  32303. d = cx_mps;
  32304. cx_index = qeTableIcx.nmps;
  32305. } else {
  32306. a = qeIcx;
  32307. d = 1 ^ cx_mps;
  32308. if (qeTableIcx.switchFlag === 1) {
  32309. cx_mps = d;
  32310. }
  32311. cx_index = qeTableIcx.nlps;
  32312. }
  32313. } else {
  32314. this.chigh -= qeIcx;
  32315. if ((a & 0x8000) !== 0) {
  32316. this.a = a;
  32317. return cx_mps;
  32318. }
  32319. // exchangeMps
  32320. if (a < qeIcx) {
  32321. d = 1 ^ cx_mps;
  32322. if (qeTableIcx.switchFlag === 1) {
  32323. cx_mps = d;
  32324. }
  32325. cx_index = qeTableIcx.nlps;
  32326. } else {
  32327. d = cx_mps;
  32328. cx_index = qeTableIcx.nmps;
  32329. }
  32330. }
  32331. // C.3.3 renormD;
  32332. do {
  32333. if (this.ct === 0) {
  32334. this.byteIn();
  32335. }
  32336. a <<= 1;
  32337. this.chigh = ((this.chigh << 1) & 0xFFFF) | ((this.clow >> 15) & 1);
  32338. this.clow = (this.clow << 1) & 0xFFFF;
  32339. this.ct--;
  32340. } while ((a & 0x8000) === 0);
  32341. this.a = a;
  32342. contexts[pos] = cx_index << 1 | cx_mps;
  32343. return d;
  32344. }
  32345. };
  32346. return ArithmeticDecoder;
  32347. })();
  32348. var JpegImage = (function jpegImage() {
  32349. var dctZigZag = new Uint8Array([
  32350. 0,
  32351. 1, 8,
  32352. 16, 9, 2,
  32353. 3, 10, 17, 24,
  32354. 32, 25, 18, 11, 4,
  32355. 5, 12, 19, 26, 33, 40,
  32356. 48, 41, 34, 27, 20, 13, 6,
  32357. 7, 14, 21, 28, 35, 42, 49, 56,
  32358. 57, 50, 43, 36, 29, 22, 15,
  32359. 23, 30, 37, 44, 51, 58,
  32360. 59, 52, 45, 38, 31,
  32361. 39, 46, 53, 60,
  32362. 61, 54, 47,
  32363. 55, 62,
  32364. 63
  32365. ]);
  32366. var dctCos1 = 4017; // cos(pi/16)
  32367. var dctSin1 = 799; // sin(pi/16)
  32368. var dctCos3 = 3406; // cos(3*pi/16)
  32369. var dctSin3 = 2276; // sin(3*pi/16)
  32370. var dctCos6 = 1567; // cos(6*pi/16)
  32371. var dctSin6 = 3784; // sin(6*pi/16)
  32372. var dctSqrt2 = 5793; // sqrt(2)
  32373. var dctSqrt1d2 = 2896; // sqrt(2) / 2
  32374. function constructor() {
  32375. }
  32376. function buildHuffmanTable(codeLengths, values) {
  32377. var k = 0, code = [], i, j, length = 16;
  32378. while (length > 0 && !codeLengths[length - 1]) {
  32379. length--;
  32380. }
  32381. code.push({children: [], index: 0});
  32382. var p = code[0], q;
  32383. for (i = 0; i < length; i++) {
  32384. for (j = 0; j < codeLengths[i]; j++) {
  32385. p = code.pop();
  32386. p.children[p.index] = values[k];
  32387. while (p.index > 0) {
  32388. p = code.pop();
  32389. }
  32390. p.index++;
  32391. code.push(p);
  32392. while (code.length <= i) {
  32393. code.push(q = {children: [], index: 0});
  32394. p.children[p.index] = q.children;
  32395. p = q;
  32396. }
  32397. k++;
  32398. }
  32399. if (i + 1 < length) {
  32400. // p here points to last code
  32401. code.push(q = {children: [], index: 0});
  32402. p.children[p.index] = q.children;
  32403. p = q;
  32404. }
  32405. }
  32406. return code[0].children;
  32407. }
  32408. function getBlockBufferOffset(component, row, col) {
  32409. return 64 * ((component.blocksPerLine + 1) * row + col);
  32410. }
  32411. function decodeScan(data, offset, frame, components, resetInterval,
  32412. spectralStart, spectralEnd, successivePrev, successive) {
  32413. var precision = frame.precision;
  32414. var samplesPerLine = frame.samplesPerLine;
  32415. var scanLines = frame.scanLines;
  32416. var mcusPerLine = frame.mcusPerLine;
  32417. var progressive = frame.progressive;
  32418. var maxH = frame.maxH, maxV = frame.maxV;
  32419. var startOffset = offset, bitsData = 0, bitsCount = 0;
  32420. function readBit() {
  32421. if (bitsCount > 0) {
  32422. bitsCount--;
  32423. return (bitsData >> bitsCount) & 1;
  32424. }
  32425. bitsData = data[offset++];
  32426. if (bitsData === 0xFF) {
  32427. var nextByte = data[offset++];
  32428. if (nextByte) {
  32429. throw 'unexpected marker: ' +
  32430. ((bitsData << 8) | nextByte).toString(16);
  32431. }
  32432. // unstuff 0
  32433. }
  32434. bitsCount = 7;
  32435. return bitsData >>> 7;
  32436. }
  32437. function decodeHuffman(tree) {
  32438. var node = tree;
  32439. while (true) {
  32440. node = node[readBit()];
  32441. if (typeof node === 'number') {
  32442. return node;
  32443. }
  32444. if (typeof node !== 'object') {
  32445. throw 'invalid huffman sequence';
  32446. }
  32447. }
  32448. }
  32449. function receive(length) {
  32450. var n = 0;
  32451. while (length > 0) {
  32452. n = (n << 1) | readBit();
  32453. length--;
  32454. }
  32455. return n;
  32456. }
  32457. function receiveAndExtend(length) {
  32458. if (length === 1) {
  32459. return readBit() === 1 ? 1 : -1;
  32460. }
  32461. var n = receive(length);
  32462. if (n >= 1 << (length - 1)) {
  32463. return n;
  32464. }
  32465. return n + (-1 << length) + 1;
  32466. }
  32467. function decodeBaseline(component, offset) {
  32468. var t = decodeHuffman(component.huffmanTableDC);
  32469. var diff = t === 0 ? 0 : receiveAndExtend(t);
  32470. component.blockData[offset] = (component.pred += diff);
  32471. var k = 1;
  32472. while (k < 64) {
  32473. var rs = decodeHuffman(component.huffmanTableAC);
  32474. var s = rs & 15, r = rs >> 4;
  32475. if (s === 0) {
  32476. if (r < 15) {
  32477. break;
  32478. }
  32479. k += 16;
  32480. continue;
  32481. }
  32482. k += r;
  32483. var z = dctZigZag[k];
  32484. component.blockData[offset + z] = receiveAndExtend(s);
  32485. k++;
  32486. }
  32487. }
  32488. function decodeDCFirst(component, offset) {
  32489. var t = decodeHuffman(component.huffmanTableDC);
  32490. var diff = t === 0 ? 0 : (receiveAndExtend(t) << successive);
  32491. component.blockData[offset] = (component.pred += diff);
  32492. }
  32493. function decodeDCSuccessive(component, offset) {
  32494. component.blockData[offset] |= readBit() << successive;
  32495. }
  32496. var eobrun = 0;
  32497. function decodeACFirst(component, offset) {
  32498. if (eobrun > 0) {
  32499. eobrun--;
  32500. return;
  32501. }
  32502. var k = spectralStart, e = spectralEnd;
  32503. while (k <= e) {
  32504. var rs = decodeHuffman(component.huffmanTableAC);
  32505. var s = rs & 15, r = rs >> 4;
  32506. if (s === 0) {
  32507. if (r < 15) {
  32508. eobrun = receive(r) + (1 << r) - 1;
  32509. break;
  32510. }
  32511. k += 16;
  32512. continue;
  32513. }
  32514. k += r;
  32515. var z = dctZigZag[k];
  32516. component.blockData[offset + z] =
  32517. receiveAndExtend(s) * (1 << successive);
  32518. k++;
  32519. }
  32520. }
  32521. var successiveACState = 0, successiveACNextValue;
  32522. function decodeACSuccessive(component, offset) {
  32523. var k = spectralStart;
  32524. var e = spectralEnd;
  32525. var r = 0;
  32526. var s;
  32527. var rs;
  32528. while (k <= e) {
  32529. var z = dctZigZag[k];
  32530. switch (successiveACState) {
  32531. case 0: // initial state
  32532. rs = decodeHuffman(component.huffmanTableAC);
  32533. s = rs & 15;
  32534. r = rs >> 4;
  32535. if (s === 0) {
  32536. if (r < 15) {
  32537. eobrun = receive(r) + (1 << r);
  32538. successiveACState = 4;
  32539. } else {
  32540. r = 16;
  32541. successiveACState = 1;
  32542. }
  32543. } else {
  32544. if (s !== 1) {
  32545. throw 'invalid ACn encoding';
  32546. }
  32547. successiveACNextValue = receiveAndExtend(s);
  32548. successiveACState = r ? 2 : 3;
  32549. }
  32550. continue;
  32551. case 1: // skipping r zero items
  32552. case 2:
  32553. if (component.blockData[offset + z]) {
  32554. component.blockData[offset + z] += (readBit() << successive);
  32555. } else {
  32556. r--;
  32557. if (r === 0) {
  32558. successiveACState = successiveACState === 2 ? 3 : 0;
  32559. }
  32560. }
  32561. break;
  32562. case 3: // set value for a zero item
  32563. if (component.blockData[offset + z]) {
  32564. component.blockData[offset + z] += (readBit() << successive);
  32565. } else {
  32566. component.blockData[offset + z] =
  32567. successiveACNextValue << successive;
  32568. successiveACState = 0;
  32569. }
  32570. break;
  32571. case 4: // eob
  32572. if (component.blockData[offset + z]) {
  32573. component.blockData[offset + z] += (readBit() << successive);
  32574. }
  32575. break;
  32576. }
  32577. k++;
  32578. }
  32579. if (successiveACState === 4) {
  32580. eobrun--;
  32581. if (eobrun === 0) {
  32582. successiveACState = 0;
  32583. }
  32584. }
  32585. }
  32586. function decodeMcu(component, decode, mcu, row, col) {
  32587. var mcuRow = (mcu / mcusPerLine) | 0;
  32588. var mcuCol = mcu % mcusPerLine;
  32589. var blockRow = mcuRow * component.v + row;
  32590. var blockCol = mcuCol * component.h + col;
  32591. var offset = getBlockBufferOffset(component, blockRow, blockCol);
  32592. decode(component, offset);
  32593. }
  32594. function decodeBlock(component, decode, mcu) {
  32595. var blockRow = (mcu / component.blocksPerLine) | 0;
  32596. var blockCol = mcu % component.blocksPerLine;
  32597. var offset = getBlockBufferOffset(component, blockRow, blockCol);
  32598. decode(component, offset);
  32599. }
  32600. var componentsLength = components.length;
  32601. var component, i, j, k, n;
  32602. var decodeFn;
  32603. if (progressive) {
  32604. if (spectralStart === 0) {
  32605. decodeFn = successivePrev === 0 ? decodeDCFirst : decodeDCSuccessive;
  32606. } else {
  32607. decodeFn = successivePrev === 0 ? decodeACFirst : decodeACSuccessive;
  32608. }
  32609. } else {
  32610. decodeFn = decodeBaseline;
  32611. }
  32612. var mcu = 0, marker;
  32613. var mcuExpected;
  32614. if (componentsLength === 1) {
  32615. mcuExpected = components[0].blocksPerLine * components[0].blocksPerColumn;
  32616. } else {
  32617. mcuExpected = mcusPerLine * frame.mcusPerColumn;
  32618. }
  32619. if (!resetInterval) {
  32620. resetInterval = mcuExpected;
  32621. }
  32622. var h, v;
  32623. while (mcu < mcuExpected) {
  32624. // reset interval stuff
  32625. for (i = 0; i < componentsLength; i++) {
  32626. components[i].pred = 0;
  32627. }
  32628. eobrun = 0;
  32629. if (componentsLength === 1) {
  32630. component = components[0];
  32631. for (n = 0; n < resetInterval; n++) {
  32632. decodeBlock(component, decodeFn, mcu);
  32633. mcu++;
  32634. }
  32635. } else {
  32636. for (n = 0; n < resetInterval; n++) {
  32637. for (i = 0; i < componentsLength; i++) {
  32638. component = components[i];
  32639. h = component.h;
  32640. v = component.v;
  32641. for (j = 0; j < v; j++) {
  32642. for (k = 0; k < h; k++) {
  32643. decodeMcu(component, decodeFn, mcu, j, k);
  32644. }
  32645. }
  32646. }
  32647. mcu++;
  32648. }
  32649. }
  32650. // find marker
  32651. bitsCount = 0;
  32652. marker = (data[offset] << 8) | data[offset + 1];
  32653. if (marker <= 0xFF00) {
  32654. throw 'marker was not found';
  32655. }
  32656. if (marker >= 0xFFD0 && marker <= 0xFFD7) { // RSTx
  32657. offset += 2;
  32658. } else {
  32659. break;
  32660. }
  32661. }
  32662. return offset - startOffset;
  32663. }
  32664. // A port of poppler's IDCT method which in turn is taken from:
  32665. // Christoph Loeffler, Adriaan Ligtenberg, George S. Moschytz,
  32666. // 'Practical Fast 1-D DCT Algorithms with 11 Multiplications',
  32667. // IEEE Intl. Conf. on Acoustics, Speech & Signal Processing, 1989,
  32668. // 988-991.
  32669. function quantizeAndInverse(component, blockBufferOffset, p) {
  32670. var qt = component.quantizationTable, blockData = component.blockData;
  32671. var v0, v1, v2, v3, v4, v5, v6, v7;
  32672. var p0, p1, p2, p3, p4, p5, p6, p7;
  32673. var t;
  32674. // inverse DCT on rows
  32675. for (var row = 0; row < 64; row += 8) {
  32676. // gather block data
  32677. p0 = blockData[blockBufferOffset + row];
  32678. p1 = blockData[blockBufferOffset + row + 1];
  32679. p2 = blockData[blockBufferOffset + row + 2];
  32680. p3 = blockData[blockBufferOffset + row + 3];
  32681. p4 = blockData[blockBufferOffset + row + 4];
  32682. p5 = blockData[blockBufferOffset + row + 5];
  32683. p6 = blockData[blockBufferOffset + row + 6];
  32684. p7 = blockData[blockBufferOffset + row + 7];
  32685. // dequant p0
  32686. p0 *= qt[row];
  32687. // check for all-zero AC coefficients
  32688. if ((p1 | p2 | p3 | p4 | p5 | p6 | p7) === 0) {
  32689. t = (dctSqrt2 * p0 + 512) >> 10;
  32690. p[row] = t;
  32691. p[row + 1] = t;
  32692. p[row + 2] = t;
  32693. p[row + 3] = t;
  32694. p[row + 4] = t;
  32695. p[row + 5] = t;
  32696. p[row + 6] = t;
  32697. p[row + 7] = t;
  32698. continue;
  32699. }
  32700. // dequant p1 ... p7
  32701. p1 *= qt[row + 1];
  32702. p2 *= qt[row + 2];
  32703. p3 *= qt[row + 3];
  32704. p4 *= qt[row + 4];
  32705. p5 *= qt[row + 5];
  32706. p6 *= qt[row + 6];
  32707. p7 *= qt[row + 7];
  32708. // stage 4
  32709. v0 = (dctSqrt2 * p0 + 128) >> 8;
  32710. v1 = (dctSqrt2 * p4 + 128) >> 8;
  32711. v2 = p2;
  32712. v3 = p6;
  32713. v4 = (dctSqrt1d2 * (p1 - p7) + 128) >> 8;
  32714. v7 = (dctSqrt1d2 * (p1 + p7) + 128) >> 8;
  32715. v5 = p3 << 4;
  32716. v6 = p5 << 4;
  32717. // stage 3
  32718. v0 = (v0 + v1 + 1) >> 1;
  32719. v1 = v0 - v1;
  32720. t = (v2 * dctSin6 + v3 * dctCos6 + 128) >> 8;
  32721. v2 = (v2 * dctCos6 - v3 * dctSin6 + 128) >> 8;
  32722. v3 = t;
  32723. v4 = (v4 + v6 + 1) >> 1;
  32724. v6 = v4 - v6;
  32725. v7 = (v7 + v5 + 1) >> 1;
  32726. v5 = v7 - v5;
  32727. // stage 2
  32728. v0 = (v0 + v3 + 1) >> 1;
  32729. v3 = v0 - v3;
  32730. v1 = (v1 + v2 + 1) >> 1;
  32731. v2 = v1 - v2;
  32732. t = (v4 * dctSin3 + v7 * dctCos3 + 2048) >> 12;
  32733. v4 = (v4 * dctCos3 - v7 * dctSin3 + 2048) >> 12;
  32734. v7 = t;
  32735. t = (v5 * dctSin1 + v6 * dctCos1 + 2048) >> 12;
  32736. v5 = (v5 * dctCos1 - v6 * dctSin1 + 2048) >> 12;
  32737. v6 = t;
  32738. // stage 1
  32739. p[row] = v0 + v7;
  32740. p[row + 7] = v0 - v7;
  32741. p[row + 1] = v1 + v6;
  32742. p[row + 6] = v1 - v6;
  32743. p[row + 2] = v2 + v5;
  32744. p[row + 5] = v2 - v5;
  32745. p[row + 3] = v3 + v4;
  32746. p[row + 4] = v3 - v4;
  32747. }
  32748. // inverse DCT on columns
  32749. for (var col = 0; col < 8; ++col) {
  32750. p0 = p[col];
  32751. p1 = p[col + 8];
  32752. p2 = p[col + 16];
  32753. p3 = p[col + 24];
  32754. p4 = p[col + 32];
  32755. p5 = p[col + 40];
  32756. p6 = p[col + 48];
  32757. p7 = p[col + 56];
  32758. // check for all-zero AC coefficients
  32759. if ((p1 | p2 | p3 | p4 | p5 | p6 | p7) === 0) {
  32760. t = (dctSqrt2 * p0 + 8192) >> 14;
  32761. // convert to 8 bit
  32762. t = (t < -2040) ? 0 : (t >= 2024) ? 255 : (t + 2056) >> 4;
  32763. blockData[blockBufferOffset + col] = t;
  32764. blockData[blockBufferOffset + col + 8] = t;
  32765. blockData[blockBufferOffset + col + 16] = t;
  32766. blockData[blockBufferOffset + col + 24] = t;
  32767. blockData[blockBufferOffset + col + 32] = t;
  32768. blockData[blockBufferOffset + col + 40] = t;
  32769. blockData[blockBufferOffset + col + 48] = t;
  32770. blockData[blockBufferOffset + col + 56] = t;
  32771. continue;
  32772. }
  32773. // stage 4
  32774. v0 = (dctSqrt2 * p0 + 2048) >> 12;
  32775. v1 = (dctSqrt2 * p4 + 2048) >> 12;
  32776. v2 = p2;
  32777. v3 = p6;
  32778. v4 = (dctSqrt1d2 * (p1 - p7) + 2048) >> 12;
  32779. v7 = (dctSqrt1d2 * (p1 + p7) + 2048) >> 12;
  32780. v5 = p3;
  32781. v6 = p5;
  32782. // stage 3
  32783. // Shift v0 by 128.5 << 5 here, so we don't need to shift p0...p7 when
  32784. // converting to UInt8 range later.
  32785. v0 = ((v0 + v1 + 1) >> 1) + 4112;
  32786. v1 = v0 - v1;
  32787. t = (v2 * dctSin6 + v3 * dctCos6 + 2048) >> 12;
  32788. v2 = (v2 * dctCos6 - v3 * dctSin6 + 2048) >> 12;
  32789. v3 = t;
  32790. v4 = (v4 + v6 + 1) >> 1;
  32791. v6 = v4 - v6;
  32792. v7 = (v7 + v5 + 1) >> 1;
  32793. v5 = v7 - v5;
  32794. // stage 2
  32795. v0 = (v0 + v3 + 1) >> 1;
  32796. v3 = v0 - v3;
  32797. v1 = (v1 + v2 + 1) >> 1;
  32798. v2 = v1 - v2;
  32799. t = (v4 * dctSin3 + v7 * dctCos3 + 2048) >> 12;
  32800. v4 = (v4 * dctCos3 - v7 * dctSin3 + 2048) >> 12;
  32801. v7 = t;
  32802. t = (v5 * dctSin1 + v6 * dctCos1 + 2048) >> 12;
  32803. v5 = (v5 * dctCos1 - v6 * dctSin1 + 2048) >> 12;
  32804. v6 = t;
  32805. // stage 1
  32806. p0 = v0 + v7;
  32807. p7 = v0 - v7;
  32808. p1 = v1 + v6;
  32809. p6 = v1 - v6;
  32810. p2 = v2 + v5;
  32811. p5 = v2 - v5;
  32812. p3 = v3 + v4;
  32813. p4 = v3 - v4;
  32814. // convert to 8-bit integers
  32815. p0 = (p0 < 16) ? 0 : (p0 >= 4080) ? 255 : p0 >> 4;
  32816. p1 = (p1 < 16) ? 0 : (p1 >= 4080) ? 255 : p1 >> 4;
  32817. p2 = (p2 < 16) ? 0 : (p2 >= 4080) ? 255 : p2 >> 4;
  32818. p3 = (p3 < 16) ? 0 : (p3 >= 4080) ? 255 : p3 >> 4;
  32819. p4 = (p4 < 16) ? 0 : (p4 >= 4080) ? 255 : p4 >> 4;
  32820. p5 = (p5 < 16) ? 0 : (p5 >= 4080) ? 255 : p5 >> 4;
  32821. p6 = (p6 < 16) ? 0 : (p6 >= 4080) ? 255 : p6 >> 4;
  32822. p7 = (p7 < 16) ? 0 : (p7 >= 4080) ? 255 : p7 >> 4;
  32823. // store block data
  32824. blockData[blockBufferOffset + col] = p0;
  32825. blockData[blockBufferOffset + col + 8] = p1;
  32826. blockData[blockBufferOffset + col + 16] = p2;
  32827. blockData[blockBufferOffset + col + 24] = p3;
  32828. blockData[blockBufferOffset + col + 32] = p4;
  32829. blockData[blockBufferOffset + col + 40] = p5;
  32830. blockData[blockBufferOffset + col + 48] = p6;
  32831. blockData[blockBufferOffset + col + 56] = p7;
  32832. }
  32833. }
  32834. function buildComponentData(frame, component) {
  32835. var blocksPerLine = component.blocksPerLine;
  32836. var blocksPerColumn = component.blocksPerColumn;
  32837. var computationBuffer = new Int16Array(64);
  32838. for (var blockRow = 0; blockRow < blocksPerColumn; blockRow++) {
  32839. for (var blockCol = 0; blockCol < blocksPerLine; blockCol++) {
  32840. var offset = getBlockBufferOffset(component, blockRow, blockCol);
  32841. quantizeAndInverse(component, offset, computationBuffer);
  32842. }
  32843. }
  32844. return component.blockData;
  32845. }
  32846. function clamp0to255(a) {
  32847. return a <= 0 ? 0 : a >= 255 ? 255 : a;
  32848. }
  32849. constructor.prototype = {
  32850. parse: function parse(data) {
  32851. function readUint16() {
  32852. var value = (data[offset] << 8) | data[offset + 1];
  32853. offset += 2;
  32854. return value;
  32855. }
  32856. function readDataBlock() {
  32857. var length = readUint16();
  32858. var array = data.subarray(offset, offset + length - 2);
  32859. offset += array.length;
  32860. return array;
  32861. }
  32862. function prepareComponents(frame) {
  32863. var mcusPerLine = Math.ceil(frame.samplesPerLine / 8 / frame.maxH);
  32864. var mcusPerColumn = Math.ceil(frame.scanLines / 8 / frame.maxV);
  32865. for (var i = 0; i < frame.components.length; i++) {
  32866. component = frame.components[i];
  32867. var blocksPerLine = Math.ceil(Math.ceil(frame.samplesPerLine / 8) *
  32868. component.h / frame.maxH);
  32869. var blocksPerColumn = Math.ceil(Math.ceil(frame.scanLines / 8) *
  32870. component.v / frame.maxV);
  32871. var blocksPerLineForMcu = mcusPerLine * component.h;
  32872. var blocksPerColumnForMcu = mcusPerColumn * component.v;
  32873. var blocksBufferSize = 64 * blocksPerColumnForMcu *
  32874. (blocksPerLineForMcu + 1);
  32875. component.blockData = new Int16Array(blocksBufferSize);
  32876. component.blocksPerLine = blocksPerLine;
  32877. component.blocksPerColumn = blocksPerColumn;
  32878. }
  32879. frame.mcusPerLine = mcusPerLine;
  32880. frame.mcusPerColumn = mcusPerColumn;
  32881. }
  32882. var offset = 0, length = data.length;
  32883. var jfif = null;
  32884. var adobe = null;
  32885. var pixels = null;
  32886. var frame, resetInterval;
  32887. var quantizationTables = [];
  32888. var huffmanTablesAC = [], huffmanTablesDC = [];
  32889. var fileMarker = readUint16();
  32890. if (fileMarker !== 0xFFD8) { // SOI (Start of Image)
  32891. throw 'SOI not found';
  32892. }
  32893. fileMarker = readUint16();
  32894. while (fileMarker !== 0xFFD9) { // EOI (End of image)
  32895. var i, j, l;
  32896. switch(fileMarker) {
  32897. case 0xFFE0: // APP0 (Application Specific)
  32898. case 0xFFE1: // APP1
  32899. case 0xFFE2: // APP2
  32900. case 0xFFE3: // APP3
  32901. case 0xFFE4: // APP4
  32902. case 0xFFE5: // APP5
  32903. case 0xFFE6: // APP6
  32904. case 0xFFE7: // APP7
  32905. case 0xFFE8: // APP8
  32906. case 0xFFE9: // APP9
  32907. case 0xFFEA: // APP10
  32908. case 0xFFEB: // APP11
  32909. case 0xFFEC: // APP12
  32910. case 0xFFED: // APP13
  32911. case 0xFFEE: // APP14
  32912. case 0xFFEF: // APP15
  32913. case 0xFFFE: // COM (Comment)
  32914. var appData = readDataBlock();
  32915. if (fileMarker === 0xFFE0) {
  32916. if (appData[0] === 0x4A && appData[1] === 0x46 &&
  32917. appData[2] === 0x49 && appData[3] === 0x46 &&
  32918. appData[4] === 0) { // 'JFIF\x00'
  32919. jfif = {
  32920. version: { major: appData[5], minor: appData[6] },
  32921. densityUnits: appData[7],
  32922. xDensity: (appData[8] << 8) | appData[9],
  32923. yDensity: (appData[10] << 8) | appData[11],
  32924. thumbWidth: appData[12],
  32925. thumbHeight: appData[13],
  32926. thumbData: appData.subarray(14, 14 +
  32927. 3 * appData[12] * appData[13])
  32928. };
  32929. }
  32930. }
  32931. // TODO APP1 - Exif
  32932. if (fileMarker === 0xFFEE) {
  32933. if (appData[0] === 0x41 && appData[1] === 0x64 &&
  32934. appData[2] === 0x6F && appData[3] === 0x62 &&
  32935. appData[4] === 0x65) { // 'Adobe'
  32936. adobe = {
  32937. version: (appData[5] << 8) | appData[6],
  32938. flags0: (appData[7] << 8) | appData[8],
  32939. flags1: (appData[9] << 8) | appData[10],
  32940. transformCode: appData[11]
  32941. };
  32942. }
  32943. }
  32944. break;
  32945. case 0xFFDB: // DQT (Define Quantization Tables)
  32946. var quantizationTablesLength = readUint16();
  32947. var quantizationTablesEnd = quantizationTablesLength + offset - 2;
  32948. var z;
  32949. while (offset < quantizationTablesEnd) {
  32950. var quantizationTableSpec = data[offset++];
  32951. var tableData = new Uint16Array(64);
  32952. if ((quantizationTableSpec >> 4) === 0) { // 8 bit values
  32953. for (j = 0; j < 64; j++) {
  32954. z = dctZigZag[j];
  32955. tableData[z] = data[offset++];
  32956. }
  32957. } else if ((quantizationTableSpec >> 4) === 1) { //16 bit
  32958. for (j = 0; j < 64; j++) {
  32959. z = dctZigZag[j];
  32960. tableData[z] = readUint16();
  32961. }
  32962. } else {
  32963. throw 'DQT: invalid table spec';
  32964. }
  32965. quantizationTables[quantizationTableSpec & 15] = tableData;
  32966. }
  32967. break;
  32968. case 0xFFC0: // SOF0 (Start of Frame, Baseline DCT)
  32969. case 0xFFC1: // SOF1 (Start of Frame, Extended DCT)
  32970. case 0xFFC2: // SOF2 (Start of Frame, Progressive DCT)
  32971. if (frame) {
  32972. throw 'Only single frame JPEGs supported';
  32973. }
  32974. readUint16(); // skip data length
  32975. frame = {};
  32976. frame.extended = (fileMarker === 0xFFC1);
  32977. frame.progressive = (fileMarker === 0xFFC2);
  32978. frame.precision = data[offset++];
  32979. frame.scanLines = readUint16();
  32980. frame.samplesPerLine = readUint16();
  32981. frame.components = [];
  32982. frame.componentIds = {};
  32983. var componentsCount = data[offset++], componentId;
  32984. var maxH = 0, maxV = 0;
  32985. for (i = 0; i < componentsCount; i++) {
  32986. componentId = data[offset];
  32987. var h = data[offset + 1] >> 4;
  32988. var v = data[offset + 1] & 15;
  32989. if (maxH < h) {
  32990. maxH = h;
  32991. }
  32992. if (maxV < v) {
  32993. maxV = v;
  32994. }
  32995. var qId = data[offset + 2];
  32996. l = frame.components.push({
  32997. h: h,
  32998. v: v,
  32999. quantizationTable: quantizationTables[qId]
  33000. });
  33001. frame.componentIds[componentId] = l - 1;
  33002. offset += 3;
  33003. }
  33004. frame.maxH = maxH;
  33005. frame.maxV = maxV;
  33006. prepareComponents(frame);
  33007. break;
  33008. case 0xFFC4: // DHT (Define Huffman Tables)
  33009. var huffmanLength = readUint16();
  33010. for (i = 2; i < huffmanLength;) {
  33011. var huffmanTableSpec = data[offset++];
  33012. var codeLengths = new Uint8Array(16);
  33013. var codeLengthSum = 0;
  33014. for (j = 0; j < 16; j++, offset++) {
  33015. codeLengthSum += (codeLengths[j] = data[offset]);
  33016. }
  33017. var huffmanValues = new Uint8Array(codeLengthSum);
  33018. for (j = 0; j < codeLengthSum; j++, offset++) {
  33019. huffmanValues[j] = data[offset];
  33020. }
  33021. i += 17 + codeLengthSum;
  33022. ((huffmanTableSpec >> 4) === 0 ?
  33023. huffmanTablesDC : huffmanTablesAC)[huffmanTableSpec & 15] =
  33024. buildHuffmanTable(codeLengths, huffmanValues);
  33025. }
  33026. break;
  33027. case 0xFFDD: // DRI (Define Restart Interval)
  33028. readUint16(); // skip data length
  33029. resetInterval = readUint16();
  33030. break;
  33031. case 0xFFDA: // SOS (Start of Scan)
  33032. var scanLength = readUint16();
  33033. var selectorsCount = data[offset++];
  33034. var components = [], component;
  33035. for (i = 0; i < selectorsCount; i++) {
  33036. var componentIndex = frame.componentIds[data[offset++]];
  33037. component = frame.components[componentIndex];
  33038. var tableSpec = data[offset++];
  33039. component.huffmanTableDC = huffmanTablesDC[tableSpec >> 4];
  33040. component.huffmanTableAC = huffmanTablesAC[tableSpec & 15];
  33041. components.push(component);
  33042. }
  33043. var spectralStart = data[offset++];
  33044. var spectralEnd = data[offset++];
  33045. var successiveApproximation = data[offset++];
  33046. var processed = decodeScan(data, offset,
  33047. frame, components, resetInterval,
  33048. spectralStart, spectralEnd,
  33049. successiveApproximation >> 4, successiveApproximation & 15);
  33050. offset += processed;
  33051. break;
  33052. case 0xFFFF: // Fill bytes
  33053. if (data[offset] !== 0xFF) { // Avoid skipping a valid marker.
  33054. offset--;
  33055. }
  33056. break;
  33057. default:
  33058. if (data[offset - 3] === 0xFF &&
  33059. data[offset - 2] >= 0xC0 && data[offset - 2] <= 0xFE) {
  33060. // could be incorrect encoding -- last 0xFF byte of the previous
  33061. // block was eaten by the encoder
  33062. offset -= 3;
  33063. break;
  33064. }
  33065. throw 'unknown JPEG marker ' + fileMarker.toString(16);
  33066. }
  33067. fileMarker = readUint16();
  33068. }
  33069. this.width = frame.samplesPerLine;
  33070. this.height = frame.scanLines;
  33071. this.jfif = jfif;
  33072. this.adobe = adobe;
  33073. this.components = [];
  33074. for (i = 0; i < frame.components.length; i++) {
  33075. component = frame.components[i];
  33076. this.components.push({
  33077. output: buildComponentData(frame, component),
  33078. scaleX: component.h / frame.maxH,
  33079. scaleY: component.v / frame.maxV,
  33080. blocksPerLine: component.blocksPerLine,
  33081. blocksPerColumn: component.blocksPerColumn
  33082. });
  33083. }
  33084. this.numComponents = this.components.length;
  33085. },
  33086. _getLinearizedBlockData: function getLinearizedBlockData(width, height) {
  33087. var scaleX = this.width / width, scaleY = this.height / height;
  33088. var component, componentScaleX, componentScaleY, blocksPerScanline;
  33089. var x, y, i, j, k;
  33090. var index;
  33091. var offset = 0;
  33092. var output;
  33093. var numComponents = this.components.length;
  33094. var dataLength = width * height * numComponents;
  33095. var data = new Uint8Array(dataLength);
  33096. var xScaleBlockOffset = new Uint32Array(width);
  33097. var mask3LSB = 0xfffffff8; // used to clear the 3 LSBs
  33098. for (i = 0; i < numComponents; i++) {
  33099. component = this.components[i];
  33100. componentScaleX = component.scaleX * scaleX;
  33101. componentScaleY = component.scaleY * scaleY;
  33102. offset = i;
  33103. output = component.output;
  33104. blocksPerScanline = (component.blocksPerLine + 1) << 3;
  33105. // precalculate the xScaleBlockOffset
  33106. for (x = 0; x < width; x++) {
  33107. j = 0 | (x * componentScaleX);
  33108. xScaleBlockOffset[x] = ((j & mask3LSB) << 3) | (j & 7);
  33109. }
  33110. // linearize the blocks of the component
  33111. for (y = 0; y < height; y++) {
  33112. j = 0 | (y * componentScaleY);
  33113. index = blocksPerScanline * (j & mask3LSB) | ((j & 7) << 3);
  33114. for (x = 0; x < width; x++) {
  33115. data[offset] = output[index + xScaleBlockOffset[x]];
  33116. offset += numComponents;
  33117. }
  33118. }
  33119. }
  33120. // decodeTransform contains pairs of multiplier (-256..256) and additive
  33121. var transform = this.decodeTransform;
  33122. if (transform) {
  33123. for (i = 0; i < dataLength;) {
  33124. for (j = 0, k = 0; j < numComponents; j++, i++, k += 2) {
  33125. data[i] = ((data[i] * transform[k]) >> 8) + transform[k + 1];
  33126. }
  33127. }
  33128. }
  33129. return data;
  33130. },
  33131. _isColorConversionNeeded: function isColorConversionNeeded() {
  33132. if (this.adobe && this.adobe.transformCode) {
  33133. // The adobe transform marker overrides any previous setting
  33134. return true;
  33135. } else if (this.numComponents === 3) {
  33136. return true;
  33137. } else {
  33138. return false;
  33139. }
  33140. },
  33141. _convertYccToRgb: function convertYccToRgb(data) {
  33142. var Y, Cb, Cr;
  33143. for (var i = 0, length = data.length; i < length; i += 3) {
  33144. Y = data[i ];
  33145. Cb = data[i + 1];
  33146. Cr = data[i + 2];
  33147. data[i ] = clamp0to255(Y - 179.456 + 1.402 * Cr);
  33148. data[i + 1] = clamp0to255(Y + 135.459 - 0.344 * Cb - 0.714 * Cr);
  33149. data[i + 2] = clamp0to255(Y - 226.816 + 1.772 * Cb);
  33150. }
  33151. return data;
  33152. },
  33153. _convertYcckToRgb: function convertYcckToRgb(data) {
  33154. var Y, Cb, Cr, k;
  33155. var offset = 0;
  33156. for (var i = 0, length = data.length; i < length; i += 4) {
  33157. Y = data[i];
  33158. Cb = data[i + 1];
  33159. Cr = data[i + 2];
  33160. k = data[i + 3];
  33161. var r = -122.67195406894 +
  33162. Cb * (-6.60635669420364e-5 * Cb + 0.000437130475926232 * Cr -
  33163. 5.4080610064599e-5 * Y + 0.00048449797120281 * k -
  33164. 0.154362151871126) +
  33165. Cr * (-0.000957964378445773 * Cr + 0.000817076911346625 * Y -
  33166. 0.00477271405408747 * k + 1.53380253221734) +
  33167. Y * (0.000961250184130688 * Y - 0.00266257332283933 * k +
  33168. 0.48357088451265) +
  33169. k * (-0.000336197177618394 * k + 0.484791561490776);
  33170. var g = 107.268039397724 +
  33171. Cb * (2.19927104525741e-5 * Cb - 0.000640992018297945 * Cr +
  33172. 0.000659397001245577 * Y + 0.000426105652938837 * k -
  33173. 0.176491792462875) +
  33174. Cr * (-0.000778269941513683 * Cr + 0.00130872261408275 * Y +
  33175. 0.000770482631801132 * k - 0.151051492775562) +
  33176. Y * (0.00126935368114843 * Y - 0.00265090189010898 * k +
  33177. 0.25802910206845) +
  33178. k * (-0.000318913117588328 * k - 0.213742400323665);
  33179. var b = -20.810012546947 +
  33180. Cb * (-0.000570115196973677 * Cb - 2.63409051004589e-5 * Cr +
  33181. 0.0020741088115012 * Y - 0.00288260236853442 * k +
  33182. 0.814272968359295) +
  33183. Cr * (-1.53496057440975e-5 * Cr - 0.000132689043961446 * Y +
  33184. 0.000560833691242812 * k - 0.195152027534049) +
  33185. Y * (0.00174418132927582 * Y - 0.00255243321439347 * k +
  33186. 0.116935020465145) +
  33187. k * (-0.000343531996510555 * k + 0.24165260232407);
  33188. data[offset++] = clamp0to255(r);
  33189. data[offset++] = clamp0to255(g);
  33190. data[offset++] = clamp0to255(b);
  33191. }
  33192. return data;
  33193. },
  33194. _convertYcckToCmyk: function convertYcckToCmyk(data) {
  33195. var Y, Cb, Cr;
  33196. for (var i = 0, length = data.length; i < length; i += 4) {
  33197. Y = data[i];
  33198. Cb = data[i + 1];
  33199. Cr = data[i + 2];
  33200. data[i ] = clamp0to255(434.456 - Y - 1.402 * Cr);
  33201. data[i + 1] = clamp0to255(119.541 - Y + 0.344 * Cb + 0.714 * Cr);
  33202. data[i + 2] = clamp0to255(481.816 - Y - 1.772 * Cb);
  33203. // K in data[i + 3] is unchanged
  33204. }
  33205. return data;
  33206. },
  33207. _convertCmykToRgb: function convertCmykToRgb(data) {
  33208. var c, m, y, k;
  33209. var offset = 0;
  33210. var min = -255 * 255 * 255;
  33211. var scale = 1 / 255 / 255;
  33212. for (var i = 0, length = data.length; i < length; i += 4) {
  33213. c = data[i];
  33214. m = data[i + 1];
  33215. y = data[i + 2];
  33216. k = data[i + 3];
  33217. var r =
  33218. c * (-4.387332384609988 * c + 54.48615194189176 * m +
  33219. 18.82290502165302 * y + 212.25662451639585 * k -
  33220. 72734.4411664936) +
  33221. m * (1.7149763477362134 * m - 5.6096736904047315 * y -
  33222. 17.873870861415444 * k - 1401.7366389350734) +
  33223. y * (-2.5217340131683033 * y - 21.248923337353073 * k +
  33224. 4465.541406466231) -
  33225. k * (21.86122147463605 * k + 48317.86113160301);
  33226. var g =
  33227. c * (8.841041422036149 * c + 60.118027045597366 * m +
  33228. 6.871425592049007 * y + 31.159100130055922 * k -
  33229. 20220.756542821975) +
  33230. m * (-15.310361306967817 * m + 17.575251261109482 * y +
  33231. 131.35250912493976 * k - 48691.05921601825) +
  33232. y * (4.444339102852739 * y + 9.8632861493405 * k -
  33233. 6341.191035517494) -
  33234. k * (20.737325471181034 * k + 47890.15695978492);
  33235. var b =
  33236. c * (0.8842522430003296 * c + 8.078677503112928 * m +
  33237. 30.89978309703729 * y - 0.23883238689178934 * k -
  33238. 3616.812083916688) +
  33239. m * (10.49593273432072 * m + 63.02378494754052 * y +
  33240. 50.606957656360734 * k - 28620.90484698408) +
  33241. y * (0.03296041114873217 * y + 115.60384449646641 * k -
  33242. 49363.43385999684) -
  33243. k * (22.33816807309886 * k + 45932.16563550634);
  33244. data[offset++] = r >= 0 ? 255 : r <= min ? 0 : 255 + r * scale | 0;
  33245. data[offset++] = g >= 0 ? 255 : g <= min ? 0 : 255 + g * scale | 0;
  33246. data[offset++] = b >= 0 ? 255 : b <= min ? 0 : 255 + b * scale | 0;
  33247. }
  33248. return data;
  33249. },
  33250. getData: function getData(width, height, forceRGBoutput) {
  33251. if (this.numComponents > 4) {
  33252. throw 'Unsupported color mode';
  33253. }
  33254. // type of data: Uint8Array(width * height * numComponents)
  33255. var data = this._getLinearizedBlockData(width, height);
  33256. if (this.numComponents === 3) {
  33257. return this._convertYccToRgb(data);
  33258. } else if (this.numComponents === 4) {
  33259. if (this._isColorConversionNeeded()) {
  33260. if (forceRGBoutput) {
  33261. return this._convertYcckToRgb(data);
  33262. } else {
  33263. return this._convertYcckToCmyk(data);
  33264. }
  33265. } else if (forceRGBoutput) {
  33266. return this._convertCmykToRgb(data);
  33267. }
  33268. }
  33269. return data;
  33270. }
  33271. };
  33272. return constructor;
  33273. })();
  33274. var JpxImage = (function JpxImageClosure() {
  33275. // Table E.1
  33276. var SubbandsGainLog2 = {
  33277. 'LL': 0,
  33278. 'LH': 1,
  33279. 'HL': 1,
  33280. 'HH': 2
  33281. };
  33282. function JpxImage() {
  33283. this.failOnCorruptedImage = false;
  33284. }
  33285. JpxImage.prototype = {
  33286. parse: function JpxImage_parse(data) {
  33287. var head = readUint16(data, 0);
  33288. // No box header, immediate start of codestream (SOC)
  33289. if (head === 0xFF4F) {
  33290. this.parseCodestream(data, 0, data.length);
  33291. return;
  33292. }
  33293. var position = 0, length = data.length;
  33294. while (position < length) {
  33295. var headerSize = 8;
  33296. var lbox = readUint32(data, position);
  33297. var tbox = readUint32(data, position + 4);
  33298. position += headerSize;
  33299. if (lbox === 1) {
  33300. // XLBox: read UInt64 according to spec.
  33301. // JavaScript's int precision of 53 bit should be sufficient here.
  33302. lbox = readUint32(data, position) * 4294967296 +
  33303. readUint32(data, position + 4);
  33304. position += 8;
  33305. headerSize += 8;
  33306. }
  33307. if (lbox === 0) {
  33308. lbox = length - position + headerSize;
  33309. }
  33310. if (lbox < headerSize) {
  33311. throw new Error('JPX Error: Invalid box field size');
  33312. }
  33313. var dataLength = lbox - headerSize;
  33314. var jumpDataLength = true;
  33315. switch (tbox) {
  33316. case 0x6A703268: // 'jp2h'
  33317. jumpDataLength = false; // parsing child boxes
  33318. break;
  33319. case 0x636F6C72: // 'colr'
  33320. // Colorspaces are not used, the CS from the PDF is used.
  33321. var method = data[position];
  33322. var precedence = data[position + 1];
  33323. var approximation = data[position + 2];
  33324. if (method === 1) {
  33325. // enumerated colorspace
  33326. var colorspace = readUint32(data, position + 3);
  33327. switch (colorspace) {
  33328. case 16: // this indicates a sRGB colorspace
  33329. case 17: // this indicates a grayscale colorspace
  33330. case 18: // this indicates a YUV colorspace
  33331. break;
  33332. default:
  33333. warn('Unknown colorspace ' + colorspace);
  33334. break;
  33335. }
  33336. } else if (method === 2) {
  33337. info('ICC profile not supported');
  33338. }
  33339. break;
  33340. case 0x6A703263: // 'jp2c'
  33341. this.parseCodestream(data, position, position + dataLength);
  33342. break;
  33343. case 0x6A502020: // 'jP\024\024'
  33344. if (0x0d0a870a !== readUint32(data, position)) {
  33345. warn('Invalid JP2 signature');
  33346. }
  33347. break;
  33348. // The following header types are valid but currently not used:
  33349. case 0x6A501A1A: // 'jP\032\032'
  33350. case 0x66747970: // 'ftyp'
  33351. case 0x72726571: // 'rreq'
  33352. case 0x72657320: // 'res '
  33353. case 0x69686472: // 'ihdr'
  33354. break;
  33355. default:
  33356. var headerType = String.fromCharCode((tbox >> 24) & 0xFF,
  33357. (tbox >> 16) & 0xFF,
  33358. (tbox >> 8) & 0xFF,
  33359. tbox & 0xFF);
  33360. warn('Unsupported header type ' + tbox + ' (' + headerType + ')');
  33361. break;
  33362. }
  33363. if (jumpDataLength) {
  33364. position += dataLength;
  33365. }
  33366. }
  33367. },
  33368. parseImageProperties: function JpxImage_parseImageProperties(stream) {
  33369. var newByte = stream.getByte();
  33370. while (newByte >= 0) {
  33371. var oldByte = newByte;
  33372. newByte = stream.getByte();
  33373. var code = (oldByte << 8) | newByte;
  33374. // Image and tile size (SIZ)
  33375. if (code === 0xFF51) {
  33376. stream.skip(4);
  33377. var Xsiz = stream.getInt32() >>> 0; // Byte 4
  33378. var Ysiz = stream.getInt32() >>> 0; // Byte 8
  33379. var XOsiz = stream.getInt32() >>> 0; // Byte 12
  33380. var YOsiz = stream.getInt32() >>> 0; // Byte 16
  33381. stream.skip(16);
  33382. var Csiz = stream.getUint16(); // Byte 36
  33383. this.width = Xsiz - XOsiz;
  33384. this.height = Ysiz - YOsiz;
  33385. this.componentsCount = Csiz;
  33386. // Results are always returned as Uint8Arrays
  33387. this.bitsPerComponent = 8;
  33388. return;
  33389. }
  33390. }
  33391. throw new Error('JPX Error: No size marker found in JPX stream');
  33392. },
  33393. parseCodestream: function JpxImage_parseCodestream(data, start, end) {
  33394. var context = {};
  33395. try {
  33396. var doNotRecover = false;
  33397. var position = start;
  33398. while (position + 1 < end) {
  33399. var code = readUint16(data, position);
  33400. position += 2;
  33401. var length = 0, j, sqcd, spqcds, spqcdSize, scalarExpounded, tile;
  33402. switch (code) {
  33403. case 0xFF4F: // Start of codestream (SOC)
  33404. context.mainHeader = true;
  33405. break;
  33406. case 0xFFD9: // End of codestream (EOC)
  33407. break;
  33408. case 0xFF51: // Image and tile size (SIZ)
  33409. length = readUint16(data, position);
  33410. var siz = {};
  33411. siz.Xsiz = readUint32(data, position + 4);
  33412. siz.Ysiz = readUint32(data, position + 8);
  33413. siz.XOsiz = readUint32(data, position + 12);
  33414. siz.YOsiz = readUint32(data, position + 16);
  33415. siz.XTsiz = readUint32(data, position + 20);
  33416. siz.YTsiz = readUint32(data, position + 24);
  33417. siz.XTOsiz = readUint32(data, position + 28);
  33418. siz.YTOsiz = readUint32(data, position + 32);
  33419. var componentsCount = readUint16(data, position + 36);
  33420. siz.Csiz = componentsCount;
  33421. var components = [];
  33422. j = position + 38;
  33423. for (var i = 0; i < componentsCount; i++) {
  33424. var component = {
  33425. precision: (data[j] & 0x7F) + 1,
  33426. isSigned: !!(data[j] & 0x80),
  33427. XRsiz: data[j + 1],
  33428. YRsiz: data[j + 1]
  33429. };
  33430. calculateComponentDimensions(component, siz);
  33431. components.push(component);
  33432. }
  33433. context.SIZ = siz;
  33434. context.components = components;
  33435. calculateTileGrids(context, components);
  33436. context.QCC = [];
  33437. context.COC = [];
  33438. break;
  33439. case 0xFF5C: // Quantization default (QCD)
  33440. length = readUint16(data, position);
  33441. var qcd = {};
  33442. j = position + 2;
  33443. sqcd = data[j++];
  33444. switch (sqcd & 0x1F) {
  33445. case 0:
  33446. spqcdSize = 8;
  33447. scalarExpounded = true;
  33448. break;
  33449. case 1:
  33450. spqcdSize = 16;
  33451. scalarExpounded = false;
  33452. break;
  33453. case 2:
  33454. spqcdSize = 16;
  33455. scalarExpounded = true;
  33456. break;
  33457. default:
  33458. throw new Error('JPX Error: Invalid SQcd value ' + sqcd);
  33459. }
  33460. qcd.noQuantization = (spqcdSize === 8);
  33461. qcd.scalarExpounded = scalarExpounded;
  33462. qcd.guardBits = sqcd >> 5;
  33463. spqcds = [];
  33464. while (j < length + position) {
  33465. var spqcd = {};
  33466. if (spqcdSize === 8) {
  33467. spqcd.epsilon = data[j++] >> 3;
  33468. spqcd.mu = 0;
  33469. } else {
  33470. spqcd.epsilon = data[j] >> 3;
  33471. spqcd.mu = ((data[j] & 0x7) << 8) | data[j + 1];
  33472. j += 2;
  33473. }
  33474. spqcds.push(spqcd);
  33475. }
  33476. qcd.SPqcds = spqcds;
  33477. if (context.mainHeader) {
  33478. context.QCD = qcd;
  33479. } else {
  33480. context.currentTile.QCD = qcd;
  33481. context.currentTile.QCC = [];
  33482. }
  33483. break;
  33484. case 0xFF5D: // Quantization component (QCC)
  33485. length = readUint16(data, position);
  33486. var qcc = {};
  33487. j = position + 2;
  33488. var cqcc;
  33489. if (context.SIZ.Csiz < 257) {
  33490. cqcc = data[j++];
  33491. } else {
  33492. cqcc = readUint16(data, j);
  33493. j += 2;
  33494. }
  33495. sqcd = data[j++];
  33496. switch (sqcd & 0x1F) {
  33497. case 0:
  33498. spqcdSize = 8;
  33499. scalarExpounded = true;
  33500. break;
  33501. case 1:
  33502. spqcdSize = 16;
  33503. scalarExpounded = false;
  33504. break;
  33505. case 2:
  33506. spqcdSize = 16;
  33507. scalarExpounded = true;
  33508. break;
  33509. default:
  33510. throw new Error('JPX Error: Invalid SQcd value ' + sqcd);
  33511. }
  33512. qcc.noQuantization = (spqcdSize === 8);
  33513. qcc.scalarExpounded = scalarExpounded;
  33514. qcc.guardBits = sqcd >> 5;
  33515. spqcds = [];
  33516. while (j < (length + position)) {
  33517. spqcd = {};
  33518. if (spqcdSize === 8) {
  33519. spqcd.epsilon = data[j++] >> 3;
  33520. spqcd.mu = 0;
  33521. } else {
  33522. spqcd.epsilon = data[j] >> 3;
  33523. spqcd.mu = ((data[j] & 0x7) << 8) | data[j + 1];
  33524. j += 2;
  33525. }
  33526. spqcds.push(spqcd);
  33527. }
  33528. qcc.SPqcds = spqcds;
  33529. if (context.mainHeader) {
  33530. context.QCC[cqcc] = qcc;
  33531. } else {
  33532. context.currentTile.QCC[cqcc] = qcc;
  33533. }
  33534. break;
  33535. case 0xFF52: // Coding style default (COD)
  33536. length = readUint16(data, position);
  33537. var cod = {};
  33538. j = position + 2;
  33539. var scod = data[j++];
  33540. cod.entropyCoderWithCustomPrecincts = !!(scod & 1);
  33541. cod.sopMarkerUsed = !!(scod & 2);
  33542. cod.ephMarkerUsed = !!(scod & 4);
  33543. cod.progressionOrder = data[j++];
  33544. cod.layersCount = readUint16(data, j);
  33545. j += 2;
  33546. cod.multipleComponentTransform = data[j++];
  33547. cod.decompositionLevelsCount = data[j++];
  33548. cod.xcb = (data[j++] & 0xF) + 2;
  33549. cod.ycb = (data[j++] & 0xF) + 2;
  33550. var blockStyle = data[j++];
  33551. cod.selectiveArithmeticCodingBypass = !!(blockStyle & 1);
  33552. cod.resetContextProbabilities = !!(blockStyle & 2);
  33553. cod.terminationOnEachCodingPass = !!(blockStyle & 4);
  33554. cod.verticalyStripe = !!(blockStyle & 8);
  33555. cod.predictableTermination = !!(blockStyle & 16);
  33556. cod.segmentationSymbolUsed = !!(blockStyle & 32);
  33557. cod.reversibleTransformation = data[j++];
  33558. if (cod.entropyCoderWithCustomPrecincts) {
  33559. var precinctsSizes = [];
  33560. while (j < length + position) {
  33561. var precinctsSize = data[j++];
  33562. precinctsSizes.push({
  33563. PPx: precinctsSize & 0xF,
  33564. PPy: precinctsSize >> 4
  33565. });
  33566. }
  33567. cod.precinctsSizes = precinctsSizes;
  33568. }
  33569. var unsupported = [];
  33570. if (cod.selectiveArithmeticCodingBypass) {
  33571. unsupported.push('selectiveArithmeticCodingBypass');
  33572. }
  33573. if (cod.resetContextProbabilities) {
  33574. unsupported.push('resetContextProbabilities');
  33575. }
  33576. if (cod.terminationOnEachCodingPass) {
  33577. unsupported.push('terminationOnEachCodingPass');
  33578. }
  33579. if (cod.verticalyStripe) {
  33580. unsupported.push('verticalyStripe');
  33581. }
  33582. if (cod.predictableTermination) {
  33583. unsupported.push('predictableTermination');
  33584. }
  33585. if (unsupported.length > 0) {
  33586. doNotRecover = true;
  33587. throw new Error('JPX Error: Unsupported COD options (' +
  33588. unsupported.join(', ') + ')');
  33589. }
  33590. if (context.mainHeader) {
  33591. context.COD = cod;
  33592. } else {
  33593. context.currentTile.COD = cod;
  33594. context.currentTile.COC = [];
  33595. }
  33596. break;
  33597. case 0xFF90: // Start of tile-part (SOT)
  33598. length = readUint16(data, position);
  33599. tile = {};
  33600. tile.index = readUint16(data, position + 2);
  33601. tile.length = readUint32(data, position + 4);
  33602. tile.dataEnd = tile.length + position - 2;
  33603. tile.partIndex = data[position + 8];
  33604. tile.partsCount = data[position + 9];
  33605. context.mainHeader = false;
  33606. if (tile.partIndex === 0) {
  33607. // reset component specific settings
  33608. tile.COD = context.COD;
  33609. tile.COC = context.COC.slice(0); // clone of the global COC
  33610. tile.QCD = context.QCD;
  33611. tile.QCC = context.QCC.slice(0); // clone of the global COC
  33612. }
  33613. context.currentTile = tile;
  33614. break;
  33615. case 0xFF93: // Start of data (SOD)
  33616. tile = context.currentTile;
  33617. if (tile.partIndex === 0) {
  33618. initializeTile(context, tile.index);
  33619. buildPackets(context);
  33620. }
  33621. // moving to the end of the data
  33622. length = tile.dataEnd - position;
  33623. parseTilePackets(context, data, position, length);
  33624. break;
  33625. case 0xFF55: // Tile-part lengths, main header (TLM)
  33626. case 0xFF57: // Packet length, main header (PLM)
  33627. case 0xFF58: // Packet length, tile-part header (PLT)
  33628. case 0xFF64: // Comment (COM)
  33629. length = readUint16(data, position);
  33630. // skipping content
  33631. break;
  33632. case 0xFF53: // Coding style component (COC)
  33633. throw new Error('JPX Error: Codestream code 0xFF53 (COC) is ' +
  33634. 'not implemented');
  33635. default:
  33636. throw new Error('JPX Error: Unknown codestream code: ' +
  33637. code.toString(16));
  33638. }
  33639. position += length;
  33640. }
  33641. } catch (e) {
  33642. if (doNotRecover || this.failOnCorruptedImage) {
  33643. throw e;
  33644. } else {
  33645. warn('Trying to recover from ' + e.message);
  33646. }
  33647. }
  33648. this.tiles = transformComponents(context);
  33649. this.width = context.SIZ.Xsiz - context.SIZ.XOsiz;
  33650. this.height = context.SIZ.Ysiz - context.SIZ.YOsiz;
  33651. this.componentsCount = context.SIZ.Csiz;
  33652. }
  33653. };
  33654. function calculateComponentDimensions(component, siz) {
  33655. // Section B.2 Component mapping
  33656. component.x0 = Math.ceil(siz.XOsiz / component.XRsiz);
  33657. component.x1 = Math.ceil(siz.Xsiz / component.XRsiz);
  33658. component.y0 = Math.ceil(siz.YOsiz / component.YRsiz);
  33659. component.y1 = Math.ceil(siz.Ysiz / component.YRsiz);
  33660. component.width = component.x1 - component.x0;
  33661. component.height = component.y1 - component.y0;
  33662. }
  33663. function calculateTileGrids(context, components) {
  33664. var siz = context.SIZ;
  33665. // Section B.3 Division into tile and tile-components
  33666. var tile, tiles = [];
  33667. var numXtiles = Math.ceil((siz.Xsiz - siz.XTOsiz) / siz.XTsiz);
  33668. var numYtiles = Math.ceil((siz.Ysiz - siz.YTOsiz) / siz.YTsiz);
  33669. for (var q = 0; q < numYtiles; q++) {
  33670. for (var p = 0; p < numXtiles; p++) {
  33671. tile = {};
  33672. tile.tx0 = Math.max(siz.XTOsiz + p * siz.XTsiz, siz.XOsiz);
  33673. tile.ty0 = Math.max(siz.YTOsiz + q * siz.YTsiz, siz.YOsiz);
  33674. tile.tx1 = Math.min(siz.XTOsiz + (p + 1) * siz.XTsiz, siz.Xsiz);
  33675. tile.ty1 = Math.min(siz.YTOsiz + (q + 1) * siz.YTsiz, siz.Ysiz);
  33676. tile.width = tile.tx1 - tile.tx0;
  33677. tile.height = tile.ty1 - tile.ty0;
  33678. tile.components = [];
  33679. tiles.push(tile);
  33680. }
  33681. }
  33682. context.tiles = tiles;
  33683. var componentsCount = siz.Csiz;
  33684. for (var i = 0, ii = componentsCount; i < ii; i++) {
  33685. var component = components[i];
  33686. for (var j = 0, jj = tiles.length; j < jj; j++) {
  33687. var tileComponent = {};
  33688. tile = tiles[j];
  33689. tileComponent.tcx0 = Math.ceil(tile.tx0 / component.XRsiz);
  33690. tileComponent.tcy0 = Math.ceil(tile.ty0 / component.YRsiz);
  33691. tileComponent.tcx1 = Math.ceil(tile.tx1 / component.XRsiz);
  33692. tileComponent.tcy1 = Math.ceil(tile.ty1 / component.YRsiz);
  33693. tileComponent.width = tileComponent.tcx1 - tileComponent.tcx0;
  33694. tileComponent.height = tileComponent.tcy1 - tileComponent.tcy0;
  33695. tile.components[i] = tileComponent;
  33696. }
  33697. }
  33698. }
  33699. function getBlocksDimensions(context, component, r) {
  33700. var codOrCoc = component.codingStyleParameters;
  33701. var result = {};
  33702. if (!codOrCoc.entropyCoderWithCustomPrecincts) {
  33703. result.PPx = 15;
  33704. result.PPy = 15;
  33705. } else {
  33706. result.PPx = codOrCoc.precinctsSizes[r].PPx;
  33707. result.PPy = codOrCoc.precinctsSizes[r].PPy;
  33708. }
  33709. // calculate codeblock size as described in section B.7
  33710. result.xcb_ = (r > 0 ? Math.min(codOrCoc.xcb, result.PPx - 1) :
  33711. Math.min(codOrCoc.xcb, result.PPx));
  33712. result.ycb_ = (r > 0 ? Math.min(codOrCoc.ycb, result.PPy - 1) :
  33713. Math.min(codOrCoc.ycb, result.PPy));
  33714. return result;
  33715. }
  33716. function buildPrecincts(context, resolution, dimensions) {
  33717. // Section B.6 Division resolution to precincts
  33718. var precinctWidth = 1 << dimensions.PPx;
  33719. var precinctHeight = 1 << dimensions.PPy;
  33720. // Jasper introduces codeblock groups for mapping each subband codeblocks
  33721. // to precincts. Precinct partition divides a resolution according to width
  33722. // and height parameters. The subband that belongs to the resolution level
  33723. // has a different size than the level, unless it is the zero resolution.
  33724. // From Jasper documentation: jpeg2000.pdf, section K: Tier-2 coding:
  33725. // The precinct partitioning for a particular subband is derived from a
  33726. // partitioning of its parent LL band (i.e., the LL band at the next higher
  33727. // resolution level)... The LL band associated with each resolution level is
  33728. // divided into precincts... Each of the resulting precinct regions is then
  33729. // mapped into its child subbands (if any) at the next lower resolution
  33730. // level. This is accomplished by using the coordinate transformation
  33731. // (u, v) = (ceil(x/2), ceil(y/2)) where (x, y) and (u, v) are the
  33732. // coordinates of a point in the LL band and child subband, respectively.
  33733. var isZeroRes = resolution.resLevel === 0;
  33734. var precinctWidthInSubband = 1 << (dimensions.PPx + (isZeroRes ? 0 : -1));
  33735. var precinctHeightInSubband = 1 << (dimensions.PPy + (isZeroRes ? 0 : -1));
  33736. var numprecinctswide = (resolution.trx1 > resolution.trx0 ?
  33737. Math.ceil(resolution.trx1 / precinctWidth) -
  33738. Math.floor(resolution.trx0 / precinctWidth) : 0);
  33739. var numprecinctshigh = (resolution.try1 > resolution.try0 ?
  33740. Math.ceil(resolution.try1 / precinctHeight) -
  33741. Math.floor(resolution.try0 / precinctHeight) : 0);
  33742. var numprecincts = numprecinctswide * numprecinctshigh;
  33743. resolution.precinctParameters = {
  33744. precinctWidth: precinctWidth,
  33745. precinctHeight: precinctHeight,
  33746. numprecinctswide: numprecinctswide,
  33747. numprecinctshigh: numprecinctshigh,
  33748. numprecincts: numprecincts,
  33749. precinctWidthInSubband: precinctWidthInSubband,
  33750. precinctHeightInSubband: precinctHeightInSubband
  33751. };
  33752. }
  33753. function buildCodeblocks(context, subband, dimensions) {
  33754. // Section B.7 Division sub-band into code-blocks
  33755. var xcb_ = dimensions.xcb_;
  33756. var ycb_ = dimensions.ycb_;
  33757. var codeblockWidth = 1 << xcb_;
  33758. var codeblockHeight = 1 << ycb_;
  33759. var cbx0 = subband.tbx0 >> xcb_;
  33760. var cby0 = subband.tby0 >> ycb_;
  33761. var cbx1 = (subband.tbx1 + codeblockWidth - 1) >> xcb_;
  33762. var cby1 = (subband.tby1 + codeblockHeight - 1) >> ycb_;
  33763. var precinctParameters = subband.resolution.precinctParameters;
  33764. var codeblocks = [];
  33765. var precincts = [];
  33766. var i, j, codeblock, precinctNumber;
  33767. for (j = cby0; j < cby1; j++) {
  33768. for (i = cbx0; i < cbx1; i++) {
  33769. codeblock = {
  33770. cbx: i,
  33771. cby: j,
  33772. tbx0: codeblockWidth * i,
  33773. tby0: codeblockHeight * j,
  33774. tbx1: codeblockWidth * (i + 1),
  33775. tby1: codeblockHeight * (j + 1)
  33776. };
  33777. codeblock.tbx0_ = Math.max(subband.tbx0, codeblock.tbx0);
  33778. codeblock.tby0_ = Math.max(subband.tby0, codeblock.tby0);
  33779. codeblock.tbx1_ = Math.min(subband.tbx1, codeblock.tbx1);
  33780. codeblock.tby1_ = Math.min(subband.tby1, codeblock.tby1);
  33781. // Calculate precinct number for this codeblock, codeblock position
  33782. // should be relative to its subband, use actual dimension and position
  33783. // See comment about codeblock group width and height
  33784. var pi = Math.floor((codeblock.tbx0_ - subband.tbx0) /
  33785. precinctParameters.precinctWidthInSubband);
  33786. var pj = Math.floor((codeblock.tby0_ - subband.tby0) /
  33787. precinctParameters.precinctHeightInSubband);
  33788. precinctNumber = pi + (pj * precinctParameters.numprecinctswide);
  33789. codeblock.precinctNumber = precinctNumber;
  33790. codeblock.subbandType = subband.type;
  33791. codeblock.Lblock = 3;
  33792. if (codeblock.tbx1_ <= codeblock.tbx0_ ||
  33793. codeblock.tby1_ <= codeblock.tby0_) {
  33794. continue;
  33795. }
  33796. codeblocks.push(codeblock);
  33797. // building precinct for the sub-band
  33798. var precinct = precincts[precinctNumber];
  33799. if (precinct !== undefined) {
  33800. if (i < precinct.cbxMin) {
  33801. precinct.cbxMin = i;
  33802. } else if (i > precinct.cbxMax) {
  33803. precinct.cbxMax = i;
  33804. }
  33805. if (j < precinct.cbyMin) {
  33806. precinct.cbxMin = j;
  33807. } else if (j > precinct.cbyMax) {
  33808. precinct.cbyMax = j;
  33809. }
  33810. } else {
  33811. precincts[precinctNumber] = precinct = {
  33812. cbxMin: i,
  33813. cbyMin: j,
  33814. cbxMax: i,
  33815. cbyMax: j
  33816. };
  33817. }
  33818. codeblock.precinct = precinct;
  33819. }
  33820. }
  33821. subband.codeblockParameters = {
  33822. codeblockWidth: xcb_,
  33823. codeblockHeight: ycb_,
  33824. numcodeblockwide: cbx1 - cbx0 + 1,
  33825. numcodeblockhigh: cby1 - cby0 + 1
  33826. };
  33827. subband.codeblocks = codeblocks;
  33828. subband.precincts = precincts;
  33829. }
  33830. function createPacket(resolution, precinctNumber, layerNumber) {
  33831. var precinctCodeblocks = [];
  33832. // Section B.10.8 Order of info in packet
  33833. var subbands = resolution.subbands;
  33834. // sub-bands already ordered in 'LL', 'HL', 'LH', and 'HH' sequence
  33835. for (var i = 0, ii = subbands.length; i < ii; i++) {
  33836. var subband = subbands[i];
  33837. var codeblocks = subband.codeblocks;
  33838. for (var j = 0, jj = codeblocks.length; j < jj; j++) {
  33839. var codeblock = codeblocks[j];
  33840. if (codeblock.precinctNumber !== precinctNumber) {
  33841. continue;
  33842. }
  33843. precinctCodeblocks.push(codeblock);
  33844. }
  33845. }
  33846. return {
  33847. layerNumber: layerNumber,
  33848. codeblocks: precinctCodeblocks
  33849. };
  33850. }
  33851. function LayerResolutionComponentPositionIterator(context) {
  33852. var siz = context.SIZ;
  33853. var tileIndex = context.currentTile.index;
  33854. var tile = context.tiles[tileIndex];
  33855. var layersCount = tile.codingStyleDefaultParameters.layersCount;
  33856. var componentsCount = siz.Csiz;
  33857. var maxDecompositionLevelsCount = 0;
  33858. for (var q = 0; q < componentsCount; q++) {
  33859. maxDecompositionLevelsCount = Math.max(maxDecompositionLevelsCount,
  33860. tile.components[q].codingStyleParameters.decompositionLevelsCount);
  33861. }
  33862. var l = 0, r = 0, i = 0, k = 0;
  33863. this.nextPacket = function JpxImage_nextPacket() {
  33864. // Section B.12.1.1 Layer-resolution-component-position
  33865. for (; l < layersCount; l++) {
  33866. for (; r <= maxDecompositionLevelsCount; r++) {
  33867. for (; i < componentsCount; i++) {
  33868. var component = tile.components[i];
  33869. if (r > component.codingStyleParameters.decompositionLevelsCount) {
  33870. continue;
  33871. }
  33872. var resolution = component.resolutions[r];
  33873. var numprecincts = resolution.precinctParameters.numprecincts;
  33874. for (; k < numprecincts;) {
  33875. var packet = createPacket(resolution, k, l);
  33876. k++;
  33877. return packet;
  33878. }
  33879. k = 0;
  33880. }
  33881. i = 0;
  33882. }
  33883. r = 0;
  33884. }
  33885. throw new Error('JPX Error: Out of packets');
  33886. };
  33887. }
  33888. function ResolutionLayerComponentPositionIterator(context) {
  33889. var siz = context.SIZ;
  33890. var tileIndex = context.currentTile.index;
  33891. var tile = context.tiles[tileIndex];
  33892. var layersCount = tile.codingStyleDefaultParameters.layersCount;
  33893. var componentsCount = siz.Csiz;
  33894. var maxDecompositionLevelsCount = 0;
  33895. for (var q = 0; q < componentsCount; q++) {
  33896. maxDecompositionLevelsCount = Math.max(maxDecompositionLevelsCount,
  33897. tile.components[q].codingStyleParameters.decompositionLevelsCount);
  33898. }
  33899. var r = 0, l = 0, i = 0, k = 0;
  33900. this.nextPacket = function JpxImage_nextPacket() {
  33901. // Section B.12.1.2 Resolution-layer-component-position
  33902. for (; r <= maxDecompositionLevelsCount; r++) {
  33903. for (; l < layersCount; l++) {
  33904. for (; i < componentsCount; i++) {
  33905. var component = tile.components[i];
  33906. if (r > component.codingStyleParameters.decompositionLevelsCount) {
  33907. continue;
  33908. }
  33909. var resolution = component.resolutions[r];
  33910. var numprecincts = resolution.precinctParameters.numprecincts;
  33911. for (; k < numprecincts;) {
  33912. var packet = createPacket(resolution, k, l);
  33913. k++;
  33914. return packet;
  33915. }
  33916. k = 0;
  33917. }
  33918. i = 0;
  33919. }
  33920. l = 0;
  33921. }
  33922. throw new Error('JPX Error: Out of packets');
  33923. };
  33924. }
  33925. function ResolutionPositionComponentLayerIterator(context) {
  33926. var siz = context.SIZ;
  33927. var tileIndex = context.currentTile.index;
  33928. var tile = context.tiles[tileIndex];
  33929. var layersCount = tile.codingStyleDefaultParameters.layersCount;
  33930. var componentsCount = siz.Csiz;
  33931. var l, r, c, p;
  33932. var maxDecompositionLevelsCount = 0;
  33933. for (c = 0; c < componentsCount; c++) {
  33934. var component = tile.components[c];
  33935. maxDecompositionLevelsCount = Math.max(maxDecompositionLevelsCount,
  33936. component.codingStyleParameters.decompositionLevelsCount);
  33937. }
  33938. var maxNumPrecinctsInLevel = new Int32Array(
  33939. maxDecompositionLevelsCount + 1);
  33940. for (r = 0; r <= maxDecompositionLevelsCount; ++r) {
  33941. var maxNumPrecincts = 0;
  33942. for (c = 0; c < componentsCount; ++c) {
  33943. var resolutions = tile.components[c].resolutions;
  33944. if (r < resolutions.length) {
  33945. maxNumPrecincts = Math.max(maxNumPrecincts,
  33946. resolutions[r].precinctParameters.numprecincts);
  33947. }
  33948. }
  33949. maxNumPrecinctsInLevel[r] = maxNumPrecincts;
  33950. }
  33951. l = 0;
  33952. r = 0;
  33953. c = 0;
  33954. p = 0;
  33955. this.nextPacket = function JpxImage_nextPacket() {
  33956. // Section B.12.1.3 Resolution-position-component-layer
  33957. for (; r <= maxDecompositionLevelsCount; r++) {
  33958. for (; p < maxNumPrecinctsInLevel[r]; p++) {
  33959. for (; c < componentsCount; c++) {
  33960. var component = tile.components[c];
  33961. if (r > component.codingStyleParameters.decompositionLevelsCount) {
  33962. continue;
  33963. }
  33964. var resolution = component.resolutions[r];
  33965. var numprecincts = resolution.precinctParameters.numprecincts;
  33966. if (p >= numprecincts) {
  33967. continue;
  33968. }
  33969. for (; l < layersCount;) {
  33970. var packet = createPacket(resolution, p, l);
  33971. l++;
  33972. return packet;
  33973. }
  33974. l = 0;
  33975. }
  33976. c = 0;
  33977. }
  33978. p = 0;
  33979. }
  33980. throw new Error('JPX Error: Out of packets');
  33981. };
  33982. }
  33983. function PositionComponentResolutionLayerIterator(context) {
  33984. var siz = context.SIZ;
  33985. var tileIndex = context.currentTile.index;
  33986. var tile = context.tiles[tileIndex];
  33987. var layersCount = tile.codingStyleDefaultParameters.layersCount;
  33988. var componentsCount = siz.Csiz;
  33989. var precinctsSizes = getPrecinctSizesInImageScale(tile);
  33990. var precinctsIterationSizes = precinctsSizes;
  33991. var l = 0, r = 0, c = 0, px = 0, py = 0;
  33992. this.nextPacket = function JpxImage_nextPacket() {
  33993. // Section B.12.1.4 Position-component-resolution-layer
  33994. for (; py < precinctsIterationSizes.maxNumHigh; py++) {
  33995. for (; px < precinctsIterationSizes.maxNumWide; px++) {
  33996. for (; c < componentsCount; c++) {
  33997. var component = tile.components[c];
  33998. var decompositionLevelsCount =
  33999. component.codingStyleParameters.decompositionLevelsCount;
  34000. for (; r <= decompositionLevelsCount; r++) {
  34001. var resolution = component.resolutions[r];
  34002. var sizeInImageScale =
  34003. precinctsSizes.components[c].resolutions[r];
  34004. var k = getPrecinctIndexIfExist(
  34005. px,
  34006. py,
  34007. sizeInImageScale,
  34008. precinctsIterationSizes,
  34009. resolution);
  34010. if (k === null) {
  34011. continue;
  34012. }
  34013. for (; l < layersCount;) {
  34014. var packet = createPacket(resolution, k, l);
  34015. l++;
  34016. return packet;
  34017. }
  34018. l = 0;
  34019. }
  34020. r = 0;
  34021. }
  34022. c = 0;
  34023. }
  34024. px = 0;
  34025. }
  34026. throw new Error('JPX Error: Out of packets');
  34027. };
  34028. }
  34029. function ComponentPositionResolutionLayerIterator(context) {
  34030. var siz = context.SIZ;
  34031. var tileIndex = context.currentTile.index;
  34032. var tile = context.tiles[tileIndex];
  34033. var layersCount = tile.codingStyleDefaultParameters.layersCount;
  34034. var componentsCount = siz.Csiz;
  34035. var precinctsSizes = getPrecinctSizesInImageScale(tile);
  34036. var l = 0, r = 0, c = 0, px = 0, py = 0;
  34037. this.nextPacket = function JpxImage_nextPacket() {
  34038. // Section B.12.1.5 Component-position-resolution-layer
  34039. for (; c < componentsCount; ++c) {
  34040. var component = tile.components[c];
  34041. var precinctsIterationSizes = precinctsSizes.components[c];
  34042. var decompositionLevelsCount =
  34043. component.codingStyleParameters.decompositionLevelsCount;
  34044. for (; py < precinctsIterationSizes.maxNumHigh; py++) {
  34045. for (; px < precinctsIterationSizes.maxNumWide; px++) {
  34046. for (; r <= decompositionLevelsCount; r++) {
  34047. var resolution = component.resolutions[r];
  34048. var sizeInImageScale = precinctsIterationSizes.resolutions[r];
  34049. var k = getPrecinctIndexIfExist(
  34050. px,
  34051. py,
  34052. sizeInImageScale,
  34053. precinctsIterationSizes,
  34054. resolution);
  34055. if (k === null) {
  34056. continue;
  34057. }
  34058. for (; l < layersCount;) {
  34059. var packet = createPacket(resolution, k, l);
  34060. l++;
  34061. return packet;
  34062. }
  34063. l = 0;
  34064. }
  34065. r = 0;
  34066. }
  34067. px = 0;
  34068. }
  34069. py = 0;
  34070. }
  34071. throw new Error('JPX Error: Out of packets');
  34072. };
  34073. }
  34074. function getPrecinctIndexIfExist(
  34075. pxIndex, pyIndex, sizeInImageScale, precinctIterationSizes, resolution) {
  34076. var posX = pxIndex * precinctIterationSizes.minWidth;
  34077. var posY = pyIndex * precinctIterationSizes.minHeight;
  34078. if (posX % sizeInImageScale.width !== 0 ||
  34079. posY % sizeInImageScale.height !== 0) {
  34080. return null;
  34081. }
  34082. var startPrecinctRowIndex =
  34083. (posY / sizeInImageScale.width) *
  34084. resolution.precinctParameters.numprecinctswide;
  34085. return (posX / sizeInImageScale.height) + startPrecinctRowIndex;
  34086. }
  34087. function getPrecinctSizesInImageScale(tile) {
  34088. var componentsCount = tile.components.length;
  34089. var minWidth = Number.MAX_VALUE;
  34090. var minHeight = Number.MAX_VALUE;
  34091. var maxNumWide = 0;
  34092. var maxNumHigh = 0;
  34093. var sizePerComponent = new Array(componentsCount);
  34094. for (var c = 0; c < componentsCount; c++) {
  34095. var component = tile.components[c];
  34096. var decompositionLevelsCount =
  34097. component.codingStyleParameters.decompositionLevelsCount;
  34098. var sizePerResolution = new Array(decompositionLevelsCount + 1);
  34099. var minWidthCurrentComponent = Number.MAX_VALUE;
  34100. var minHeightCurrentComponent = Number.MAX_VALUE;
  34101. var maxNumWideCurrentComponent = 0;
  34102. var maxNumHighCurrentComponent = 0;
  34103. var scale = 1;
  34104. for (var r = decompositionLevelsCount; r >= 0; --r) {
  34105. var resolution = component.resolutions[r];
  34106. var widthCurrentResolution =
  34107. scale * resolution.precinctParameters.precinctWidth;
  34108. var heightCurrentResolution =
  34109. scale * resolution.precinctParameters.precinctHeight;
  34110. minWidthCurrentComponent = Math.min(
  34111. minWidthCurrentComponent,
  34112. widthCurrentResolution);
  34113. minHeightCurrentComponent = Math.min(
  34114. minHeightCurrentComponent,
  34115. heightCurrentResolution);
  34116. maxNumWideCurrentComponent = Math.max(maxNumWideCurrentComponent,
  34117. resolution.precinctParameters.numprecinctswide);
  34118. maxNumHighCurrentComponent = Math.max(maxNumHighCurrentComponent,
  34119. resolution.precinctParameters.numprecinctshigh);
  34120. sizePerResolution[r] = {
  34121. width: widthCurrentResolution,
  34122. height: heightCurrentResolution
  34123. };
  34124. scale <<= 1;
  34125. }
  34126. minWidth = Math.min(minWidth, minWidthCurrentComponent);
  34127. minHeight = Math.min(minHeight, minHeightCurrentComponent);
  34128. maxNumWide = Math.max(maxNumWide, maxNumWideCurrentComponent);
  34129. maxNumHigh = Math.max(maxNumHigh, maxNumHighCurrentComponent);
  34130. sizePerComponent[c] = {
  34131. resolutions: sizePerResolution,
  34132. minWidth: minWidthCurrentComponent,
  34133. minHeight: minHeightCurrentComponent,
  34134. maxNumWide: maxNumWideCurrentComponent,
  34135. maxNumHigh: maxNumHighCurrentComponent
  34136. };
  34137. }
  34138. return {
  34139. components: sizePerComponent,
  34140. minWidth: minWidth,
  34141. minHeight: minHeight,
  34142. maxNumWide: maxNumWide,
  34143. maxNumHigh: maxNumHigh
  34144. };
  34145. }
  34146. function buildPackets(context) {
  34147. var siz = context.SIZ;
  34148. var tileIndex = context.currentTile.index;
  34149. var tile = context.tiles[tileIndex];
  34150. var componentsCount = siz.Csiz;
  34151. // Creating resolutions and sub-bands for each component
  34152. for (var c = 0; c < componentsCount; c++) {
  34153. var component = tile.components[c];
  34154. var decompositionLevelsCount =
  34155. component.codingStyleParameters.decompositionLevelsCount;
  34156. // Section B.5 Resolution levels and sub-bands
  34157. var resolutions = [];
  34158. var subbands = [];
  34159. for (var r = 0; r <= decompositionLevelsCount; r++) {
  34160. var blocksDimensions = getBlocksDimensions(context, component, r);
  34161. var resolution = {};
  34162. var scale = 1 << (decompositionLevelsCount - r);
  34163. resolution.trx0 = Math.ceil(component.tcx0 / scale);
  34164. resolution.try0 = Math.ceil(component.tcy0 / scale);
  34165. resolution.trx1 = Math.ceil(component.tcx1 / scale);
  34166. resolution.try1 = Math.ceil(component.tcy1 / scale);
  34167. resolution.resLevel = r;
  34168. buildPrecincts(context, resolution, blocksDimensions);
  34169. resolutions.push(resolution);
  34170. var subband;
  34171. if (r === 0) {
  34172. // one sub-band (LL) with last decomposition
  34173. subband = {};
  34174. subband.type = 'LL';
  34175. subband.tbx0 = Math.ceil(component.tcx0 / scale);
  34176. subband.tby0 = Math.ceil(component.tcy0 / scale);
  34177. subband.tbx1 = Math.ceil(component.tcx1 / scale);
  34178. subband.tby1 = Math.ceil(component.tcy1 / scale);
  34179. subband.resolution = resolution;
  34180. buildCodeblocks(context, subband, blocksDimensions);
  34181. subbands.push(subband);
  34182. resolution.subbands = [subband];
  34183. } else {
  34184. var bscale = 1 << (decompositionLevelsCount - r + 1);
  34185. var resolutionSubbands = [];
  34186. // three sub-bands (HL, LH and HH) with rest of decompositions
  34187. subband = {};
  34188. subband.type = 'HL';
  34189. subband.tbx0 = Math.ceil(component.tcx0 / bscale - 0.5);
  34190. subband.tby0 = Math.ceil(component.tcy0 / bscale);
  34191. subband.tbx1 = Math.ceil(component.tcx1 / bscale - 0.5);
  34192. subband.tby1 = Math.ceil(component.tcy1 / bscale);
  34193. subband.resolution = resolution;
  34194. buildCodeblocks(context, subband, blocksDimensions);
  34195. subbands.push(subband);
  34196. resolutionSubbands.push(subband);
  34197. subband = {};
  34198. subband.type = 'LH';
  34199. subband.tbx0 = Math.ceil(component.tcx0 / bscale);
  34200. subband.tby0 = Math.ceil(component.tcy0 / bscale - 0.5);
  34201. subband.tbx1 = Math.ceil(component.tcx1 / bscale);
  34202. subband.tby1 = Math.ceil(component.tcy1 / bscale - 0.5);
  34203. subband.resolution = resolution;
  34204. buildCodeblocks(context, subband, blocksDimensions);
  34205. subbands.push(subband);
  34206. resolutionSubbands.push(subband);
  34207. subband = {};
  34208. subband.type = 'HH';
  34209. subband.tbx0 = Math.ceil(component.tcx0 / bscale - 0.5);
  34210. subband.tby0 = Math.ceil(component.tcy0 / bscale - 0.5);
  34211. subband.tbx1 = Math.ceil(component.tcx1 / bscale - 0.5);
  34212. subband.tby1 = Math.ceil(component.tcy1 / bscale - 0.5);
  34213. subband.resolution = resolution;
  34214. buildCodeblocks(context, subband, blocksDimensions);
  34215. subbands.push(subband);
  34216. resolutionSubbands.push(subband);
  34217. resolution.subbands = resolutionSubbands;
  34218. }
  34219. }
  34220. component.resolutions = resolutions;
  34221. component.subbands = subbands;
  34222. }
  34223. // Generate the packets sequence
  34224. var progressionOrder = tile.codingStyleDefaultParameters.progressionOrder;
  34225. switch (progressionOrder) {
  34226. case 0:
  34227. tile.packetsIterator =
  34228. new LayerResolutionComponentPositionIterator(context);
  34229. break;
  34230. case 1:
  34231. tile.packetsIterator =
  34232. new ResolutionLayerComponentPositionIterator(context);
  34233. break;
  34234. case 2:
  34235. tile.packetsIterator =
  34236. new ResolutionPositionComponentLayerIterator(context);
  34237. break;
  34238. case 3:
  34239. tile.packetsIterator =
  34240. new PositionComponentResolutionLayerIterator(context);
  34241. break;
  34242. case 4:
  34243. tile.packetsIterator =
  34244. new ComponentPositionResolutionLayerIterator(context);
  34245. break;
  34246. default:
  34247. throw new Error('JPX Error: Unsupported progression order ' +
  34248. progressionOrder);
  34249. }
  34250. }
  34251. function parseTilePackets(context, data, offset, dataLength) {
  34252. var position = 0;
  34253. var buffer, bufferSize = 0, skipNextBit = false;
  34254. function readBits(count) {
  34255. while (bufferSize < count) {
  34256. var b = data[offset + position];
  34257. position++;
  34258. if (skipNextBit) {
  34259. buffer = (buffer << 7) | b;
  34260. bufferSize += 7;
  34261. skipNextBit = false;
  34262. } else {
  34263. buffer = (buffer << 8) | b;
  34264. bufferSize += 8;
  34265. }
  34266. if (b === 0xFF) {
  34267. skipNextBit = true;
  34268. }
  34269. }
  34270. bufferSize -= count;
  34271. return (buffer >>> bufferSize) & ((1 << count) - 1);
  34272. }
  34273. function skipMarkerIfEqual(value) {
  34274. if (data[offset + position - 1] === 0xFF &&
  34275. data[offset + position] === value) {
  34276. skipBytes(1);
  34277. return true;
  34278. } else if (data[offset + position] === 0xFF &&
  34279. data[offset + position + 1] === value) {
  34280. skipBytes(2);
  34281. return true;
  34282. }
  34283. return false;
  34284. }
  34285. function skipBytes(count) {
  34286. position += count;
  34287. }
  34288. function alignToByte() {
  34289. bufferSize = 0;
  34290. if (skipNextBit) {
  34291. position++;
  34292. skipNextBit = false;
  34293. }
  34294. }
  34295. function readCodingpasses() {
  34296. if (readBits(1) === 0) {
  34297. return 1;
  34298. }
  34299. if (readBits(1) === 0) {
  34300. return 2;
  34301. }
  34302. var value = readBits(2);
  34303. if (value < 3) {
  34304. return value + 3;
  34305. }
  34306. value = readBits(5);
  34307. if (value < 31) {
  34308. return value + 6;
  34309. }
  34310. value = readBits(7);
  34311. return value + 37;
  34312. }
  34313. var tileIndex = context.currentTile.index;
  34314. var tile = context.tiles[tileIndex];
  34315. var sopMarkerUsed = context.COD.sopMarkerUsed;
  34316. var ephMarkerUsed = context.COD.ephMarkerUsed;
  34317. var packetsIterator = tile.packetsIterator;
  34318. while (position < dataLength) {
  34319. alignToByte();
  34320. if (sopMarkerUsed && skipMarkerIfEqual(0x91)) {
  34321. // Skip also marker segment length and packet sequence ID
  34322. skipBytes(4);
  34323. }
  34324. var packet = packetsIterator.nextPacket();
  34325. if (!readBits(1)) {
  34326. continue;
  34327. }
  34328. var layerNumber = packet.layerNumber;
  34329. var queue = [], codeblock;
  34330. for (var i = 0, ii = packet.codeblocks.length; i < ii; i++) {
  34331. codeblock = packet.codeblocks[i];
  34332. var precinct = codeblock.precinct;
  34333. var codeblockColumn = codeblock.cbx - precinct.cbxMin;
  34334. var codeblockRow = codeblock.cby - precinct.cbyMin;
  34335. var codeblockIncluded = false;
  34336. var firstTimeInclusion = false;
  34337. var valueReady;
  34338. if (codeblock['included'] !== undefined) {
  34339. codeblockIncluded = !!readBits(1);
  34340. } else {
  34341. // reading inclusion tree
  34342. precinct = codeblock.precinct;
  34343. var inclusionTree, zeroBitPlanesTree;
  34344. if (precinct['inclusionTree'] !== undefined) {
  34345. inclusionTree = precinct.inclusionTree;
  34346. } else {
  34347. // building inclusion and zero bit-planes trees
  34348. var width = precinct.cbxMax - precinct.cbxMin + 1;
  34349. var height = precinct.cbyMax - precinct.cbyMin + 1;
  34350. inclusionTree = new InclusionTree(width, height, layerNumber);
  34351. zeroBitPlanesTree = new TagTree(width, height);
  34352. precinct.inclusionTree = inclusionTree;
  34353. precinct.zeroBitPlanesTree = zeroBitPlanesTree;
  34354. }
  34355. if (inclusionTree.reset(codeblockColumn, codeblockRow, layerNumber)) {
  34356. while (true) {
  34357. if (readBits(1)) {
  34358. valueReady = !inclusionTree.nextLevel();
  34359. if (valueReady) {
  34360. codeblock.included = true;
  34361. codeblockIncluded = firstTimeInclusion = true;
  34362. break;
  34363. }
  34364. } else {
  34365. inclusionTree.incrementValue(layerNumber);
  34366. break;
  34367. }
  34368. }
  34369. }
  34370. }
  34371. if (!codeblockIncluded) {
  34372. continue;
  34373. }
  34374. if (firstTimeInclusion) {
  34375. zeroBitPlanesTree = precinct.zeroBitPlanesTree;
  34376. zeroBitPlanesTree.reset(codeblockColumn, codeblockRow);
  34377. while (true) {
  34378. if (readBits(1)) {
  34379. valueReady = !zeroBitPlanesTree.nextLevel();
  34380. if (valueReady) {
  34381. break;
  34382. }
  34383. } else {
  34384. zeroBitPlanesTree.incrementValue();
  34385. }
  34386. }
  34387. codeblock.zeroBitPlanes = zeroBitPlanesTree.value;
  34388. }
  34389. var codingpasses = readCodingpasses();
  34390. while (readBits(1)) {
  34391. codeblock.Lblock++;
  34392. }
  34393. var codingpassesLog2 = log2(codingpasses);
  34394. // rounding down log2
  34395. var bits = ((codingpasses < (1 << codingpassesLog2)) ?
  34396. codingpassesLog2 - 1 : codingpassesLog2) + codeblock.Lblock;
  34397. var codedDataLength = readBits(bits);
  34398. queue.push({
  34399. codeblock: codeblock,
  34400. codingpasses: codingpasses,
  34401. dataLength: codedDataLength
  34402. });
  34403. }
  34404. alignToByte();
  34405. if (ephMarkerUsed) {
  34406. skipMarkerIfEqual(0x92);
  34407. }
  34408. while (queue.length > 0) {
  34409. var packetItem = queue.shift();
  34410. codeblock = packetItem.codeblock;
  34411. if (codeblock['data'] === undefined) {
  34412. codeblock.data = [];
  34413. }
  34414. codeblock.data.push({
  34415. data: data,
  34416. start: offset + position,
  34417. end: offset + position + packetItem.dataLength,
  34418. codingpasses: packetItem.codingpasses
  34419. });
  34420. position += packetItem.dataLength;
  34421. }
  34422. }
  34423. return position;
  34424. }
  34425. function copyCoefficients(coefficients, levelWidth, levelHeight, subband,
  34426. delta, mb, reversible, segmentationSymbolUsed) {
  34427. var x0 = subband.tbx0;
  34428. var y0 = subband.tby0;
  34429. var width = subband.tbx1 - subband.tbx0;
  34430. var codeblocks = subband.codeblocks;
  34431. var right = subband.type.charAt(0) === 'H' ? 1 : 0;
  34432. var bottom = subband.type.charAt(1) === 'H' ? levelWidth : 0;
  34433. for (var i = 0, ii = codeblocks.length; i < ii; ++i) {
  34434. var codeblock = codeblocks[i];
  34435. var blockWidth = codeblock.tbx1_ - codeblock.tbx0_;
  34436. var blockHeight = codeblock.tby1_ - codeblock.tby0_;
  34437. if (blockWidth === 0 || blockHeight === 0) {
  34438. continue;
  34439. }
  34440. if (codeblock['data'] === undefined) {
  34441. continue;
  34442. }
  34443. var bitModel, currentCodingpassType;
  34444. bitModel = new BitModel(blockWidth, blockHeight, codeblock.subbandType,
  34445. codeblock.zeroBitPlanes, mb);
  34446. currentCodingpassType = 2; // first bit plane starts from cleanup
  34447. // collect data
  34448. var data = codeblock.data, totalLength = 0, codingpasses = 0;
  34449. var j, jj, dataItem;
  34450. for (j = 0, jj = data.length; j < jj; j++) {
  34451. dataItem = data[j];
  34452. totalLength += dataItem.end - dataItem.start;
  34453. codingpasses += dataItem.codingpasses;
  34454. }
  34455. var encodedData = new Uint8Array(totalLength);
  34456. var position = 0;
  34457. for (j = 0, jj = data.length; j < jj; j++) {
  34458. dataItem = data[j];
  34459. var chunk = dataItem.data.subarray(dataItem.start, dataItem.end);
  34460. encodedData.set(chunk, position);
  34461. position += chunk.length;
  34462. }
  34463. // decoding the item
  34464. var decoder = new ArithmeticDecoder(encodedData, 0, totalLength);
  34465. bitModel.setDecoder(decoder);
  34466. for (j = 0; j < codingpasses; j++) {
  34467. switch (currentCodingpassType) {
  34468. case 0:
  34469. bitModel.runSignificancePropogationPass();
  34470. break;
  34471. case 1:
  34472. bitModel.runMagnitudeRefinementPass();
  34473. break;
  34474. case 2:
  34475. bitModel.runCleanupPass();
  34476. if (segmentationSymbolUsed) {
  34477. bitModel.checkSegmentationSymbol();
  34478. }
  34479. break;
  34480. }
  34481. currentCodingpassType = (currentCodingpassType + 1) % 3;
  34482. }
  34483. var offset = (codeblock.tbx0_ - x0) + (codeblock.tby0_ - y0) * width;
  34484. var sign = bitModel.coefficentsSign;
  34485. var magnitude = bitModel.coefficentsMagnitude;
  34486. var bitsDecoded = bitModel.bitsDecoded;
  34487. var magnitudeCorrection = reversible ? 0 : 0.5;
  34488. var k, n, nb;
  34489. position = 0;
  34490. // Do the interleaving of Section F.3.3 here, so we do not need
  34491. // to copy later. LL level is not interleaved, just copied.
  34492. var interleave = (subband.type !== 'LL');
  34493. for (j = 0; j < blockHeight; j++) {
  34494. var row = (offset / width) | 0; // row in the non-interleaved subband
  34495. var levelOffset = 2 * row * (levelWidth - width) + right + bottom;
  34496. for (k = 0; k < blockWidth; k++) {
  34497. n = magnitude[position];
  34498. if (n !== 0) {
  34499. n = (n + magnitudeCorrection) * delta;
  34500. if (sign[position] !== 0) {
  34501. n = -n;
  34502. }
  34503. nb = bitsDecoded[position];
  34504. var pos = interleave ? (levelOffset + (offset << 1)) : offset;
  34505. if (reversible && (nb >= mb)) {
  34506. coefficients[pos] = n;
  34507. } else {
  34508. coefficients[pos] = n * (1 << (mb - nb));
  34509. }
  34510. }
  34511. offset++;
  34512. position++;
  34513. }
  34514. offset += width - blockWidth;
  34515. }
  34516. }
  34517. }
  34518. function transformTile(context, tile, c) {
  34519. var component = tile.components[c];
  34520. var codingStyleParameters = component.codingStyleParameters;
  34521. var quantizationParameters = component.quantizationParameters;
  34522. var decompositionLevelsCount =
  34523. codingStyleParameters.decompositionLevelsCount;
  34524. var spqcds = quantizationParameters.SPqcds;
  34525. var scalarExpounded = quantizationParameters.scalarExpounded;
  34526. var guardBits = quantizationParameters.guardBits;
  34527. var segmentationSymbolUsed = codingStyleParameters.segmentationSymbolUsed;
  34528. var precision = context.components[c].precision;
  34529. var reversible = codingStyleParameters.reversibleTransformation;
  34530. var transform = (reversible ? new ReversibleTransform() :
  34531. new IrreversibleTransform());
  34532. var subbandCoefficients = [];
  34533. var b = 0;
  34534. for (var i = 0; i <= decompositionLevelsCount; i++) {
  34535. var resolution = component.resolutions[i];
  34536. var width = resolution.trx1 - resolution.trx0;
  34537. var height = resolution.try1 - resolution.try0;
  34538. // Allocate space for the whole sublevel.
  34539. var coefficients = new Float32Array(width * height);
  34540. for (var j = 0, jj = resolution.subbands.length; j < jj; j++) {
  34541. var mu, epsilon;
  34542. if (!scalarExpounded) {
  34543. // formula E-5
  34544. mu = spqcds[0].mu;
  34545. epsilon = spqcds[0].epsilon + (i > 0 ? 1 - i : 0);
  34546. } else {
  34547. mu = spqcds[b].mu;
  34548. epsilon = spqcds[b].epsilon;
  34549. b++;
  34550. }
  34551. var subband = resolution.subbands[j];
  34552. var gainLog2 = SubbandsGainLog2[subband.type];
  34553. // calulate quantization coefficient (Section E.1.1.1)
  34554. var delta = (reversible ? 1 :
  34555. Math.pow(2, precision + gainLog2 - epsilon) * (1 + mu / 2048));
  34556. var mb = (guardBits + epsilon - 1);
  34557. // In the first resolution level, copyCoefficients will fill the
  34558. // whole array with coefficients. In the succeding passes,
  34559. // copyCoefficients will consecutively fill in the values that belong
  34560. // to the interleaved positions of the HL, LH, and HH coefficients.
  34561. // The LL coefficients will then be interleaved in Transform.iterate().
  34562. copyCoefficients(coefficients, width, height, subband, delta, mb,
  34563. reversible, segmentationSymbolUsed);
  34564. }
  34565. subbandCoefficients.push({
  34566. width: width,
  34567. height: height,
  34568. items: coefficients
  34569. });
  34570. }
  34571. var result = transform.calculate(subbandCoefficients,
  34572. component.tcx0, component.tcy0);
  34573. return {
  34574. left: component.tcx0,
  34575. top: component.tcy0,
  34576. width: result.width,
  34577. height: result.height,
  34578. items: result.items
  34579. };
  34580. }
  34581. function transformComponents(context) {
  34582. var siz = context.SIZ;
  34583. var components = context.components;
  34584. var componentsCount = siz.Csiz;
  34585. var resultImages = [];
  34586. for (var i = 0, ii = context.tiles.length; i < ii; i++) {
  34587. var tile = context.tiles[i];
  34588. var transformedTiles = [];
  34589. var c;
  34590. for (c = 0; c < componentsCount; c++) {
  34591. transformedTiles[c] = transformTile(context, tile, c);
  34592. }
  34593. var tile0 = transformedTiles[0];
  34594. var out = new Uint8Array(tile0.items.length * componentsCount);
  34595. var result = {
  34596. left: tile0.left,
  34597. top: tile0.top,
  34598. width: tile0.width,
  34599. height: tile0.height,
  34600. items: out
  34601. };
  34602. // Section G.2.2 Inverse multi component transform
  34603. var shift, offset, max, min, maxK;
  34604. var pos = 0, j, jj, y0, y1, y2, r, g, b, k, val;
  34605. if (tile.codingStyleDefaultParameters.multipleComponentTransform) {
  34606. var fourComponents = componentsCount === 4;
  34607. var y0items = transformedTiles[0].items;
  34608. var y1items = transformedTiles[1].items;
  34609. var y2items = transformedTiles[2].items;
  34610. var y3items = fourComponents ? transformedTiles[3].items : null;
  34611. // HACK: The multiple component transform formulas below assume that
  34612. // all components have the same precision. With this in mind, we
  34613. // compute shift and offset only once.
  34614. shift = components[0].precision - 8;
  34615. offset = (128 << shift) + 0.5;
  34616. max = 255 * (1 << shift);
  34617. maxK = max * 0.5;
  34618. min = -maxK;
  34619. var component0 = tile.components[0];
  34620. var alpha01 = componentsCount - 3;
  34621. jj = y0items.length;
  34622. if (!component0.codingStyleParameters.reversibleTransformation) {
  34623. // inverse irreversible multiple component transform
  34624. for (j = 0; j < jj; j++, pos += alpha01) {
  34625. y0 = y0items[j] + offset;
  34626. y1 = y1items[j];
  34627. y2 = y2items[j];
  34628. r = y0 + 1.402 * y2;
  34629. g = y0 - 0.34413 * y1 - 0.71414 * y2;
  34630. b = y0 + 1.772 * y1;
  34631. out[pos++] = r <= 0 ? 0 : r >= max ? 255 : r >> shift;
  34632. out[pos++] = g <= 0 ? 0 : g >= max ? 255 : g >> shift;
  34633. out[pos++] = b <= 0 ? 0 : b >= max ? 255 : b >> shift;
  34634. }
  34635. } else {
  34636. // inverse reversible multiple component transform
  34637. for (j = 0; j < jj; j++, pos += alpha01) {
  34638. y0 = y0items[j] + offset;
  34639. y1 = y1items[j];
  34640. y2 = y2items[j];
  34641. g = y0 - ((y2 + y1) >> 2);
  34642. r = g + y2;
  34643. b = g + y1;
  34644. out[pos++] = r <= 0 ? 0 : r >= max ? 255 : r >> shift;
  34645. out[pos++] = g <= 0 ? 0 : g >= max ? 255 : g >> shift;
  34646. out[pos++] = b <= 0 ? 0 : b >= max ? 255 : b >> shift;
  34647. }
  34648. }
  34649. if (fourComponents) {
  34650. for (j = 0, pos = 3; j < jj; j++, pos += 4) {
  34651. k = y3items[j];
  34652. out[pos] = k <= min ? 0 : k >= maxK ? 255 : (k + offset) >> shift;
  34653. }
  34654. }
  34655. } else { // no multi-component transform
  34656. for (c = 0; c < componentsCount; c++) {
  34657. var items = transformedTiles[c].items;
  34658. shift = components[c].precision - 8;
  34659. offset = (128 << shift) + 0.5;
  34660. max = (127.5 * (1 << shift));
  34661. min = -max;
  34662. for (pos = c, j = 0, jj = items.length; j < jj; j++) {
  34663. val = items[j];
  34664. out[pos] = val <= min ? 0 :
  34665. val >= max ? 255 : (val + offset) >> shift;
  34666. pos += componentsCount;
  34667. }
  34668. }
  34669. }
  34670. resultImages.push(result);
  34671. }
  34672. return resultImages;
  34673. }
  34674. function initializeTile(context, tileIndex) {
  34675. var siz = context.SIZ;
  34676. var componentsCount = siz.Csiz;
  34677. var tile = context.tiles[tileIndex];
  34678. for (var c = 0; c < componentsCount; c++) {
  34679. var component = tile.components[c];
  34680. var qcdOrQcc = (context.currentTile.QCC[c] !== undefined ?
  34681. context.currentTile.QCC[c] : context.currentTile.QCD);
  34682. component.quantizationParameters = qcdOrQcc;
  34683. var codOrCoc = (context.currentTile.COC[c] !== undefined ?
  34684. context.currentTile.COC[c] : context.currentTile.COD);
  34685. component.codingStyleParameters = codOrCoc;
  34686. }
  34687. tile.codingStyleDefaultParameters = context.currentTile.COD;
  34688. }
  34689. // Section B.10.2 Tag trees
  34690. var TagTree = (function TagTreeClosure() {
  34691. function TagTree(width, height) {
  34692. var levelsLength = log2(Math.max(width, height)) + 1;
  34693. this.levels = [];
  34694. for (var i = 0; i < levelsLength; i++) {
  34695. var level = {
  34696. width: width,
  34697. height: height,
  34698. items: []
  34699. };
  34700. this.levels.push(level);
  34701. width = Math.ceil(width / 2);
  34702. height = Math.ceil(height / 2);
  34703. }
  34704. }
  34705. TagTree.prototype = {
  34706. reset: function TagTree_reset(i, j) {
  34707. var currentLevel = 0, value = 0, level;
  34708. while (currentLevel < this.levels.length) {
  34709. level = this.levels[currentLevel];
  34710. var index = i + j * level.width;
  34711. if (level.items[index] !== undefined) {
  34712. value = level.items[index];
  34713. break;
  34714. }
  34715. level.index = index;
  34716. i >>= 1;
  34717. j >>= 1;
  34718. currentLevel++;
  34719. }
  34720. currentLevel--;
  34721. level = this.levels[currentLevel];
  34722. level.items[level.index] = value;
  34723. this.currentLevel = currentLevel;
  34724. delete this.value;
  34725. },
  34726. incrementValue: function TagTree_incrementValue() {
  34727. var level = this.levels[this.currentLevel];
  34728. level.items[level.index]++;
  34729. },
  34730. nextLevel: function TagTree_nextLevel() {
  34731. var currentLevel = this.currentLevel;
  34732. var level = this.levels[currentLevel];
  34733. var value = level.items[level.index];
  34734. currentLevel--;
  34735. if (currentLevel < 0) {
  34736. this.value = value;
  34737. return false;
  34738. }
  34739. this.currentLevel = currentLevel;
  34740. level = this.levels[currentLevel];
  34741. level.items[level.index] = value;
  34742. return true;
  34743. }
  34744. };
  34745. return TagTree;
  34746. })();
  34747. var InclusionTree = (function InclusionTreeClosure() {
  34748. function InclusionTree(width, height, defaultValue) {
  34749. var levelsLength = log2(Math.max(width, height)) + 1;
  34750. this.levels = [];
  34751. for (var i = 0; i < levelsLength; i++) {
  34752. var items = new Uint8Array(width * height);
  34753. for (var j = 0, jj = items.length; j < jj; j++) {
  34754. items[j] = defaultValue;
  34755. }
  34756. var level = {
  34757. width: width,
  34758. height: height,
  34759. items: items
  34760. };
  34761. this.levels.push(level);
  34762. width = Math.ceil(width / 2);
  34763. height = Math.ceil(height / 2);
  34764. }
  34765. }
  34766. InclusionTree.prototype = {
  34767. reset: function InclusionTree_reset(i, j, stopValue) {
  34768. var currentLevel = 0;
  34769. while (currentLevel < this.levels.length) {
  34770. var level = this.levels[currentLevel];
  34771. var index = i + j * level.width;
  34772. level.index = index;
  34773. var value = level.items[index];
  34774. if (value === 0xFF) {
  34775. break;
  34776. }
  34777. if (value > stopValue) {
  34778. this.currentLevel = currentLevel;
  34779. // already know about this one, propagating the value to top levels
  34780. this.propagateValues();
  34781. return false;
  34782. }
  34783. i >>= 1;
  34784. j >>= 1;
  34785. currentLevel++;
  34786. }
  34787. this.currentLevel = currentLevel - 1;
  34788. return true;
  34789. },
  34790. incrementValue: function InclusionTree_incrementValue(stopValue) {
  34791. var level = this.levels[this.currentLevel];
  34792. level.items[level.index] = stopValue + 1;
  34793. this.propagateValues();
  34794. },
  34795. propagateValues: function InclusionTree_propagateValues() {
  34796. var levelIndex = this.currentLevel;
  34797. var level = this.levels[levelIndex];
  34798. var currentValue = level.items[level.index];
  34799. while (--levelIndex >= 0) {
  34800. level = this.levels[levelIndex];
  34801. level.items[level.index] = currentValue;
  34802. }
  34803. },
  34804. nextLevel: function InclusionTree_nextLevel() {
  34805. var currentLevel = this.currentLevel;
  34806. var level = this.levels[currentLevel];
  34807. var value = level.items[level.index];
  34808. level.items[level.index] = 0xFF;
  34809. currentLevel--;
  34810. if (currentLevel < 0) {
  34811. return false;
  34812. }
  34813. this.currentLevel = currentLevel;
  34814. level = this.levels[currentLevel];
  34815. level.items[level.index] = value;
  34816. return true;
  34817. }
  34818. };
  34819. return InclusionTree;
  34820. })();
  34821. // Section D. Coefficient bit modeling
  34822. var BitModel = (function BitModelClosure() {
  34823. var UNIFORM_CONTEXT = 17;
  34824. var RUNLENGTH_CONTEXT = 18;
  34825. // Table D-1
  34826. // The index is binary presentation: 0dddvvhh, ddd - sum of Di (0..4),
  34827. // vv - sum of Vi (0..2), and hh - sum of Hi (0..2)
  34828. var LLAndLHContextsLabel = new Uint8Array([
  34829. 0, 5, 8, 0, 3, 7, 8, 0, 4, 7, 8, 0, 0, 0, 0, 0, 1, 6, 8, 0, 3, 7, 8, 0, 4,
  34830. 7, 8, 0, 0, 0, 0, 0, 2, 6, 8, 0, 3, 7, 8, 0, 4, 7, 8, 0, 0, 0, 0, 0, 2, 6,
  34831. 8, 0, 3, 7, 8, 0, 4, 7, 8, 0, 0, 0, 0, 0, 2, 6, 8, 0, 3, 7, 8, 0, 4, 7, 8
  34832. ]);
  34833. var HLContextLabel = new Uint8Array([
  34834. 0, 3, 4, 0, 5, 7, 7, 0, 8, 8, 8, 0, 0, 0, 0, 0, 1, 3, 4, 0, 6, 7, 7, 0, 8,
  34835. 8, 8, 0, 0, 0, 0, 0, 2, 3, 4, 0, 6, 7, 7, 0, 8, 8, 8, 0, 0, 0, 0, 0, 2, 3,
  34836. 4, 0, 6, 7, 7, 0, 8, 8, 8, 0, 0, 0, 0, 0, 2, 3, 4, 0, 6, 7, 7, 0, 8, 8, 8
  34837. ]);
  34838. var HHContextLabel = new Uint8Array([
  34839. 0, 1, 2, 0, 1, 2, 2, 0, 2, 2, 2, 0, 0, 0, 0, 0, 3, 4, 5, 0, 4, 5, 5, 0, 5,
  34840. 5, 5, 0, 0, 0, 0, 0, 6, 7, 7, 0, 7, 7, 7, 0, 7, 7, 7, 0, 0, 0, 0, 0, 8, 8,
  34841. 8, 0, 8, 8, 8, 0, 8, 8, 8, 0, 0, 0, 0, 0, 8, 8, 8, 0, 8, 8, 8, 0, 8, 8, 8
  34842. ]);
  34843. function BitModel(width, height, subband, zeroBitPlanes, mb) {
  34844. this.width = width;
  34845. this.height = height;
  34846. this.contextLabelTable = (subband === 'HH' ? HHContextLabel :
  34847. (subband === 'HL' ? HLContextLabel : LLAndLHContextsLabel));
  34848. var coefficientCount = width * height;
  34849. // coefficients outside the encoding region treated as insignificant
  34850. // add border state cells for significanceState
  34851. this.neighborsSignificance = new Uint8Array(coefficientCount);
  34852. this.coefficentsSign = new Uint8Array(coefficientCount);
  34853. this.coefficentsMagnitude = mb > 14 ? new Uint32Array(coefficientCount) :
  34854. mb > 6 ? new Uint16Array(coefficientCount) :
  34855. new Uint8Array(coefficientCount);
  34856. this.processingFlags = new Uint8Array(coefficientCount);
  34857. var bitsDecoded = new Uint8Array(coefficientCount);
  34858. if (zeroBitPlanes !== 0) {
  34859. for (var i = 0; i < coefficientCount; i++) {
  34860. bitsDecoded[i] = zeroBitPlanes;
  34861. }
  34862. }
  34863. this.bitsDecoded = bitsDecoded;
  34864. this.reset();
  34865. }
  34866. BitModel.prototype = {
  34867. setDecoder: function BitModel_setDecoder(decoder) {
  34868. this.decoder = decoder;
  34869. },
  34870. reset: function BitModel_reset() {
  34871. // We have 17 contexts that are accessed via context labels,
  34872. // plus the uniform and runlength context.
  34873. this.contexts = new Int8Array(19);
  34874. // Contexts are packed into 1 byte:
  34875. // highest 7 bits carry the index, lowest bit carries mps
  34876. this.contexts[0] = (4 << 1) | 0;
  34877. this.contexts[UNIFORM_CONTEXT] = (46 << 1) | 0;
  34878. this.contexts[RUNLENGTH_CONTEXT] = (3 << 1) | 0;
  34879. },
  34880. setNeighborsSignificance:
  34881. function BitModel_setNeighborsSignificance(row, column, index) {
  34882. var neighborsSignificance = this.neighborsSignificance;
  34883. var width = this.width, height = this.height;
  34884. var left = (column > 0);
  34885. var right = (column + 1 < width);
  34886. var i;
  34887. if (row > 0) {
  34888. i = index - width;
  34889. if (left) {
  34890. neighborsSignificance[i - 1] += 0x10;
  34891. }
  34892. if (right) {
  34893. neighborsSignificance[i + 1] += 0x10;
  34894. }
  34895. neighborsSignificance[i] += 0x04;
  34896. }
  34897. if (row + 1 < height) {
  34898. i = index + width;
  34899. if (left) {
  34900. neighborsSignificance[i - 1] += 0x10;
  34901. }
  34902. if (right) {
  34903. neighborsSignificance[i + 1] += 0x10;
  34904. }
  34905. neighborsSignificance[i] += 0x04;
  34906. }
  34907. if (left) {
  34908. neighborsSignificance[index - 1] += 0x01;
  34909. }
  34910. if (right) {
  34911. neighborsSignificance[index + 1] += 0x01;
  34912. }
  34913. neighborsSignificance[index] |= 0x80;
  34914. },
  34915. runSignificancePropogationPass:
  34916. function BitModel_runSignificancePropogationPass() {
  34917. var decoder = this.decoder;
  34918. var width = this.width, height = this.height;
  34919. var coefficentsMagnitude = this.coefficentsMagnitude;
  34920. var coefficentsSign = this.coefficentsSign;
  34921. var neighborsSignificance = this.neighborsSignificance;
  34922. var processingFlags = this.processingFlags;
  34923. var contexts = this.contexts;
  34924. var labels = this.contextLabelTable;
  34925. var bitsDecoded = this.bitsDecoded;
  34926. var processedInverseMask = ~1;
  34927. var processedMask = 1;
  34928. var firstMagnitudeBitMask = 2;
  34929. for (var i0 = 0; i0 < height; i0 += 4) {
  34930. for (var j = 0; j < width; j++) {
  34931. var index = i0 * width + j;
  34932. for (var i1 = 0; i1 < 4; i1++, index += width) {
  34933. var i = i0 + i1;
  34934. if (i >= height) {
  34935. break;
  34936. }
  34937. // clear processed flag first
  34938. processingFlags[index] &= processedInverseMask;
  34939. if (coefficentsMagnitude[index] ||
  34940. !neighborsSignificance[index]) {
  34941. continue;
  34942. }
  34943. var contextLabel = labels[neighborsSignificance[index]];
  34944. var decision = decoder.readBit(contexts, contextLabel);
  34945. if (decision) {
  34946. var sign = this.decodeSignBit(i, j, index);
  34947. coefficentsSign[index] = sign;
  34948. coefficentsMagnitude[index] = 1;
  34949. this.setNeighborsSignificance(i, j, index);
  34950. processingFlags[index] |= firstMagnitudeBitMask;
  34951. }
  34952. bitsDecoded[index]++;
  34953. processingFlags[index] |= processedMask;
  34954. }
  34955. }
  34956. }
  34957. },
  34958. decodeSignBit: function BitModel_decodeSignBit(row, column, index) {
  34959. var width = this.width, height = this.height;
  34960. var coefficentsMagnitude = this.coefficentsMagnitude;
  34961. var coefficentsSign = this.coefficentsSign;
  34962. var contribution, sign0, sign1, significance1;
  34963. var contextLabel, decoded;
  34964. // calculate horizontal contribution
  34965. significance1 = (column > 0 && coefficentsMagnitude[index - 1] !== 0);
  34966. if (column + 1 < width && coefficentsMagnitude[index + 1] !== 0) {
  34967. sign1 = coefficentsSign[index + 1];
  34968. if (significance1) {
  34969. sign0 = coefficentsSign[index - 1];
  34970. contribution = 1 - sign1 - sign0;
  34971. } else {
  34972. contribution = 1 - sign1 - sign1;
  34973. }
  34974. } else if (significance1) {
  34975. sign0 = coefficentsSign[index - 1];
  34976. contribution = 1 - sign0 - sign0;
  34977. } else {
  34978. contribution = 0;
  34979. }
  34980. var horizontalContribution = 3 * contribution;
  34981. // calculate vertical contribution and combine with the horizontal
  34982. significance1 = (row > 0 && coefficentsMagnitude[index - width] !== 0);
  34983. if (row + 1 < height && coefficentsMagnitude[index + width] !== 0) {
  34984. sign1 = coefficentsSign[index + width];
  34985. if (significance1) {
  34986. sign0 = coefficentsSign[index - width];
  34987. contribution = 1 - sign1 - sign0 + horizontalContribution;
  34988. } else {
  34989. contribution = 1 - sign1 - sign1 + horizontalContribution;
  34990. }
  34991. } else if (significance1) {
  34992. sign0 = coefficentsSign[index - width];
  34993. contribution = 1 - sign0 - sign0 + horizontalContribution;
  34994. } else {
  34995. contribution = horizontalContribution;
  34996. }
  34997. if (contribution >= 0) {
  34998. contextLabel = 9 + contribution;
  34999. decoded = this.decoder.readBit(this.contexts, contextLabel);
  35000. } else {
  35001. contextLabel = 9 - contribution;
  35002. decoded = this.decoder.readBit(this.contexts, contextLabel) ^ 1;
  35003. }
  35004. return decoded;
  35005. },
  35006. runMagnitudeRefinementPass:
  35007. function BitModel_runMagnitudeRefinementPass() {
  35008. var decoder = this.decoder;
  35009. var width = this.width, height = this.height;
  35010. var coefficentsMagnitude = this.coefficentsMagnitude;
  35011. var neighborsSignificance = this.neighborsSignificance;
  35012. var contexts = this.contexts;
  35013. var bitsDecoded = this.bitsDecoded;
  35014. var processingFlags = this.processingFlags;
  35015. var processedMask = 1;
  35016. var firstMagnitudeBitMask = 2;
  35017. var length = width * height;
  35018. var width4 = width * 4;
  35019. for (var index0 = 0, indexNext; index0 < length; index0 = indexNext) {
  35020. indexNext = Math.min(length, index0 + width4);
  35021. for (var j = 0; j < width; j++) {
  35022. for (var index = index0 + j; index < indexNext; index += width) {
  35023. // significant but not those that have just become
  35024. if (!coefficentsMagnitude[index] ||
  35025. (processingFlags[index] & processedMask) !== 0) {
  35026. continue;
  35027. }
  35028. var contextLabel = 16;
  35029. if ((processingFlags[index] & firstMagnitudeBitMask) !== 0) {
  35030. processingFlags[index] ^= firstMagnitudeBitMask;
  35031. // first refinement
  35032. var significance = neighborsSignificance[index] & 127;
  35033. contextLabel = significance === 0 ? 15 : 14;
  35034. }
  35035. var bit = decoder.readBit(contexts, contextLabel);
  35036. coefficentsMagnitude[index] =
  35037. (coefficentsMagnitude[index] << 1) | bit;
  35038. bitsDecoded[index]++;
  35039. processingFlags[index] |= processedMask;
  35040. }
  35041. }
  35042. }
  35043. },
  35044. runCleanupPass: function BitModel_runCleanupPass() {
  35045. var decoder = this.decoder;
  35046. var width = this.width, height = this.height;
  35047. var neighborsSignificance = this.neighborsSignificance;
  35048. var coefficentsMagnitude = this.coefficentsMagnitude;
  35049. var coefficentsSign = this.coefficentsSign;
  35050. var contexts = this.contexts;
  35051. var labels = this.contextLabelTable;
  35052. var bitsDecoded = this.bitsDecoded;
  35053. var processingFlags = this.processingFlags;
  35054. var processedMask = 1;
  35055. var firstMagnitudeBitMask = 2;
  35056. var oneRowDown = width;
  35057. var twoRowsDown = width * 2;
  35058. var threeRowsDown = width * 3;
  35059. var iNext;
  35060. for (var i0 = 0; i0 < height; i0 = iNext) {
  35061. iNext = Math.min(i0 + 4, height);
  35062. var indexBase = i0 * width;
  35063. var checkAllEmpty = i0 + 3 < height;
  35064. for (var j = 0; j < width; j++) {
  35065. var index0 = indexBase + j;
  35066. // using the property: labels[neighborsSignificance[index]] === 0
  35067. // when neighborsSignificance[index] === 0
  35068. var allEmpty = (checkAllEmpty &&
  35069. processingFlags[index0] === 0 &&
  35070. processingFlags[index0 + oneRowDown] === 0 &&
  35071. processingFlags[index0 + twoRowsDown] === 0 &&
  35072. processingFlags[index0 + threeRowsDown] === 0 &&
  35073. neighborsSignificance[index0] === 0 &&
  35074. neighborsSignificance[index0 + oneRowDown] === 0 &&
  35075. neighborsSignificance[index0 + twoRowsDown] === 0 &&
  35076. neighborsSignificance[index0 + threeRowsDown] === 0);
  35077. var i1 = 0, index = index0;
  35078. var i = i0, sign;
  35079. if (allEmpty) {
  35080. var hasSignificantCoefficent =
  35081. decoder.readBit(contexts, RUNLENGTH_CONTEXT);
  35082. if (!hasSignificantCoefficent) {
  35083. bitsDecoded[index0]++;
  35084. bitsDecoded[index0 + oneRowDown]++;
  35085. bitsDecoded[index0 + twoRowsDown]++;
  35086. bitsDecoded[index0 + threeRowsDown]++;
  35087. continue; // next column
  35088. }
  35089. i1 = (decoder.readBit(contexts, UNIFORM_CONTEXT) << 1) |
  35090. decoder.readBit(contexts, UNIFORM_CONTEXT);
  35091. if (i1 !== 0) {
  35092. i = i0 + i1;
  35093. index += i1 * width;
  35094. }
  35095. sign = this.decodeSignBit(i, j, index);
  35096. coefficentsSign[index] = sign;
  35097. coefficentsMagnitude[index] = 1;
  35098. this.setNeighborsSignificance(i, j, index);
  35099. processingFlags[index] |= firstMagnitudeBitMask;
  35100. index = index0;
  35101. for (var i2 = i0; i2 <= i; i2++, index += width) {
  35102. bitsDecoded[index]++;
  35103. }
  35104. i1++;
  35105. }
  35106. for (i = i0 + i1; i < iNext; i++, index += width) {
  35107. if (coefficentsMagnitude[index] ||
  35108. (processingFlags[index] & processedMask) !== 0) {
  35109. continue;
  35110. }
  35111. var contextLabel = labels[neighborsSignificance[index]];
  35112. var decision = decoder.readBit(contexts, contextLabel);
  35113. if (decision === 1) {
  35114. sign = this.decodeSignBit(i, j, index);
  35115. coefficentsSign[index] = sign;
  35116. coefficentsMagnitude[index] = 1;
  35117. this.setNeighborsSignificance(i, j, index);
  35118. processingFlags[index] |= firstMagnitudeBitMask;
  35119. }
  35120. bitsDecoded[index]++;
  35121. }
  35122. }
  35123. }
  35124. },
  35125. checkSegmentationSymbol: function BitModel_checkSegmentationSymbol() {
  35126. var decoder = this.decoder;
  35127. var contexts = this.contexts;
  35128. var symbol = (decoder.readBit(contexts, UNIFORM_CONTEXT) << 3) |
  35129. (decoder.readBit(contexts, UNIFORM_CONTEXT) << 2) |
  35130. (decoder.readBit(contexts, UNIFORM_CONTEXT) << 1) |
  35131. decoder.readBit(contexts, UNIFORM_CONTEXT);
  35132. if (symbol !== 0xA) {
  35133. throw new Error('JPX Error: Invalid segmentation symbol');
  35134. }
  35135. }
  35136. };
  35137. return BitModel;
  35138. })();
  35139. // Section F, Discrete wavelet transformation
  35140. var Transform = (function TransformClosure() {
  35141. function Transform() {}
  35142. Transform.prototype.calculate =
  35143. function transformCalculate(subbands, u0, v0) {
  35144. var ll = subbands[0];
  35145. for (var i = 1, ii = subbands.length; i < ii; i++) {
  35146. ll = this.iterate(ll, subbands[i], u0, v0);
  35147. }
  35148. return ll;
  35149. };
  35150. Transform.prototype.extend = function extend(buffer, offset, size) {
  35151. // Section F.3.7 extending... using max extension of 4
  35152. var i1 = offset - 1, j1 = offset + 1;
  35153. var i2 = offset + size - 2, j2 = offset + size;
  35154. buffer[i1--] = buffer[j1++];
  35155. buffer[j2++] = buffer[i2--];
  35156. buffer[i1--] = buffer[j1++];
  35157. buffer[j2++] = buffer[i2--];
  35158. buffer[i1--] = buffer[j1++];
  35159. buffer[j2++] = buffer[i2--];
  35160. buffer[i1] = buffer[j1];
  35161. buffer[j2] = buffer[i2];
  35162. };
  35163. Transform.prototype.iterate = function Transform_iterate(ll, hl_lh_hh,
  35164. u0, v0) {
  35165. var llWidth = ll.width, llHeight = ll.height, llItems = ll.items;
  35166. var width = hl_lh_hh.width;
  35167. var height = hl_lh_hh.height;
  35168. var items = hl_lh_hh.items;
  35169. var i, j, k, l, u, v;
  35170. // Interleave LL according to Section F.3.3
  35171. for (k = 0, i = 0; i < llHeight; i++) {
  35172. l = i * 2 * width;
  35173. for (j = 0; j < llWidth; j++, k++, l += 2) {
  35174. items[l] = llItems[k];
  35175. }
  35176. }
  35177. // The LL band is not needed anymore.
  35178. llItems = ll.items = null;
  35179. var bufferPadding = 4;
  35180. var rowBuffer = new Float32Array(width + 2 * bufferPadding);
  35181. // Section F.3.4 HOR_SR
  35182. if (width === 1) {
  35183. // if width = 1, when u0 even keep items as is, when odd divide by 2
  35184. if ((u0 & 1) !== 0) {
  35185. for (v = 0, k = 0; v < height; v++, k += width) {
  35186. items[k] *= 0.5;
  35187. }
  35188. }
  35189. } else {
  35190. for (v = 0, k = 0; v < height; v++, k += width) {
  35191. rowBuffer.set(items.subarray(k, k + width), bufferPadding);
  35192. this.extend(rowBuffer, bufferPadding, width);
  35193. this.filter(rowBuffer, bufferPadding, width);
  35194. items.set(
  35195. rowBuffer.subarray(bufferPadding, bufferPadding + width),
  35196. k);
  35197. }
  35198. }
  35199. // Accesses to the items array can take long, because it may not fit into
  35200. // CPU cache and has to be fetched from main memory. Since subsequent
  35201. // accesses to the items array are not local when reading columns, we
  35202. // have a cache miss every time. To reduce cache misses, get up to
  35203. // 'numBuffers' items at a time and store them into the individual
  35204. // buffers. The colBuffers should be small enough to fit into CPU cache.
  35205. var numBuffers = 16;
  35206. var colBuffers = [];
  35207. for (i = 0; i < numBuffers; i++) {
  35208. colBuffers.push(new Float32Array(height + 2 * bufferPadding));
  35209. }
  35210. var b, currentBuffer = 0;
  35211. ll = bufferPadding + height;
  35212. // Section F.3.5 VER_SR
  35213. if (height === 1) {
  35214. // if height = 1, when v0 even keep items as is, when odd divide by 2
  35215. if ((v0 & 1) !== 0) {
  35216. for (u = 0; u < width; u++) {
  35217. items[u] *= 0.5;
  35218. }
  35219. }
  35220. } else {
  35221. for (u = 0; u < width; u++) {
  35222. // if we ran out of buffers, copy several image columns at once
  35223. if (currentBuffer === 0) {
  35224. numBuffers = Math.min(width - u, numBuffers);
  35225. for (k = u, l = bufferPadding; l < ll; k += width, l++) {
  35226. for (b = 0; b < numBuffers; b++) {
  35227. colBuffers[b][l] = items[k + b];
  35228. }
  35229. }
  35230. currentBuffer = numBuffers;
  35231. }
  35232. currentBuffer--;
  35233. var buffer = colBuffers[currentBuffer];
  35234. this.extend(buffer, bufferPadding, height);
  35235. this.filter(buffer, bufferPadding, height);
  35236. // If this is last buffer in this group of buffers, flush all buffers.
  35237. if (currentBuffer === 0) {
  35238. k = u - numBuffers + 1;
  35239. for (l = bufferPadding; l < ll; k += width, l++) {
  35240. for (b = 0; b < numBuffers; b++) {
  35241. items[k + b] = colBuffers[b][l];
  35242. }
  35243. }
  35244. }
  35245. }
  35246. }
  35247. return {
  35248. width: width,
  35249. height: height,
  35250. items: items
  35251. };
  35252. };
  35253. return Transform;
  35254. })();
  35255. // Section 3.8.2 Irreversible 9-7 filter
  35256. var IrreversibleTransform = (function IrreversibleTransformClosure() {
  35257. function IrreversibleTransform() {
  35258. Transform.call(this);
  35259. }
  35260. IrreversibleTransform.prototype = Object.create(Transform.prototype);
  35261. IrreversibleTransform.prototype.filter =
  35262. function irreversibleTransformFilter(x, offset, length) {
  35263. var len = length >> 1;
  35264. offset = offset | 0;
  35265. var j, n, current, next;
  35266. var alpha = -1.586134342059924;
  35267. var beta = -0.052980118572961;
  35268. var gamma = 0.882911075530934;
  35269. var delta = 0.443506852043971;
  35270. var K = 1.230174104914001;
  35271. var K_ = 1 / K;
  35272. // step 1 is combined with step 3
  35273. // step 2
  35274. j = offset - 3;
  35275. for (n = len + 4; n--; j += 2) {
  35276. x[j] *= K_;
  35277. }
  35278. // step 1 & 3
  35279. j = offset - 2;
  35280. current = delta * x[j -1];
  35281. for (n = len + 3; n--; j += 2) {
  35282. next = delta * x[j + 1];
  35283. x[j] = K * x[j] - current - next;
  35284. if (n--) {
  35285. j += 2;
  35286. current = delta * x[j + 1];
  35287. x[j] = K * x[j] - current - next;
  35288. } else {
  35289. break;
  35290. }
  35291. }
  35292. // step 4
  35293. j = offset - 1;
  35294. current = gamma * x[j - 1];
  35295. for (n = len + 2; n--; j += 2) {
  35296. next = gamma * x[j + 1];
  35297. x[j] -= current + next;
  35298. if (n--) {
  35299. j += 2;
  35300. current = gamma * x[j + 1];
  35301. x[j] -= current + next;
  35302. } else {
  35303. break;
  35304. }
  35305. }
  35306. // step 5
  35307. j = offset;
  35308. current = beta * x[j - 1];
  35309. for (n = len + 1; n--; j += 2) {
  35310. next = beta * x[j + 1];
  35311. x[j] -= current + next;
  35312. if (n--) {
  35313. j += 2;
  35314. current = beta * x[j + 1];
  35315. x[j] -= current + next;
  35316. } else {
  35317. break;
  35318. }
  35319. }
  35320. // step 6
  35321. if (len !== 0) {
  35322. j = offset + 1;
  35323. current = alpha * x[j - 1];
  35324. for (n = len; n--; j += 2) {
  35325. next = alpha * x[j + 1];
  35326. x[j] -= current + next;
  35327. if (n--) {
  35328. j += 2;
  35329. current = alpha * x[j + 1];
  35330. x[j] -= current + next;
  35331. } else {
  35332. break;
  35333. }
  35334. }
  35335. }
  35336. };
  35337. return IrreversibleTransform;
  35338. })();
  35339. // Section 3.8.1 Reversible 5-3 filter
  35340. var ReversibleTransform = (function ReversibleTransformClosure() {
  35341. function ReversibleTransform() {
  35342. Transform.call(this);
  35343. }
  35344. ReversibleTransform.prototype = Object.create(Transform.prototype);
  35345. ReversibleTransform.prototype.filter =
  35346. function reversibleTransformFilter(x, offset, length) {
  35347. var len = length >> 1;
  35348. offset = offset | 0;
  35349. var j, n;
  35350. for (j = offset, n = len + 1; n--; j += 2) {
  35351. x[j] -= (x[j - 1] + x[j + 1] + 2) >> 2;
  35352. }
  35353. for (j = offset + 1, n = len; n--; j += 2) {
  35354. x[j] += (x[j - 1] + x[j + 1]) >> 1;
  35355. }
  35356. };
  35357. return ReversibleTransform;
  35358. })();
  35359. return JpxImage;
  35360. })();
  35361. var Jbig2Image = (function Jbig2ImageClosure() {
  35362. // Utility data structures
  35363. function ContextCache() {}
  35364. ContextCache.prototype = {
  35365. getContexts: function(id) {
  35366. if (id in this) {
  35367. return this[id];
  35368. }
  35369. return (this[id] = new Int8Array(1 << 16));
  35370. }
  35371. };
  35372. function DecodingContext(data, start, end) {
  35373. this.data = data;
  35374. this.start = start;
  35375. this.end = end;
  35376. }
  35377. DecodingContext.prototype = {
  35378. get decoder() {
  35379. var decoder = new ArithmeticDecoder(this.data, this.start, this.end);
  35380. return shadow(this, 'decoder', decoder);
  35381. },
  35382. get contextCache() {
  35383. var cache = new ContextCache();
  35384. return shadow(this, 'contextCache', cache);
  35385. }
  35386. };
  35387. // Annex A. Arithmetic Integer Decoding Procedure
  35388. // A.2 Procedure for decoding values
  35389. function decodeInteger(contextCache, procedure, decoder) {
  35390. var contexts = contextCache.getContexts(procedure);
  35391. var prev = 1;
  35392. function readBits(length) {
  35393. var v = 0;
  35394. for (var i = 0; i < length; i++) {
  35395. var bit = decoder.readBit(contexts, prev);
  35396. prev = (prev < 256 ? (prev << 1) | bit :
  35397. (((prev << 1) | bit) & 511) | 256);
  35398. v = (v << 1) | bit;
  35399. }
  35400. return v >>> 0;
  35401. }
  35402. var sign = readBits(1);
  35403. var value = readBits(1) ?
  35404. (readBits(1) ?
  35405. (readBits(1) ?
  35406. (readBits(1) ?
  35407. (readBits(1) ?
  35408. (readBits(32) + 4436) :
  35409. readBits(12) + 340) :
  35410. readBits(8) + 84) :
  35411. readBits(6) + 20) :
  35412. readBits(4) + 4) :
  35413. readBits(2);
  35414. return (sign === 0 ? value : (value > 0 ? -value : null));
  35415. }
  35416. // A.3 The IAID decoding procedure
  35417. function decodeIAID(contextCache, decoder, codeLength) {
  35418. var contexts = contextCache.getContexts('IAID');
  35419. var prev = 1;
  35420. for (var i = 0; i < codeLength; i++) {
  35421. var bit = decoder.readBit(contexts, prev);
  35422. prev = (prev << 1) | bit;
  35423. }
  35424. if (codeLength < 31) {
  35425. return prev & ((1 << codeLength) - 1);
  35426. }
  35427. return prev & 0x7FFFFFFF;
  35428. }
  35429. // 7.3 Segment types
  35430. var SegmentTypes = [
  35431. 'SymbolDictionary', null, null, null, 'IntermediateTextRegion', null,
  35432. 'ImmediateTextRegion', 'ImmediateLosslessTextRegion', null, null, null,
  35433. null, null, null, null, null, 'patternDictionary', null, null, null,
  35434. 'IntermediateHalftoneRegion', null, 'ImmediateHalftoneRegion',
  35435. 'ImmediateLosslessHalftoneRegion', null, null, null, null, null, null, null,
  35436. null, null, null, null, null, 'IntermediateGenericRegion', null,
  35437. 'ImmediateGenericRegion', 'ImmediateLosslessGenericRegion',
  35438. 'IntermediateGenericRefinementRegion', null,
  35439. 'ImmediateGenericRefinementRegion',
  35440. 'ImmediateLosslessGenericRefinementRegion', null, null, null, null,
  35441. 'PageInformation', 'EndOfPage', 'EndOfStripe', 'EndOfFile', 'Profiles',
  35442. 'Tables', null, null, null, null, null, null, null, null,
  35443. 'Extension'
  35444. ];
  35445. var CodingTemplates = [
  35446. [{x: -1, y: -2}, {x: 0, y: -2}, {x: 1, y: -2}, {x: -2, y: -1},
  35447. {x: -1, y: -1}, {x: 0, y: -1}, {x: 1, y: -1}, {x: 2, y: -1},
  35448. {x: -4, y: 0}, {x: -3, y: 0}, {x: -2, y: 0}, {x: -1, y: 0}],
  35449. [{x: -1, y: -2}, {x: 0, y: -2}, {x: 1, y: -2}, {x: 2, y: -2},
  35450. {x: -2, y: -1}, {x: -1, y: -1}, {x: 0, y: -1}, {x: 1, y: -1},
  35451. {x: 2, y: -1}, {x: -3, y: 0}, {x: -2, y: 0}, {x: -1, y: 0}],
  35452. [{x: -1, y: -2}, {x: 0, y: -2}, {x: 1, y: -2}, {x: -2, y: -1},
  35453. {x: -1, y: -1}, {x: 0, y: -1}, {x: 1, y: -1}, {x: -2, y: 0},
  35454. {x: -1, y: 0}],
  35455. [{x: -3, y: -1}, {x: -2, y: -1}, {x: -1, y: -1}, {x: 0, y: -1},
  35456. {x: 1, y: -1}, {x: -4, y: 0}, {x: -3, y: 0}, {x: -2, y: 0}, {x: -1, y: 0}]
  35457. ];
  35458. var RefinementTemplates = [
  35459. {
  35460. coding: [{x: 0, y: -1}, {x: 1, y: -1}, {x: -1, y: 0}],
  35461. reference: [{x: 0, y: -1}, {x: 1, y: -1}, {x: -1, y: 0}, {x: 0, y: 0},
  35462. {x: 1, y: 0}, {x: -1, y: 1}, {x: 0, y: 1}, {x: 1, y: 1}]
  35463. },
  35464. {
  35465. coding: [{x: -1, y: -1}, {x: 0, y: -1}, {x: 1, y: -1}, {x: -1, y: 0}],
  35466. reference: [{x: 0, y: -1}, {x: -1, y: 0}, {x: 0, y: 0}, {x: 1, y: 0},
  35467. {x: 0, y: 1}, {x: 1, y: 1}]
  35468. }
  35469. ];
  35470. // See 6.2.5.7 Decoding the bitmap.
  35471. var ReusedContexts = [
  35472. 0x9B25, // 10011 0110010 0101
  35473. 0x0795, // 0011 110010 101
  35474. 0x00E5, // 001 11001 01
  35475. 0x0195 // 011001 0101
  35476. ];
  35477. var RefinementReusedContexts = [
  35478. 0x0020, // '000' + '0' (coding) + '00010000' + '0' (reference)
  35479. 0x0008 // '0000' + '001000'
  35480. ];
  35481. function decodeBitmapTemplate0(width, height, decodingContext) {
  35482. var decoder = decodingContext.decoder;
  35483. var contexts = decodingContext.contextCache.getContexts('GB');
  35484. var contextLabel, i, j, pixel, row, row1, row2, bitmap = [];
  35485. // ...ooooo....
  35486. // ..ooooooo... Context template for current pixel (X)
  35487. // .ooooX...... (concatenate values of 'o'-pixels to get contextLabel)
  35488. var OLD_PIXEL_MASK = 0x7BF7; // 01111 0111111 0111
  35489. for (i = 0; i < height; i++) {
  35490. row = bitmap[i] = new Uint8Array(width);
  35491. row1 = (i < 1) ? row : bitmap[i - 1];
  35492. row2 = (i < 2) ? row : bitmap[i - 2];
  35493. // At the beginning of each row:
  35494. // Fill contextLabel with pixels that are above/right of (X)
  35495. contextLabel = (row2[0] << 13) | (row2[1] << 12) | (row2[2] << 11) |
  35496. (row1[0] << 7) | (row1[1] << 6) | (row1[2] << 5) |
  35497. (row1[3] << 4);
  35498. for (j = 0; j < width; j++) {
  35499. row[j] = pixel = decoder.readBit(contexts, contextLabel);
  35500. // At each pixel: Clear contextLabel pixels that are shifted
  35501. // out of the context, then add new ones.
  35502. contextLabel = ((contextLabel & OLD_PIXEL_MASK) << 1) |
  35503. (j + 3 < width ? row2[j + 3] << 11 : 0) |
  35504. (j + 4 < width ? row1[j + 4] << 4 : 0) | pixel;
  35505. }
  35506. }
  35507. return bitmap;
  35508. }
  35509. // 6.2 Generic Region Decoding Procedure
  35510. function decodeBitmap(mmr, width, height, templateIndex, prediction, skip, at,
  35511. decodingContext) {
  35512. if (mmr) {
  35513. error('JBIG2 error: MMR encoding is not supported');
  35514. }
  35515. // Use optimized version for the most common case
  35516. if (templateIndex === 0 && !skip && !prediction && at.length === 4 &&
  35517. at[0].x === 3 && at[0].y === -1 && at[1].x === -3 && at[1].y === -1 &&
  35518. at[2].x === 2 && at[2].y === -2 && at[3].x === -2 && at[3].y === -2) {
  35519. return decodeBitmapTemplate0(width, height, decodingContext);
  35520. }
  35521. var useskip = !!skip;
  35522. var template = CodingTemplates[templateIndex].concat(at);
  35523. // Sorting is non-standard, and it is not required. But sorting increases
  35524. // the number of template bits that can be reused from the previous
  35525. // contextLabel in the main loop.
  35526. template.sort(function (a, b) {
  35527. return (a.y - b.y) || (a.x - b.x);
  35528. });
  35529. var templateLength = template.length;
  35530. var templateX = new Int8Array(templateLength);
  35531. var templateY = new Int8Array(templateLength);
  35532. var changingTemplateEntries = [];
  35533. var reuseMask = 0, minX = 0, maxX = 0, minY = 0;
  35534. var c, k;
  35535. for (k = 0; k < templateLength; k++) {
  35536. templateX[k] = template[k].x;
  35537. templateY[k] = template[k].y;
  35538. minX = Math.min(minX, template[k].x);
  35539. maxX = Math.max(maxX, template[k].x);
  35540. minY = Math.min(minY, template[k].y);
  35541. // Check if the template pixel appears in two consecutive context labels,
  35542. // so it can be reused. Otherwise, we add it to the list of changing
  35543. // template entries.
  35544. if (k < templateLength - 1 &&
  35545. template[k].y === template[k + 1].y &&
  35546. template[k].x === template[k + 1].x - 1) {
  35547. reuseMask |= 1 << (templateLength - 1 - k);
  35548. } else {
  35549. changingTemplateEntries.push(k);
  35550. }
  35551. }
  35552. var changingEntriesLength = changingTemplateEntries.length;
  35553. var changingTemplateX = new Int8Array(changingEntriesLength);
  35554. var changingTemplateY = new Int8Array(changingEntriesLength);
  35555. var changingTemplateBit = new Uint16Array(changingEntriesLength);
  35556. for (c = 0; c < changingEntriesLength; c++) {
  35557. k = changingTemplateEntries[c];
  35558. changingTemplateX[c] = template[k].x;
  35559. changingTemplateY[c] = template[k].y;
  35560. changingTemplateBit[c] = 1 << (templateLength - 1 - k);
  35561. }
  35562. // Get the safe bounding box edges from the width, height, minX, maxX, minY
  35563. var sbb_left = -minX;
  35564. var sbb_top = -minY;
  35565. var sbb_right = width - maxX;
  35566. var pseudoPixelContext = ReusedContexts[templateIndex];
  35567. var row = new Uint8Array(width);
  35568. var bitmap = [];
  35569. var decoder = decodingContext.decoder;
  35570. var contexts = decodingContext.contextCache.getContexts('GB');
  35571. var ltp = 0, j, i0, j0, contextLabel = 0, bit, shift;
  35572. for (var i = 0; i < height; i++) {
  35573. if (prediction) {
  35574. var sltp = decoder.readBit(contexts, pseudoPixelContext);
  35575. ltp ^= sltp;
  35576. if (ltp) {
  35577. bitmap.push(row); // duplicate previous row
  35578. continue;
  35579. }
  35580. }
  35581. row = new Uint8Array(row);
  35582. bitmap.push(row);
  35583. for (j = 0; j < width; j++) {
  35584. if (useskip && skip[i][j]) {
  35585. row[j] = 0;
  35586. continue;
  35587. }
  35588. // Are we in the middle of a scanline, so we can reuse contextLabel
  35589. // bits?
  35590. if (j >= sbb_left && j < sbb_right && i >= sbb_top) {
  35591. // If yes, we can just shift the bits that are reusable and only
  35592. // fetch the remaining ones.
  35593. contextLabel = (contextLabel << 1) & reuseMask;
  35594. for (k = 0; k < changingEntriesLength; k++) {
  35595. i0 = i + changingTemplateY[k];
  35596. j0 = j + changingTemplateX[k];
  35597. bit = bitmap[i0][j0];
  35598. if (bit) {
  35599. bit = changingTemplateBit[k];
  35600. contextLabel |= bit;
  35601. }
  35602. }
  35603. } else {
  35604. // compute the contextLabel from scratch
  35605. contextLabel = 0;
  35606. shift = templateLength - 1;
  35607. for (k = 0; k < templateLength; k++, shift--) {
  35608. j0 = j + templateX[k];
  35609. if (j0 >= 0 && j0 < width) {
  35610. i0 = i + templateY[k];
  35611. if (i0 >= 0) {
  35612. bit = bitmap[i0][j0];
  35613. if (bit) {
  35614. contextLabel |= bit << shift;
  35615. }
  35616. }
  35617. }
  35618. }
  35619. }
  35620. var pixel = decoder.readBit(contexts, contextLabel);
  35621. row[j] = pixel;
  35622. }
  35623. }
  35624. return bitmap;
  35625. }
  35626. // 6.3.2 Generic Refinement Region Decoding Procedure
  35627. function decodeRefinement(width, height, templateIndex, referenceBitmap,
  35628. offsetX, offsetY, prediction, at,
  35629. decodingContext) {
  35630. var codingTemplate = RefinementTemplates[templateIndex].coding;
  35631. if (templateIndex === 0) {
  35632. codingTemplate = codingTemplate.concat([at[0]]);
  35633. }
  35634. var codingTemplateLength = codingTemplate.length;
  35635. var codingTemplateX = new Int32Array(codingTemplateLength);
  35636. var codingTemplateY = new Int32Array(codingTemplateLength);
  35637. var k;
  35638. for (k = 0; k < codingTemplateLength; k++) {
  35639. codingTemplateX[k] = codingTemplate[k].x;
  35640. codingTemplateY[k] = codingTemplate[k].y;
  35641. }
  35642. var referenceTemplate = RefinementTemplates[templateIndex].reference;
  35643. if (templateIndex === 0) {
  35644. referenceTemplate = referenceTemplate.concat([at[1]]);
  35645. }
  35646. var referenceTemplateLength = referenceTemplate.length;
  35647. var referenceTemplateX = new Int32Array(referenceTemplateLength);
  35648. var referenceTemplateY = new Int32Array(referenceTemplateLength);
  35649. for (k = 0; k < referenceTemplateLength; k++) {
  35650. referenceTemplateX[k] = referenceTemplate[k].x;
  35651. referenceTemplateY[k] = referenceTemplate[k].y;
  35652. }
  35653. var referenceWidth = referenceBitmap[0].length;
  35654. var referenceHeight = referenceBitmap.length;
  35655. var pseudoPixelContext = RefinementReusedContexts[templateIndex];
  35656. var bitmap = [];
  35657. var decoder = decodingContext.decoder;
  35658. var contexts = decodingContext.contextCache.getContexts('GR');
  35659. var ltp = 0;
  35660. for (var i = 0; i < height; i++) {
  35661. if (prediction) {
  35662. var sltp = decoder.readBit(contexts, pseudoPixelContext);
  35663. ltp ^= sltp;
  35664. if (ltp) {
  35665. error('JBIG2 error: prediction is not supported');
  35666. }
  35667. }
  35668. var row = new Uint8Array(width);
  35669. bitmap.push(row);
  35670. for (var j = 0; j < width; j++) {
  35671. var i0, j0;
  35672. var contextLabel = 0;
  35673. for (k = 0; k < codingTemplateLength; k++) {
  35674. i0 = i + codingTemplateY[k];
  35675. j0 = j + codingTemplateX[k];
  35676. if (i0 < 0 || j0 < 0 || j0 >= width) {
  35677. contextLabel <<= 1; // out of bound pixel
  35678. } else {
  35679. contextLabel = (contextLabel << 1) | bitmap[i0][j0];
  35680. }
  35681. }
  35682. for (k = 0; k < referenceTemplateLength; k++) {
  35683. i0 = i + referenceTemplateY[k] + offsetY;
  35684. j0 = j + referenceTemplateX[k] + offsetX;
  35685. if (i0 < 0 || i0 >= referenceHeight || j0 < 0 ||
  35686. j0 >= referenceWidth) {
  35687. contextLabel <<= 1; // out of bound pixel
  35688. } else {
  35689. contextLabel = (contextLabel << 1) | referenceBitmap[i0][j0];
  35690. }
  35691. }
  35692. var pixel = decoder.readBit(contexts, contextLabel);
  35693. row[j] = pixel;
  35694. }
  35695. }
  35696. return bitmap;
  35697. }
  35698. // 6.5.5 Decoding the symbol dictionary
  35699. function decodeSymbolDictionary(huffman, refinement, symbols,
  35700. numberOfNewSymbols, numberOfExportedSymbols,
  35701. huffmanTables, templateIndex, at,
  35702. refinementTemplateIndex, refinementAt,
  35703. decodingContext) {
  35704. if (huffman) {
  35705. error('JBIG2 error: huffman is not supported');
  35706. }
  35707. var newSymbols = [];
  35708. var currentHeight = 0;
  35709. var symbolCodeLength = log2(symbols.length + numberOfNewSymbols);
  35710. var decoder = decodingContext.decoder;
  35711. var contextCache = decodingContext.contextCache;
  35712. while (newSymbols.length < numberOfNewSymbols) {
  35713. var deltaHeight = decodeInteger(contextCache, 'IADH', decoder); // 6.5.6
  35714. currentHeight += deltaHeight;
  35715. var currentWidth = 0;
  35716. var totalWidth = 0;
  35717. while (true) {
  35718. var deltaWidth = decodeInteger(contextCache, 'IADW', decoder); // 6.5.7
  35719. if (deltaWidth === null) {
  35720. break; // OOB
  35721. }
  35722. currentWidth += deltaWidth;
  35723. totalWidth += currentWidth;
  35724. var bitmap;
  35725. if (refinement) {
  35726. // 6.5.8.2 Refinement/aggregate-coded symbol bitmap
  35727. var numberOfInstances = decodeInteger(contextCache, 'IAAI', decoder);
  35728. if (numberOfInstances > 1) {
  35729. bitmap = decodeTextRegion(huffman, refinement,
  35730. currentWidth, currentHeight, 0,
  35731. numberOfInstances, 1, //strip size
  35732. symbols.concat(newSymbols),
  35733. symbolCodeLength,
  35734. 0, //transposed
  35735. 0, //ds offset
  35736. 1, //top left 7.4.3.1.1
  35737. 0, //OR operator
  35738. huffmanTables,
  35739. refinementTemplateIndex, refinementAt,
  35740. decodingContext);
  35741. } else {
  35742. var symbolId = decodeIAID(contextCache, decoder, symbolCodeLength);
  35743. var rdx = decodeInteger(contextCache, 'IARDX', decoder); // 6.4.11.3
  35744. var rdy = decodeInteger(contextCache, 'IARDY', decoder); // 6.4.11.4
  35745. var symbol = (symbolId < symbols.length ? symbols[symbolId] :
  35746. newSymbols[symbolId - symbols.length]);
  35747. bitmap = decodeRefinement(currentWidth, currentHeight,
  35748. refinementTemplateIndex, symbol, rdx, rdy, false, refinementAt,
  35749. decodingContext);
  35750. }
  35751. } else {
  35752. // 6.5.8.1 Direct-coded symbol bitmap
  35753. bitmap = decodeBitmap(false, currentWidth, currentHeight,
  35754. templateIndex, false, null, at, decodingContext);
  35755. }
  35756. newSymbols.push(bitmap);
  35757. }
  35758. }
  35759. // 6.5.10 Exported symbols
  35760. var exportedSymbols = [];
  35761. var flags = [], currentFlag = false;
  35762. var totalSymbolsLength = symbols.length + numberOfNewSymbols;
  35763. while (flags.length < totalSymbolsLength) {
  35764. var runLength = decodeInteger(contextCache, 'IAEX', decoder);
  35765. while (runLength--) {
  35766. flags.push(currentFlag);
  35767. }
  35768. currentFlag = !currentFlag;
  35769. }
  35770. for (var i = 0, ii = symbols.length; i < ii; i++) {
  35771. if (flags[i]) {
  35772. exportedSymbols.push(symbols[i]);
  35773. }
  35774. }
  35775. for (var j = 0; j < numberOfNewSymbols; i++, j++) {
  35776. if (flags[i]) {
  35777. exportedSymbols.push(newSymbols[j]);
  35778. }
  35779. }
  35780. return exportedSymbols;
  35781. }
  35782. function decodeTextRegion(huffman, refinement, width, height,
  35783. defaultPixelValue, numberOfSymbolInstances,
  35784. stripSize, inputSymbols, symbolCodeLength,
  35785. transposed, dsOffset, referenceCorner,
  35786. combinationOperator, huffmanTables,
  35787. refinementTemplateIndex, refinementAt,
  35788. decodingContext) {
  35789. if (huffman) {
  35790. error('JBIG2 error: huffman is not supported');
  35791. }
  35792. // Prepare bitmap
  35793. var bitmap = [];
  35794. var i, row;
  35795. for (i = 0; i < height; i++) {
  35796. row = new Uint8Array(width);
  35797. if (defaultPixelValue) {
  35798. for (var j = 0; j < width; j++) {
  35799. row[j] = defaultPixelValue;
  35800. }
  35801. }
  35802. bitmap.push(row);
  35803. }
  35804. var decoder = decodingContext.decoder;
  35805. var contextCache = decodingContext.contextCache;
  35806. var stripT = -decodeInteger(contextCache, 'IADT', decoder); // 6.4.6
  35807. var firstS = 0;
  35808. i = 0;
  35809. while (i < numberOfSymbolInstances) {
  35810. var deltaT = decodeInteger(contextCache, 'IADT', decoder); // 6.4.6
  35811. stripT += deltaT;
  35812. var deltaFirstS = decodeInteger(contextCache, 'IAFS', decoder); // 6.4.7
  35813. firstS += deltaFirstS;
  35814. var currentS = firstS;
  35815. do {
  35816. var currentT = (stripSize === 1 ? 0 :
  35817. decodeInteger(contextCache, 'IAIT', decoder)); // 6.4.9
  35818. var t = stripSize * stripT + currentT;
  35819. var symbolId = decodeIAID(contextCache, decoder, symbolCodeLength);
  35820. var applyRefinement = (refinement &&
  35821. decodeInteger(contextCache, 'IARI', decoder));
  35822. var symbolBitmap = inputSymbols[symbolId];
  35823. var symbolWidth = symbolBitmap[0].length;
  35824. var symbolHeight = symbolBitmap.length;
  35825. if (applyRefinement) {
  35826. var rdw = decodeInteger(contextCache, 'IARDW', decoder); // 6.4.11.1
  35827. var rdh = decodeInteger(contextCache, 'IARDH', decoder); // 6.4.11.2
  35828. var rdx = decodeInteger(contextCache, 'IARDX', decoder); // 6.4.11.3
  35829. var rdy = decodeInteger(contextCache, 'IARDY', decoder); // 6.4.11.4
  35830. symbolWidth += rdw;
  35831. symbolHeight += rdh;
  35832. symbolBitmap = decodeRefinement(symbolWidth, symbolHeight,
  35833. refinementTemplateIndex, symbolBitmap, (rdw >> 1) + rdx,
  35834. (rdh >> 1) + rdy, false, refinementAt,
  35835. decodingContext);
  35836. }
  35837. var offsetT = t - ((referenceCorner & 1) ? 0 : symbolHeight);
  35838. var offsetS = currentS - ((referenceCorner & 2) ? symbolWidth : 0);
  35839. var s2, t2, symbolRow;
  35840. if (transposed) {
  35841. // Place Symbol Bitmap from T1,S1
  35842. for (s2 = 0; s2 < symbolHeight; s2++) {
  35843. row = bitmap[offsetS + s2];
  35844. if (!row) {
  35845. continue;
  35846. }
  35847. symbolRow = symbolBitmap[s2];
  35848. // To ignore Parts of Symbol bitmap which goes
  35849. // outside bitmap region
  35850. var maxWidth = Math.min(width - offsetT, symbolWidth);
  35851. switch (combinationOperator) {
  35852. case 0: // OR
  35853. for (t2 = 0; t2 < maxWidth; t2++) {
  35854. row[offsetT + t2] |= symbolRow[t2];
  35855. }
  35856. break;
  35857. case 2: // XOR
  35858. for (t2 = 0; t2 < maxWidth; t2++) {
  35859. row[offsetT + t2] ^= symbolRow[t2];
  35860. }
  35861. break;
  35862. default:
  35863. error('JBIG2 error: operator ' + combinationOperator +
  35864. ' is not supported');
  35865. }
  35866. }
  35867. currentS += symbolHeight - 1;
  35868. } else {
  35869. for (t2 = 0; t2 < symbolHeight; t2++) {
  35870. row = bitmap[offsetT + t2];
  35871. if (!row) {
  35872. continue;
  35873. }
  35874. symbolRow = symbolBitmap[t2];
  35875. switch (combinationOperator) {
  35876. case 0: // OR
  35877. for (s2 = 0; s2 < symbolWidth; s2++) {
  35878. row[offsetS + s2] |= symbolRow[s2];
  35879. }
  35880. break;
  35881. case 2: // XOR
  35882. for (s2 = 0; s2 < symbolWidth; s2++) {
  35883. row[offsetS + s2] ^= symbolRow[s2];
  35884. }
  35885. break;
  35886. default:
  35887. error('JBIG2 error: operator ' + combinationOperator +
  35888. ' is not supported');
  35889. }
  35890. }
  35891. currentS += symbolWidth - 1;
  35892. }
  35893. i++;
  35894. var deltaS = decodeInteger(contextCache, 'IADS', decoder); // 6.4.8
  35895. if (deltaS === null) {
  35896. break; // OOB
  35897. }
  35898. currentS += deltaS + dsOffset;
  35899. } while (true);
  35900. }
  35901. return bitmap;
  35902. }
  35903. function readSegmentHeader(data, start) {
  35904. var segmentHeader = {};
  35905. segmentHeader.number = readUint32(data, start);
  35906. var flags = data[start + 4];
  35907. var segmentType = flags & 0x3F;
  35908. if (!SegmentTypes[segmentType]) {
  35909. error('JBIG2 error: invalid segment type: ' + segmentType);
  35910. }
  35911. segmentHeader.type = segmentType;
  35912. segmentHeader.typeName = SegmentTypes[segmentType];
  35913. segmentHeader.deferredNonRetain = !!(flags & 0x80);
  35914. var pageAssociationFieldSize = !!(flags & 0x40);
  35915. var referredFlags = data[start + 5];
  35916. var referredToCount = (referredFlags >> 5) & 7;
  35917. var retainBits = [referredFlags & 31];
  35918. var position = start + 6;
  35919. if (referredFlags === 7) {
  35920. referredToCount = readUint32(data, position - 1) & 0x1FFFFFFF;
  35921. position += 3;
  35922. var bytes = (referredToCount + 7) >> 3;
  35923. retainBits[0] = data[position++];
  35924. while (--bytes > 0) {
  35925. retainBits.push(data[position++]);
  35926. }
  35927. } else if (referredFlags === 5 || referredFlags === 6) {
  35928. error('JBIG2 error: invalid referred-to flags');
  35929. }
  35930. segmentHeader.retainBits = retainBits;
  35931. var referredToSegmentNumberSize = (segmentHeader.number <= 256 ? 1 :
  35932. (segmentHeader.number <= 65536 ? 2 : 4));
  35933. var referredTo = [];
  35934. var i, ii;
  35935. for (i = 0; i < referredToCount; i++) {
  35936. var number = (referredToSegmentNumberSize === 1 ? data[position] :
  35937. (referredToSegmentNumberSize === 2 ? readUint16(data, position) :
  35938. readUint32(data, position)));
  35939. referredTo.push(number);
  35940. position += referredToSegmentNumberSize;
  35941. }
  35942. segmentHeader.referredTo = referredTo;
  35943. if (!pageAssociationFieldSize) {
  35944. segmentHeader.pageAssociation = data[position++];
  35945. } else {
  35946. segmentHeader.pageAssociation = readUint32(data, position);
  35947. position += 4;
  35948. }
  35949. segmentHeader.length = readUint32(data, position);
  35950. position += 4;
  35951. if (segmentHeader.length === 0xFFFFFFFF) {
  35952. // 7.2.7 Segment data length, unknown segment length
  35953. if (segmentType === 38) { // ImmediateGenericRegion
  35954. var genericRegionInfo = readRegionSegmentInformation(data, position);
  35955. var genericRegionSegmentFlags = data[position +
  35956. RegionSegmentInformationFieldLength];
  35957. var genericRegionMmr = !!(genericRegionSegmentFlags & 1);
  35958. // searching for the segment end
  35959. var searchPatternLength = 6;
  35960. var searchPattern = new Uint8Array(searchPatternLength);
  35961. if (!genericRegionMmr) {
  35962. searchPattern[0] = 0xFF;
  35963. searchPattern[1] = 0xAC;
  35964. }
  35965. searchPattern[2] = (genericRegionInfo.height >>> 24) & 0xFF;
  35966. searchPattern[3] = (genericRegionInfo.height >> 16) & 0xFF;
  35967. searchPattern[4] = (genericRegionInfo.height >> 8) & 0xFF;
  35968. searchPattern[5] = genericRegionInfo.height & 0xFF;
  35969. for (i = position, ii = data.length; i < ii; i++) {
  35970. var j = 0;
  35971. while (j < searchPatternLength && searchPattern[j] === data[i + j]) {
  35972. j++;
  35973. }
  35974. if (j === searchPatternLength) {
  35975. segmentHeader.length = i + searchPatternLength;
  35976. break;
  35977. }
  35978. }
  35979. if (segmentHeader.length === 0xFFFFFFFF) {
  35980. error('JBIG2 error: segment end was not found');
  35981. }
  35982. } else {
  35983. error('JBIG2 error: invalid unknown segment length');
  35984. }
  35985. }
  35986. segmentHeader.headerEnd = position;
  35987. return segmentHeader;
  35988. }
  35989. function readSegments(header, data, start, end) {
  35990. var segments = [];
  35991. var position = start;
  35992. while (position < end) {
  35993. var segmentHeader = readSegmentHeader(data, position);
  35994. position = segmentHeader.headerEnd;
  35995. var segment = {
  35996. header: segmentHeader,
  35997. data: data
  35998. };
  35999. if (!header.randomAccess) {
  36000. segment.start = position;
  36001. position += segmentHeader.length;
  36002. segment.end = position;
  36003. }
  36004. segments.push(segment);
  36005. if (segmentHeader.type === 51) {
  36006. break; // end of file is found
  36007. }
  36008. }
  36009. if (header.randomAccess) {
  36010. for (var i = 0, ii = segments.length; i < ii; i++) {
  36011. segments[i].start = position;
  36012. position += segments[i].header.length;
  36013. segments[i].end = position;
  36014. }
  36015. }
  36016. return segments;
  36017. }
  36018. // 7.4.1 Region segment information field
  36019. function readRegionSegmentInformation(data, start) {
  36020. return {
  36021. width: readUint32(data, start),
  36022. height: readUint32(data, start + 4),
  36023. x: readUint32(data, start + 8),
  36024. y: readUint32(data, start + 12),
  36025. combinationOperator: data[start + 16] & 7
  36026. };
  36027. }
  36028. var RegionSegmentInformationFieldLength = 17;
  36029. function processSegment(segment, visitor) {
  36030. var header = segment.header;
  36031. var data = segment.data, position = segment.start, end = segment.end;
  36032. var args, at, i, atLength;
  36033. switch (header.type) {
  36034. case 0: // SymbolDictionary
  36035. // 7.4.2 Symbol dictionary segment syntax
  36036. var dictionary = {};
  36037. var dictionaryFlags = readUint16(data, position); // 7.4.2.1.1
  36038. dictionary.huffman = !!(dictionaryFlags & 1);
  36039. dictionary.refinement = !!(dictionaryFlags & 2);
  36040. dictionary.huffmanDHSelector = (dictionaryFlags >> 2) & 3;
  36041. dictionary.huffmanDWSelector = (dictionaryFlags >> 4) & 3;
  36042. dictionary.bitmapSizeSelector = (dictionaryFlags >> 6) & 1;
  36043. dictionary.aggregationInstancesSelector = (dictionaryFlags >> 7) & 1;
  36044. dictionary.bitmapCodingContextUsed = !!(dictionaryFlags & 256);
  36045. dictionary.bitmapCodingContextRetained = !!(dictionaryFlags & 512);
  36046. dictionary.template = (dictionaryFlags >> 10) & 3;
  36047. dictionary.refinementTemplate = (dictionaryFlags >> 12) & 1;
  36048. position += 2;
  36049. if (!dictionary.huffman) {
  36050. atLength = dictionary.template === 0 ? 4 : 1;
  36051. at = [];
  36052. for (i = 0; i < atLength; i++) {
  36053. at.push({
  36054. x: readInt8(data, position),
  36055. y: readInt8(data, position + 1)
  36056. });
  36057. position += 2;
  36058. }
  36059. dictionary.at = at;
  36060. }
  36061. if (dictionary.refinement && !dictionary.refinementTemplate) {
  36062. at = [];
  36063. for (i = 0; i < 2; i++) {
  36064. at.push({
  36065. x: readInt8(data, position),
  36066. y: readInt8(data, position + 1)
  36067. });
  36068. position += 2;
  36069. }
  36070. dictionary.refinementAt = at;
  36071. }
  36072. dictionary.numberOfExportedSymbols = readUint32(data, position);
  36073. position += 4;
  36074. dictionary.numberOfNewSymbols = readUint32(data, position);
  36075. position += 4;
  36076. args = [dictionary, header.number, header.referredTo,
  36077. data, position, end];
  36078. break;
  36079. case 6: // ImmediateTextRegion
  36080. case 7: // ImmediateLosslessTextRegion
  36081. var textRegion = {};
  36082. textRegion.info = readRegionSegmentInformation(data, position);
  36083. position += RegionSegmentInformationFieldLength;
  36084. var textRegionSegmentFlags = readUint16(data, position);
  36085. position += 2;
  36086. textRegion.huffman = !!(textRegionSegmentFlags & 1);
  36087. textRegion.refinement = !!(textRegionSegmentFlags & 2);
  36088. textRegion.stripSize = 1 << ((textRegionSegmentFlags >> 2) & 3);
  36089. textRegion.referenceCorner = (textRegionSegmentFlags >> 4) & 3;
  36090. textRegion.transposed = !!(textRegionSegmentFlags & 64);
  36091. textRegion.combinationOperator = (textRegionSegmentFlags >> 7) & 3;
  36092. textRegion.defaultPixelValue = (textRegionSegmentFlags >> 9) & 1;
  36093. textRegion.dsOffset = (textRegionSegmentFlags << 17) >> 27;
  36094. textRegion.refinementTemplate = (textRegionSegmentFlags >> 15) & 1;
  36095. if (textRegion.huffman) {
  36096. var textRegionHuffmanFlags = readUint16(data, position);
  36097. position += 2;
  36098. textRegion.huffmanFS = (textRegionHuffmanFlags) & 3;
  36099. textRegion.huffmanDS = (textRegionHuffmanFlags >> 2) & 3;
  36100. textRegion.huffmanDT = (textRegionHuffmanFlags >> 4) & 3;
  36101. textRegion.huffmanRefinementDW = (textRegionHuffmanFlags >> 6) & 3;
  36102. textRegion.huffmanRefinementDH = (textRegionHuffmanFlags >> 8) & 3;
  36103. textRegion.huffmanRefinementDX = (textRegionHuffmanFlags >> 10) & 3;
  36104. textRegion.huffmanRefinementDY = (textRegionHuffmanFlags >> 12) & 3;
  36105. textRegion.huffmanRefinementSizeSelector =
  36106. !!(textRegionHuffmanFlags & 14);
  36107. }
  36108. if (textRegion.refinement && !textRegion.refinementTemplate) {
  36109. at = [];
  36110. for (i = 0; i < 2; i++) {
  36111. at.push({
  36112. x: readInt8(data, position),
  36113. y: readInt8(data, position + 1)
  36114. });
  36115. position += 2;
  36116. }
  36117. textRegion.refinementAt = at;
  36118. }
  36119. textRegion.numberOfSymbolInstances = readUint32(data, position);
  36120. position += 4;
  36121. // TODO 7.4.3.1.7 Symbol ID Huffman table decoding
  36122. if (textRegion.huffman) {
  36123. error('JBIG2 error: huffman is not supported');
  36124. }
  36125. args = [textRegion, header.referredTo, data, position, end];
  36126. break;
  36127. case 38: // ImmediateGenericRegion
  36128. case 39: // ImmediateLosslessGenericRegion
  36129. var genericRegion = {};
  36130. genericRegion.info = readRegionSegmentInformation(data, position);
  36131. position += RegionSegmentInformationFieldLength;
  36132. var genericRegionSegmentFlags = data[position++];
  36133. genericRegion.mmr = !!(genericRegionSegmentFlags & 1);
  36134. genericRegion.template = (genericRegionSegmentFlags >> 1) & 3;
  36135. genericRegion.prediction = !!(genericRegionSegmentFlags & 8);
  36136. if (!genericRegion.mmr) {
  36137. atLength = genericRegion.template === 0 ? 4 : 1;
  36138. at = [];
  36139. for (i = 0; i < atLength; i++) {
  36140. at.push({
  36141. x: readInt8(data, position),
  36142. y: readInt8(data, position + 1)
  36143. });
  36144. position += 2;
  36145. }
  36146. genericRegion.at = at;
  36147. }
  36148. args = [genericRegion, data, position, end];
  36149. break;
  36150. case 48: // PageInformation
  36151. var pageInfo = {
  36152. width: readUint32(data, position),
  36153. height: readUint32(data, position + 4),
  36154. resolutionX: readUint32(data, position + 8),
  36155. resolutionY: readUint32(data, position + 12)
  36156. };
  36157. if (pageInfo.height === 0xFFFFFFFF) {
  36158. delete pageInfo.height;
  36159. }
  36160. var pageSegmentFlags = data[position + 16];
  36161. var pageStripingInformatiom = readUint16(data, position + 17);
  36162. pageInfo.lossless = !!(pageSegmentFlags & 1);
  36163. pageInfo.refinement = !!(pageSegmentFlags & 2);
  36164. pageInfo.defaultPixelValue = (pageSegmentFlags >> 2) & 1;
  36165. pageInfo.combinationOperator = (pageSegmentFlags >> 3) & 3;
  36166. pageInfo.requiresBuffer = !!(pageSegmentFlags & 32);
  36167. pageInfo.combinationOperatorOverride = !!(pageSegmentFlags & 64);
  36168. args = [pageInfo];
  36169. break;
  36170. case 49: // EndOfPage
  36171. break;
  36172. case 50: // EndOfStripe
  36173. break;
  36174. case 51: // EndOfFile
  36175. break;
  36176. case 62: // 7.4.15 defines 2 extension types which
  36177. // are comments and can be ignored.
  36178. break;
  36179. default:
  36180. error('JBIG2 error: segment type ' + header.typeName + '(' +
  36181. header.type + ') is not implemented');
  36182. }
  36183. var callbackName = 'on' + header.typeName;
  36184. if (callbackName in visitor) {
  36185. visitor[callbackName].apply(visitor, args);
  36186. }
  36187. }
  36188. function processSegments(segments, visitor) {
  36189. for (var i = 0, ii = segments.length; i < ii; i++) {
  36190. processSegment(segments[i], visitor);
  36191. }
  36192. }
  36193. function parseJbig2(data, start, end) {
  36194. var position = start;
  36195. if (data[position] !== 0x97 || data[position + 1] !== 0x4A ||
  36196. data[position + 2] !== 0x42 || data[position + 3] !== 0x32 ||
  36197. data[position + 4] !== 0x0D || data[position + 5] !== 0x0A ||
  36198. data[position + 6] !== 0x1A || data[position + 7] !== 0x0A) {
  36199. error('JBIG2 error: invalid header');
  36200. }
  36201. var header = {};
  36202. position += 8;
  36203. var flags = data[position++];
  36204. header.randomAccess = !(flags & 1);
  36205. if (!(flags & 2)) {
  36206. header.numberOfPages = readUint32(data, position);
  36207. position += 4;
  36208. }
  36209. var segments = readSegments(header, data, position, end);
  36210. error('Not implemented');
  36211. // processSegments(segments, new SimpleSegmentVisitor());
  36212. }
  36213. function parseJbig2Chunks(chunks) {
  36214. var visitor = new SimpleSegmentVisitor();
  36215. for (var i = 0, ii = chunks.length; i < ii; i++) {
  36216. var chunk = chunks[i];
  36217. var segments = readSegments({}, chunk.data, chunk.start, chunk.end);
  36218. processSegments(segments, visitor);
  36219. }
  36220. return visitor.buffer;
  36221. }
  36222. function SimpleSegmentVisitor() {}
  36223. SimpleSegmentVisitor.prototype = {
  36224. onPageInformation: function SimpleSegmentVisitor_onPageInformation(info) {
  36225. this.currentPageInfo = info;
  36226. var rowSize = (info.width + 7) >> 3;
  36227. var buffer = new Uint8Array(rowSize * info.height);
  36228. // The contents of ArrayBuffers are initialized to 0.
  36229. // Fill the buffer with 0xFF only if info.defaultPixelValue is set
  36230. if (info.defaultPixelValue) {
  36231. for (var i = 0, ii = buffer.length; i < ii; i++) {
  36232. buffer[i] = 0xFF;
  36233. }
  36234. }
  36235. this.buffer = buffer;
  36236. },
  36237. drawBitmap: function SimpleSegmentVisitor_drawBitmap(regionInfo, bitmap) {
  36238. var pageInfo = this.currentPageInfo;
  36239. var width = regionInfo.width, height = regionInfo.height;
  36240. var rowSize = (pageInfo.width + 7) >> 3;
  36241. var combinationOperator = pageInfo.combinationOperatorOverride ?
  36242. regionInfo.combinationOperator : pageInfo.combinationOperator;
  36243. var buffer = this.buffer;
  36244. var mask0 = 128 >> (regionInfo.x & 7);
  36245. var offset0 = regionInfo.y * rowSize + (regionInfo.x >> 3);
  36246. var i, j, mask, offset;
  36247. switch (combinationOperator) {
  36248. case 0: // OR
  36249. for (i = 0; i < height; i++) {
  36250. mask = mask0;
  36251. offset = offset0;
  36252. for (j = 0; j < width; j++) {
  36253. if (bitmap[i][j]) {
  36254. buffer[offset] |= mask;
  36255. }
  36256. mask >>= 1;
  36257. if (!mask) {
  36258. mask = 128;
  36259. offset++;
  36260. }
  36261. }
  36262. offset0 += rowSize;
  36263. }
  36264. break;
  36265. case 2: // XOR
  36266. for (i = 0; i < height; i++) {
  36267. mask = mask0;
  36268. offset = offset0;
  36269. for (j = 0; j < width; j++) {
  36270. if (bitmap[i][j]) {
  36271. buffer[offset] ^= mask;
  36272. }
  36273. mask >>= 1;
  36274. if (!mask) {
  36275. mask = 128;
  36276. offset++;
  36277. }
  36278. }
  36279. offset0 += rowSize;
  36280. }
  36281. break;
  36282. default:
  36283. error('JBIG2 error: operator ' + combinationOperator +
  36284. ' is not supported');
  36285. }
  36286. },
  36287. onImmediateGenericRegion:
  36288. function SimpleSegmentVisitor_onImmediateGenericRegion(region, data,
  36289. start, end) {
  36290. var regionInfo = region.info;
  36291. var decodingContext = new DecodingContext(data, start, end);
  36292. var bitmap = decodeBitmap(region.mmr, regionInfo.width, regionInfo.height,
  36293. region.template, region.prediction, null,
  36294. region.at, decodingContext);
  36295. this.drawBitmap(regionInfo, bitmap);
  36296. },
  36297. onImmediateLosslessGenericRegion:
  36298. function SimpleSegmentVisitor_onImmediateLosslessGenericRegion() {
  36299. this.onImmediateGenericRegion.apply(this, arguments);
  36300. },
  36301. onSymbolDictionary:
  36302. function SimpleSegmentVisitor_onSymbolDictionary(dictionary,
  36303. currentSegment,
  36304. referredSegments,
  36305. data, start, end) {
  36306. var huffmanTables;
  36307. if (dictionary.huffman) {
  36308. error('JBIG2 error: huffman is not supported');
  36309. }
  36310. // Combines exported symbols from all referred segments
  36311. var symbols = this.symbols;
  36312. if (!symbols) {
  36313. this.symbols = symbols = {};
  36314. }
  36315. var inputSymbols = [];
  36316. for (var i = 0, ii = referredSegments.length; i < ii; i++) {
  36317. inputSymbols = inputSymbols.concat(symbols[referredSegments[i]]);
  36318. }
  36319. var decodingContext = new DecodingContext(data, start, end);
  36320. symbols[currentSegment] = decodeSymbolDictionary(dictionary.huffman,
  36321. dictionary.refinement, inputSymbols, dictionary.numberOfNewSymbols,
  36322. dictionary.numberOfExportedSymbols, huffmanTables,
  36323. dictionary.template, dictionary.at,
  36324. dictionary.refinementTemplate, dictionary.refinementAt,
  36325. decodingContext);
  36326. },
  36327. onImmediateTextRegion:
  36328. function SimpleSegmentVisitor_onImmediateTextRegion(region,
  36329. referredSegments,
  36330. data, start, end) {
  36331. var regionInfo = region.info;
  36332. var huffmanTables;
  36333. // Combines exported symbols from all referred segments
  36334. var symbols = this.symbols;
  36335. var inputSymbols = [];
  36336. for (var i = 0, ii = referredSegments.length; i < ii; i++) {
  36337. inputSymbols = inputSymbols.concat(symbols[referredSegments[i]]);
  36338. }
  36339. var symbolCodeLength = log2(inputSymbols.length);
  36340. var decodingContext = new DecodingContext(data, start, end);
  36341. var bitmap = decodeTextRegion(region.huffman, region.refinement,
  36342. regionInfo.width, regionInfo.height, region.defaultPixelValue,
  36343. region.numberOfSymbolInstances, region.stripSize, inputSymbols,
  36344. symbolCodeLength, region.transposed, region.dsOffset,
  36345. region.referenceCorner, region.combinationOperator, huffmanTables,
  36346. region.refinementTemplate, region.refinementAt, decodingContext);
  36347. this.drawBitmap(regionInfo, bitmap);
  36348. },
  36349. onImmediateLosslessTextRegion:
  36350. function SimpleSegmentVisitor_onImmediateLosslessTextRegion() {
  36351. this.onImmediateTextRegion.apply(this, arguments);
  36352. }
  36353. };
  36354. function Jbig2Image() {}
  36355. Jbig2Image.prototype = {
  36356. parseChunks: function Jbig2Image_parseChunks(chunks) {
  36357. return parseJbig2Chunks(chunks);
  36358. }
  36359. };
  36360. return Jbig2Image;
  36361. })();
  36362. var bidi = PDFJS.bidi = (function bidiClosure() {
  36363. // Character types for symbols from 0000 to 00FF.
  36364. var baseTypes = [
  36365. 'BN', 'BN', 'BN', 'BN', 'BN', 'BN', 'BN', 'BN', 'BN', 'S', 'B', 'S', 'WS',
  36366. 'B', 'BN', 'BN', 'BN', 'BN', 'BN', 'BN', 'BN', 'BN', 'BN', 'BN', 'BN', 'BN',
  36367. 'BN', 'BN', 'B', 'B', 'B', 'S', 'WS', 'ON', 'ON', 'ET', 'ET', 'ET', 'ON',
  36368. 'ON', 'ON', 'ON', 'ON', 'ON', 'CS', 'ON', 'CS', 'ON', 'EN', 'EN', 'EN',
  36369. 'EN', 'EN', 'EN', 'EN', 'EN', 'EN', 'EN', 'ON', 'ON', 'ON', 'ON', 'ON',
  36370. 'ON', 'ON', 'L', 'L', 'L', 'L', 'L', 'L', 'L', 'L', 'L', 'L', 'L', 'L', 'L',
  36371. 'L', 'L', 'L', 'L', 'L', 'L', 'L', 'L', 'L', 'L', 'L', 'L', 'L', 'ON', 'ON',
  36372. 'ON', 'ON', 'ON', 'ON', 'L', 'L', 'L', 'L', 'L', 'L', 'L', 'L', 'L', 'L',
  36373. 'L', 'L', 'L', 'L', 'L', 'L', 'L', 'L', 'L', 'L', 'L', 'L', 'L', 'L', 'L',
  36374. 'L', 'ON', 'ON', 'ON', 'ON', 'BN', 'BN', 'BN', 'BN', 'BN', 'BN', 'B', 'BN',
  36375. 'BN', 'BN', 'BN', 'BN', 'BN', 'BN', 'BN', 'BN', 'BN', 'BN', 'BN', 'BN',
  36376. 'BN', 'BN', 'BN', 'BN', 'BN', 'BN', 'BN', 'BN', 'BN', 'BN', 'BN', 'BN',
  36377. 'BN', 'CS', 'ON', 'ET', 'ET', 'ET', 'ET', 'ON', 'ON', 'ON', 'ON', 'L', 'ON',
  36378. 'ON', 'ON', 'ON', 'ON', 'ET', 'ET', 'EN', 'EN', 'ON', 'L', 'ON', 'ON', 'ON',
  36379. 'EN', 'L', 'ON', 'ON', 'ON', 'ON', 'ON', 'L', 'L', 'L', 'L', 'L', 'L', 'L',
  36380. 'L', 'L', 'L', 'L', 'L', 'L', 'L', 'L', 'L', 'L', 'L', 'L', 'L', 'L', 'L',
  36381. 'L', 'ON', 'L', 'L', 'L', 'L', 'L', 'L', 'L', 'L', 'L', 'L', 'L', 'L', 'L',
  36382. 'L', 'L', 'L', 'L', 'L', 'L', 'L', 'L', 'L', 'L', 'L', 'L', 'L', 'L', 'L',
  36383. 'L', 'L', 'L', 'ON', 'L', 'L', 'L', 'L', 'L', 'L', 'L', 'L'
  36384. ];
  36385. // Character types for symbols from 0600 to 06FF
  36386. var arabicTypes = [
  36387. 'AL', 'AL', 'AL', 'AL', 'AL', 'AL', 'AL', 'AL', 'AL', 'AL', 'AL', 'AL',
  36388. 'CS', 'AL', 'ON', 'ON', 'NSM', 'NSM', 'NSM', 'NSM', 'NSM', 'NSM', 'AL',
  36389. 'AL', 'AL', 'AL', 'AL', 'AL', 'AL', 'AL', 'AL', 'AL', 'AL', 'AL', 'AL',
  36390. 'AL', 'AL', 'AL', 'AL', 'AL', 'AL', 'AL', 'AL', 'AL', 'AL', 'AL', 'AL',
  36391. 'AL', 'AL', 'AL', 'AL', 'AL', 'AL', 'AL', 'AL', 'AL', 'AL', 'AL', 'AL',
  36392. 'AL', 'AL', 'AL', 'AL', 'AL', 'AL', 'AL', 'AL', 'AL', 'AL', 'AL', 'AL',
  36393. 'AL', 'AL', 'AL', 'AL', 'NSM', 'NSM', 'NSM', 'NSM', 'NSM', 'NSM', 'NSM',
  36394. 'NSM', 'NSM', 'NSM', 'NSM', 'NSM', 'NSM', 'NSM', 'AL', 'AL', 'AL', 'AL',
  36395. 'AL', 'AL', 'AL', 'AN', 'AN', 'AN', 'AN', 'AN', 'AN', 'AN', 'AN', 'AN',
  36396. 'AN', 'ET', 'AN', 'AN', 'AL', 'AL', 'AL', 'NSM', 'AL', 'AL', 'AL', 'AL',
  36397. 'AL', 'AL', 'AL', 'AL', 'AL', 'AL', 'AL', 'AL', 'AL', 'AL', 'AL', 'AL',
  36398. 'AL', 'AL', 'AL', 'AL', 'AL', 'AL', 'AL', 'AL', 'AL', 'AL', 'AL', 'AL',
  36399. 'AL', 'AL', 'AL', 'AL', 'AL', 'AL', 'AL', 'AL', 'AL', 'AL', 'AL', 'AL',
  36400. 'AL', 'AL', 'AL', 'AL', 'AL', 'AL', 'AL', 'AL', 'AL', 'AL', 'AL', 'AL',
  36401. 'AL', 'AL', 'AL', 'AL', 'AL', 'AL', 'AL', 'AL', 'AL', 'AL', 'AL', 'AL',
  36402. 'AL', 'AL', 'AL', 'AL', 'AL', 'AL', 'AL', 'AL', 'AL', 'AL', 'AL', 'AL',
  36403. 'AL', 'AL', 'AL', 'AL', 'AL', 'AL', 'AL', 'AL', 'AL', 'AL', 'AL', 'AL',
  36404. 'AL', 'AL', 'AL', 'AL', 'AL', 'AL', 'AL', 'AL', 'AL', 'AL', 'AL', 'AL',
  36405. 'AL', 'NSM', 'NSM', 'NSM', 'NSM', 'NSM', 'NSM', 'NSM', 'NSM', 'NSM', 'NSM',
  36406. 'NSM', 'NSM', 'NSM', 'NSM', 'NSM', 'NSM', 'NSM', 'NSM', 'NSM', 'ON', 'NSM',
  36407. 'NSM', 'NSM', 'NSM', 'AL', 'AL', 'AL', 'AL', 'AL', 'AL', 'AL', 'AL', 'AL',
  36408. 'AL', 'AL', 'AL', 'AL', 'AL', 'AL', 'AL', 'AL', 'AL'
  36409. ];
  36410. function isOdd(i) {
  36411. return (i & 1) !== 0;
  36412. }
  36413. function isEven(i) {
  36414. return (i & 1) === 0;
  36415. }
  36416. function findUnequal(arr, start, value) {
  36417. for (var j = start, jj = arr.length; j < jj; ++j) {
  36418. if (arr[j] !== value) {
  36419. return j;
  36420. }
  36421. }
  36422. return j;
  36423. }
  36424. function setValues(arr, start, end, value) {
  36425. for (var j = start; j < end; ++j) {
  36426. arr[j] = value;
  36427. }
  36428. }
  36429. function reverseValues(arr, start, end) {
  36430. for (var i = start, j = end - 1; i < j; ++i, --j) {
  36431. var temp = arr[i];
  36432. arr[i] = arr[j];
  36433. arr[j] = temp;
  36434. }
  36435. }
  36436. function createBidiText(str, isLTR, vertical) {
  36437. return {
  36438. str: str,
  36439. dir: (vertical ? 'ttb' : (isLTR ? 'ltr' : 'rtl'))
  36440. };
  36441. }
  36442. // These are used in bidi(), which is called frequently. We re-use them on
  36443. // each call to avoid unnecessary allocations.
  36444. var chars = [];
  36445. var types = [];
  36446. function bidi(str, startLevel, vertical) {
  36447. var isLTR = true;
  36448. var strLength = str.length;
  36449. if (strLength === 0 || vertical) {
  36450. return createBidiText(str, isLTR, vertical);
  36451. }
  36452. // Get types and fill arrays
  36453. chars.length = strLength;
  36454. types.length = strLength;
  36455. var numBidi = 0;
  36456. var i, ii;
  36457. for (i = 0; i < strLength; ++i) {
  36458. chars[i] = str.charAt(i);
  36459. var charCode = str.charCodeAt(i);
  36460. var charType = 'L';
  36461. if (charCode <= 0x00ff) {
  36462. charType = baseTypes[charCode];
  36463. } else if (0x0590 <= charCode && charCode <= 0x05f4) {
  36464. charType = 'R';
  36465. } else if (0x0600 <= charCode && charCode <= 0x06ff) {
  36466. charType = arabicTypes[charCode & 0xff];
  36467. } else if (0x0700 <= charCode && charCode <= 0x08AC) {
  36468. charType = 'AL';
  36469. }
  36470. if (charType === 'R' || charType === 'AL' || charType === 'AN') {
  36471. numBidi++;
  36472. }
  36473. types[i] = charType;
  36474. }
  36475. // Detect the bidi method
  36476. // - If there are no rtl characters then no bidi needed
  36477. // - If less than 30% chars are rtl then string is primarily ltr
  36478. // - If more than 30% chars are rtl then string is primarily rtl
  36479. if (numBidi === 0) {
  36480. isLTR = true;
  36481. return createBidiText(str, isLTR);
  36482. }
  36483. if (startLevel === -1) {
  36484. if ((strLength / numBidi) < 0.3) {
  36485. isLTR = true;
  36486. startLevel = 0;
  36487. } else {
  36488. isLTR = false;
  36489. startLevel = 1;
  36490. }
  36491. }
  36492. var levels = [];
  36493. for (i = 0; i < strLength; ++i) {
  36494. levels[i] = startLevel;
  36495. }
  36496. /*
  36497. X1-X10: skip most of this, since we are NOT doing the embeddings.
  36498. */
  36499. var e = (isOdd(startLevel) ? 'R' : 'L');
  36500. var sor = e;
  36501. var eor = sor;
  36502. /*
  36503. W1. Examine each non-spacing mark (NSM) in the level run, and change the
  36504. type of the NSM to the type of the previous character. If the NSM is at the
  36505. start of the level run, it will get the type of sor.
  36506. */
  36507. var lastType = sor;
  36508. for (i = 0; i < strLength; ++i) {
  36509. if (types[i] === 'NSM') {
  36510. types[i] = lastType;
  36511. } else {
  36512. lastType = types[i];
  36513. }
  36514. }
  36515. /*
  36516. W2. Search backwards from each instance of a European number until the
  36517. first strong type (R, L, AL, or sor) is found. If an AL is found, change
  36518. the type of the European number to Arabic number.
  36519. */
  36520. lastType = sor;
  36521. var t;
  36522. for (i = 0; i < strLength; ++i) {
  36523. t = types[i];
  36524. if (t === 'EN') {
  36525. types[i] = (lastType === 'AL') ? 'AN' : 'EN';
  36526. } else if (t === 'R' || t === 'L' || t === 'AL') {
  36527. lastType = t;
  36528. }
  36529. }
  36530. /*
  36531. W3. Change all ALs to R.
  36532. */
  36533. for (i = 0; i < strLength; ++i) {
  36534. t = types[i];
  36535. if (t === 'AL') {
  36536. types[i] = 'R';
  36537. }
  36538. }
  36539. /*
  36540. W4. A single European separator between two European numbers changes to a
  36541. European number. A single common separator between two numbers of the same
  36542. type changes to that type:
  36543. */
  36544. for (i = 1; i < strLength - 1; ++i) {
  36545. if (types[i] === 'ES' && types[i - 1] === 'EN' && types[i + 1] === 'EN') {
  36546. types[i] = 'EN';
  36547. }
  36548. if (types[i] === 'CS' &&
  36549. (types[i - 1] === 'EN' || types[i - 1] === 'AN') &&
  36550. types[i + 1] === types[i - 1]) {
  36551. types[i] = types[i - 1];
  36552. }
  36553. }
  36554. /*
  36555. W5. A sequence of European terminators adjacent to European numbers changes
  36556. to all European numbers:
  36557. */
  36558. for (i = 0; i < strLength; ++i) {
  36559. if (types[i] === 'EN') {
  36560. // do before
  36561. var j;
  36562. for (j = i - 1; j >= 0; --j) {
  36563. if (types[j] !== 'ET') {
  36564. break;
  36565. }
  36566. types[j] = 'EN';
  36567. }
  36568. // do after
  36569. for (j = i + 1; j < strLength; --j) {
  36570. if (types[j] !== 'ET') {
  36571. break;
  36572. }
  36573. types[j] = 'EN';
  36574. }
  36575. }
  36576. }
  36577. /*
  36578. W6. Otherwise, separators and terminators change to Other Neutral:
  36579. */
  36580. for (i = 0; i < strLength; ++i) {
  36581. t = types[i];
  36582. if (t === 'WS' || t === 'ES' || t === 'ET' || t === 'CS') {
  36583. types[i] = 'ON';
  36584. }
  36585. }
  36586. /*
  36587. W7. Search backwards from each instance of a European number until the
  36588. first strong type (R, L, or sor) is found. If an L is found, then change
  36589. the type of the European number to L.
  36590. */
  36591. lastType = sor;
  36592. for (i = 0; i < strLength; ++i) {
  36593. t = types[i];
  36594. if (t === 'EN') {
  36595. types[i] = ((lastType === 'L') ? 'L' : 'EN');
  36596. } else if (t === 'R' || t === 'L') {
  36597. lastType = t;
  36598. }
  36599. }
  36600. /*
  36601. N1. A sequence of neutrals takes the direction of the surrounding strong
  36602. text if the text on both sides has the same direction. European and Arabic
  36603. numbers are treated as though they were R. Start-of-level-run (sor) and
  36604. end-of-level-run (eor) are used at level run boundaries.
  36605. */
  36606. for (i = 0; i < strLength; ++i) {
  36607. if (types[i] === 'ON') {
  36608. var end = findUnequal(types, i + 1, 'ON');
  36609. var before = sor;
  36610. if (i > 0) {
  36611. before = types[i - 1];
  36612. }
  36613. var after = eor;
  36614. if (end + 1 < strLength) {
  36615. after = types[end + 1];
  36616. }
  36617. if (before !== 'L') {
  36618. before = 'R';
  36619. }
  36620. if (after !== 'L') {
  36621. after = 'R';
  36622. }
  36623. if (before === after) {
  36624. setValues(types, i, end, before);
  36625. }
  36626. i = end - 1; // reset to end (-1 so next iteration is ok)
  36627. }
  36628. }
  36629. /*
  36630. N2. Any remaining neutrals take the embedding direction.
  36631. */
  36632. for (i = 0; i < strLength; ++i) {
  36633. if (types[i] === 'ON') {
  36634. types[i] = e;
  36635. }
  36636. }
  36637. /*
  36638. I1. For all characters with an even (left-to-right) embedding direction,
  36639. those of type R go up one level and those of type AN or EN go up two
  36640. levels.
  36641. I2. For all characters with an odd (right-to-left) embedding direction,
  36642. those of type L, EN or AN go up one level.
  36643. */
  36644. for (i = 0; i < strLength; ++i) {
  36645. t = types[i];
  36646. if (isEven(levels[i])) {
  36647. if (t === 'R') {
  36648. levels[i] += 1;
  36649. } else if (t === 'AN' || t === 'EN') {
  36650. levels[i] += 2;
  36651. }
  36652. } else { // isOdd
  36653. if (t === 'L' || t === 'AN' || t === 'EN') {
  36654. levels[i] += 1;
  36655. }
  36656. }
  36657. }
  36658. /*
  36659. L1. On each line, reset the embedding level of the following characters to
  36660. the paragraph embedding level:
  36661. segment separators,
  36662. paragraph separators,
  36663. any sequence of whitespace characters preceding a segment separator or
  36664. paragraph separator, and any sequence of white space characters at the end
  36665. of the line.
  36666. */
  36667. // don't bother as text is only single line
  36668. /*
  36669. L2. From the highest level found in the text to the lowest odd level on
  36670. each line, reverse any contiguous sequence of characters that are at that
  36671. level or higher.
  36672. */
  36673. // find highest level & lowest odd level
  36674. var highestLevel = -1;
  36675. var lowestOddLevel = 99;
  36676. var level;
  36677. for (i = 0, ii = levels.length; i < ii; ++i) {
  36678. level = levels[i];
  36679. if (highestLevel < level) {
  36680. highestLevel = level;
  36681. }
  36682. if (lowestOddLevel > level && isOdd(level)) {
  36683. lowestOddLevel = level;
  36684. }
  36685. }
  36686. // now reverse between those limits
  36687. for (level = highestLevel; level >= lowestOddLevel; --level) {
  36688. // find segments to reverse
  36689. var start = -1;
  36690. for (i = 0, ii = levels.length; i < ii; ++i) {
  36691. if (levels[i] < level) {
  36692. if (start >= 0) {
  36693. reverseValues(chars, start, i);
  36694. start = -1;
  36695. }
  36696. } else if (start < 0) {
  36697. start = i;
  36698. }
  36699. }
  36700. if (start >= 0) {
  36701. reverseValues(chars, start, levels.length);
  36702. }
  36703. }
  36704. /*
  36705. L3. Combining marks applied to a right-to-left base character will at this
  36706. point precede their base character. If the rendering engine expects them to
  36707. follow the base characters in the final display process, then the ordering
  36708. of the marks and the base character must be reversed.
  36709. */
  36710. // don't bother for now
  36711. /*
  36712. L4. A character that possesses the mirrored property as specified by
  36713. Section 4.7, Mirrored, must be depicted by a mirrored glyph if the resolved
  36714. directionality of that character is R.
  36715. */
  36716. // don't mirror as characters are already mirrored in the pdf
  36717. // Finally, return string
  36718. var result = '';
  36719. for (i = 0, ii = chars.length; i < ii; ++i) {
  36720. var ch = chars[i];
  36721. if (ch !== '<' && ch !== '>') {
  36722. result += ch;
  36723. }
  36724. }
  36725. return createBidiText(result, isLTR);
  36726. }
  36727. return bidi;
  36728. })();
  36729. /* -*- Mode: Java; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
  36730. /* vim: set shiftwidth=2 tabstop=2 autoindent cindent expandtab: */
  36731. /* Copyright 2014 Opera Software ASA
  36732. *
  36733. * Licensed under the Apache License, Version 2.0 (the "License");
  36734. * you may not use this file except in compliance with the License.
  36735. * You may obtain a copy of the License at
  36736. *
  36737. * http://www.apache.org/licenses/LICENSE-2.0
  36738. *
  36739. * Unless required by applicable law or agreed to in writing, software
  36740. * distributed under the License is distributed on an "AS IS" BASIS,
  36741. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  36742. * See the License for the specific language governing permissions and
  36743. * limitations under the License.
  36744. *
  36745. *
  36746. * Based on https://code.google.com/p/smhasher/wiki/MurmurHash3.
  36747. * Hashes roughly 100 KB per millisecond on i7 3.4 GHz.
  36748. */
  36749. /* globals Uint32ArrayView */
  36750. 'use strict';
  36751. var MurmurHash3_64 = (function MurmurHash3_64Closure (seed) {
  36752. // Workaround for missing math precison in JS.
  36753. var MASK_HIGH = 0xffff0000;
  36754. var MASK_LOW = 0xffff;
  36755. function MurmurHash3_64 (seed) {
  36756. var SEED = 0xc3d2e1f0;
  36757. this.h1 = seed ? seed & 0xffffffff : SEED;
  36758. this.h2 = seed ? seed & 0xffffffff : SEED;
  36759. }
  36760. var alwaysUseUint32ArrayView = false;
  36761. //#if !(FIREFOX || MOZCENTRAL || B2G || CHROME)
  36762. // old webkits have issues with non-aligned arrays
  36763. try {
  36764. new Uint32Array(new Uint8Array(5).buffer, 0, 1);
  36765. } catch (e) {
  36766. alwaysUseUint32ArrayView = true;
  36767. }
  36768. //#endif
  36769. MurmurHash3_64.prototype = {
  36770. update: function MurmurHash3_64_update(input) {
  36771. var useUint32ArrayView = alwaysUseUint32ArrayView;
  36772. var i;
  36773. if (typeof input === 'string') {
  36774. var data = new Uint8Array(input.length * 2);
  36775. var length = 0;
  36776. for (i = 0; i < input.length; i++) {
  36777. var code = input.charCodeAt(i);
  36778. if (code <= 0xff) {
  36779. data[length++] = code;
  36780. }
  36781. else {
  36782. data[length++] = code >>> 8;
  36783. data[length++] = code & 0xff;
  36784. }
  36785. }
  36786. } else if (input instanceof Uint8Array) {
  36787. data = input;
  36788. length = data.length;
  36789. } else if (typeof input === 'object' && ('length' in input)) {
  36790. // processing regular arrays as well, e.g. for IE9
  36791. data = input;
  36792. length = data.length;
  36793. useUint32ArrayView = true;
  36794. } else {
  36795. throw new Error('Wrong data format in MurmurHash3_64_update. ' +
  36796. 'Input must be a string or array.');
  36797. }
  36798. var blockCounts = length >> 2;
  36799. var tailLength = length - blockCounts * 4;
  36800. // we don't care about endianness here
  36801. var dataUint32 = useUint32ArrayView ?
  36802. new Uint32ArrayView(data, blockCounts) :
  36803. new Uint32Array(data.buffer, 0, blockCounts);
  36804. var k1 = 0;
  36805. var k2 = 0;
  36806. var h1 = this.h1;
  36807. var h2 = this.h2;
  36808. var C1 = 0xcc9e2d51;
  36809. var C2 = 0x1b873593;
  36810. var C1_LOW = C1 & MASK_LOW;
  36811. var C2_LOW = C2 & MASK_LOW;
  36812. for (i = 0; i < blockCounts; i++) {
  36813. if (i & 1) {
  36814. k1 = dataUint32[i];
  36815. k1 = (k1 * C1 & MASK_HIGH) | (k1 * C1_LOW & MASK_LOW);
  36816. k1 = k1 << 15 | k1 >>> 17;
  36817. k1 = (k1 * C2 & MASK_HIGH) | (k1 * C2_LOW & MASK_LOW);
  36818. h1 ^= k1;
  36819. h1 = h1 << 13 | h1 >>> 19;
  36820. h1 = h1 * 5 + 0xe6546b64;
  36821. } else {
  36822. k2 = dataUint32[i];
  36823. k2 = (k2 * C1 & MASK_HIGH) | (k2 * C1_LOW & MASK_LOW);
  36824. k2 = k2 << 15 | k2 >>> 17;
  36825. k2 = (k2 * C2 & MASK_HIGH) | (k2 * C2_LOW & MASK_LOW);
  36826. h2 ^= k2;
  36827. h2 = h2 << 13 | h2 >>> 19;
  36828. h2 = h2 * 5 + 0xe6546b64;
  36829. }
  36830. }
  36831. k1 = 0;
  36832. switch (tailLength) {
  36833. case 3:
  36834. k1 ^= data[blockCounts * 4 + 2] << 16;
  36835. /* falls through */
  36836. case 2:
  36837. k1 ^= data[blockCounts * 4 + 1] << 8;
  36838. /* falls through */
  36839. case 1:
  36840. k1 ^= data[blockCounts * 4];
  36841. /* falls through */
  36842. k1 = (k1 * C1 & MASK_HIGH) | (k1 * C1_LOW & MASK_LOW);
  36843. k1 = k1 << 15 | k1 >>> 17;
  36844. k1 = (k1 * C2 & MASK_HIGH) | (k1 * C2_LOW & MASK_LOW);
  36845. if (blockCounts & 1) {
  36846. h1 ^= k1;
  36847. } else {
  36848. h2 ^= k1;
  36849. }
  36850. }
  36851. this.h1 = h1;
  36852. this.h2 = h2;
  36853. return this;
  36854. },
  36855. hexdigest: function MurmurHash3_64_hexdigest () {
  36856. var h1 = this.h1;
  36857. var h2 = this.h2;
  36858. h1 ^= h2 >>> 1;
  36859. h1 = (h1 * 0xed558ccd & MASK_HIGH) | (h1 * 0x8ccd & MASK_LOW);
  36860. h2 = (h2 * 0xff51afd7 & MASK_HIGH) |
  36861. (((h2 << 16 | h1 >>> 16) * 0xafd7ed55 & MASK_HIGH) >>> 16);
  36862. h1 ^= h2 >>> 1;
  36863. h1 = (h1 * 0x1a85ec53 & MASK_HIGH) | (h1 * 0xec53 & MASK_LOW);
  36864. h2 = (h2 * 0xc4ceb9fe & MASK_HIGH) |
  36865. (((h2 << 16 | h1 >>> 16) * 0xb9fe1a85 & MASK_HIGH) >>> 16);
  36866. h1 ^= h2 >>> 1;
  36867. for (var i = 0, arr = [h1, h2], str = ''; i < arr.length; i++) {
  36868. var hex = (arr[i] >>> 0).toString(16);
  36869. while (hex.length < 8) {
  36870. hex = '0' + hex;
  36871. }
  36872. str += hex;
  36873. }
  36874. return str;
  36875. }
  36876. };
  36877. return MurmurHash3_64;
  36878. })();
  36879. }).call((typeof window === 'undefined') ? this : window);
  36880. if (!PDFJS.workerSrc && typeof document !== 'undefined') {
  36881. // workerSrc is not set -- using last script url to define default location
  36882. PDFJS.workerSrc = (function () {
  36883. 'use strict';
  36884. var scriptTagContainer = document.body ||
  36885. document.getElementsByTagName('head')[0];
  36886. var pdfjsSrc = scriptTagContainer.lastChild.src;
  36887. return pdfjsSrc && pdfjsSrc.replace(/\.js$/i, '.worker.js');
  36888. })();
  36889. }