function.js 35 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149
  1. /**
  2. * @licstart The following is the entire license notice for the
  3. * Javascript code in this page
  4. *
  5. * Copyright 2017 Mozilla Foundation
  6. *
  7. * Licensed under the Apache License, Version 2.0 (the "License");
  8. * you may not use this file except in compliance with the License.
  9. * You may obtain a copy of the License at
  10. *
  11. * http://www.apache.org/licenses/LICENSE-2.0
  12. *
  13. * Unless required by applicable law or agreed to in writing, software
  14. * distributed under the License is distributed on an "AS IS" BASIS,
  15. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  16. * See the License for the specific language governing permissions and
  17. * limitations under the License.
  18. *
  19. * @licend The above is the entire license notice for the
  20. * Javascript code in this page
  21. */
  22. 'use strict';
  23. Object.defineProperty(exports, "__esModule", {
  24. value: true
  25. });
  26. exports.PostScriptCompiler = exports.PostScriptEvaluator = exports.PDFFunctionFactory = exports.isPDFFunction = undefined;
  27. var _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) { return typeof obj; } : function (obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; };
  28. var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();
  29. var _util = require('../shared/util');
  30. var _primitives = require('./primitives');
  31. var _ps_parser = require('./ps_parser');
  32. function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
  33. var IsEvalSupportedCached = {
  34. get value() {
  35. return (0, _util.shadow)(this, 'value', (0, _util.isEvalSupported)());
  36. }
  37. };
  38. var PDFFunctionFactory = function () {
  39. function PDFFunctionFactory(_ref) {
  40. var xref = _ref.xref,
  41. _ref$isEvalSupported = _ref.isEvalSupported,
  42. isEvalSupported = _ref$isEvalSupported === undefined ? true : _ref$isEvalSupported;
  43. _classCallCheck(this, PDFFunctionFactory);
  44. this.xref = xref;
  45. this.isEvalSupported = isEvalSupported !== false;
  46. }
  47. _createClass(PDFFunctionFactory, [{
  48. key: 'create',
  49. value: function create(fn) {
  50. return PDFFunction.parse({
  51. xref: this.xref,
  52. isEvalSupported: this.isEvalSupported,
  53. fn: fn
  54. });
  55. }
  56. }, {
  57. key: 'createFromArray',
  58. value: function createFromArray(fnObj) {
  59. return PDFFunction.parseArray({
  60. xref: this.xref,
  61. isEvalSupported: this.isEvalSupported,
  62. fnObj: fnObj
  63. });
  64. }
  65. }, {
  66. key: 'createFromIR',
  67. value: function createFromIR(IR) {
  68. return PDFFunction.fromIR({
  69. xref: this.xref,
  70. isEvalSupported: this.isEvalSupported,
  71. IR: IR
  72. });
  73. }
  74. }, {
  75. key: 'createIR',
  76. value: function createIR(fn) {
  77. return PDFFunction.getIR({
  78. xref: this.xref,
  79. isEvalSupported: this.isEvalSupported,
  80. fn: fn
  81. });
  82. }
  83. }]);
  84. return PDFFunctionFactory;
  85. }();
  86. var PDFFunction = function PDFFunctionClosure() {
  87. var CONSTRUCT_SAMPLED = 0;
  88. var CONSTRUCT_INTERPOLATED = 2;
  89. var CONSTRUCT_STICHED = 3;
  90. var CONSTRUCT_POSTSCRIPT = 4;
  91. return {
  92. getSampleArray: function getSampleArray(size, outputSize, bps, stream) {
  93. var i, ii;
  94. var length = 1;
  95. for (i = 0, ii = size.length; i < ii; i++) {
  96. length *= size[i];
  97. }
  98. length *= outputSize;
  99. var array = new Array(length);
  100. var codeSize = 0;
  101. var codeBuf = 0;
  102. var sampleMul = 1.0 / (Math.pow(2.0, bps) - 1);
  103. var strBytes = stream.getBytes((length * bps + 7) / 8);
  104. var strIdx = 0;
  105. for (i = 0; i < length; i++) {
  106. while (codeSize < bps) {
  107. codeBuf <<= 8;
  108. codeBuf |= strBytes[strIdx++];
  109. codeSize += 8;
  110. }
  111. codeSize -= bps;
  112. array[i] = (codeBuf >> codeSize) * sampleMul;
  113. codeBuf &= (1 << codeSize) - 1;
  114. }
  115. return array;
  116. },
  117. getIR: function getIR(_ref2) {
  118. var xref = _ref2.xref,
  119. isEvalSupported = _ref2.isEvalSupported,
  120. fn = _ref2.fn;
  121. var dict = fn.dict;
  122. if (!dict) {
  123. dict = fn;
  124. }
  125. var types = [this.constructSampled, null, this.constructInterpolated, this.constructStiched, this.constructPostScript];
  126. var typeNum = dict.get('FunctionType');
  127. var typeFn = types[typeNum];
  128. if (!typeFn) {
  129. throw new _util.FormatError('Unknown type of function');
  130. }
  131. return typeFn.call(this, {
  132. xref: xref,
  133. isEvalSupported: isEvalSupported,
  134. fn: fn,
  135. dict: dict
  136. });
  137. },
  138. fromIR: function fromIR(_ref3) {
  139. var xref = _ref3.xref,
  140. isEvalSupported = _ref3.isEvalSupported,
  141. IR = _ref3.IR;
  142. var type = IR[0];
  143. switch (type) {
  144. case CONSTRUCT_SAMPLED:
  145. return this.constructSampledFromIR({
  146. xref: xref,
  147. isEvalSupported: isEvalSupported,
  148. IR: IR
  149. });
  150. case CONSTRUCT_INTERPOLATED:
  151. return this.constructInterpolatedFromIR({
  152. xref: xref,
  153. isEvalSupported: isEvalSupported,
  154. IR: IR
  155. });
  156. case CONSTRUCT_STICHED:
  157. return this.constructStichedFromIR({
  158. xref: xref,
  159. isEvalSupported: isEvalSupported,
  160. IR: IR
  161. });
  162. default:
  163. return this.constructPostScriptFromIR({
  164. xref: xref,
  165. isEvalSupported: isEvalSupported,
  166. IR: IR
  167. });
  168. }
  169. },
  170. parse: function parse(_ref4) {
  171. var xref = _ref4.xref,
  172. isEvalSupported = _ref4.isEvalSupported,
  173. fn = _ref4.fn;
  174. var IR = this.getIR({
  175. xref: xref,
  176. isEvalSupported: isEvalSupported,
  177. fn: fn
  178. });
  179. return this.fromIR({
  180. xref: xref,
  181. isEvalSupported: isEvalSupported,
  182. IR: IR
  183. });
  184. },
  185. parseArray: function parseArray(_ref5) {
  186. var xref = _ref5.xref,
  187. isEvalSupported = _ref5.isEvalSupported,
  188. fnObj = _ref5.fnObj;
  189. if (!Array.isArray(fnObj)) {
  190. return this.parse({
  191. xref: xref,
  192. isEvalSupported: isEvalSupported,
  193. fn: fnObj
  194. });
  195. }
  196. var fnArray = [];
  197. for (var j = 0, jj = fnObj.length; j < jj; j++) {
  198. fnArray.push(this.parse({
  199. xref: xref,
  200. isEvalSupported: isEvalSupported,
  201. fn: xref.fetchIfRef(fnObj[j])
  202. }));
  203. }
  204. return function (src, srcOffset, dest, destOffset) {
  205. for (var i = 0, ii = fnArray.length; i < ii; i++) {
  206. fnArray[i](src, srcOffset, dest, destOffset + i);
  207. }
  208. };
  209. },
  210. constructSampled: function constructSampled(_ref6) {
  211. var xref = _ref6.xref,
  212. isEvalSupported = _ref6.isEvalSupported,
  213. fn = _ref6.fn,
  214. dict = _ref6.dict;
  215. function toMultiArray(arr) {
  216. var inputLength = arr.length;
  217. var out = [];
  218. var index = 0;
  219. for (var i = 0; i < inputLength; i += 2) {
  220. out[index] = [arr[i], arr[i + 1]];
  221. ++index;
  222. }
  223. return out;
  224. }
  225. var domain = dict.getArray('Domain');
  226. var range = dict.getArray('Range');
  227. if (!domain || !range) {
  228. throw new _util.FormatError('No domain or range');
  229. }
  230. var inputSize = domain.length / 2;
  231. var outputSize = range.length / 2;
  232. domain = toMultiArray(domain);
  233. range = toMultiArray(range);
  234. var size = dict.get('Size');
  235. var bps = dict.get('BitsPerSample');
  236. var order = dict.get('Order') || 1;
  237. if (order !== 1) {
  238. (0, _util.info)('No support for cubic spline interpolation: ' + order);
  239. }
  240. var encode = dict.getArray('Encode');
  241. if (!encode) {
  242. encode = [];
  243. for (var i = 0; i < inputSize; ++i) {
  244. encode.push(0);
  245. encode.push(size[i] - 1);
  246. }
  247. }
  248. encode = toMultiArray(encode);
  249. var decode = dict.getArray('Decode');
  250. if (!decode) {
  251. decode = range;
  252. } else {
  253. decode = toMultiArray(decode);
  254. }
  255. var samples = this.getSampleArray(size, outputSize, bps, fn);
  256. return [CONSTRUCT_SAMPLED, inputSize, domain, encode, decode, samples, size, outputSize, Math.pow(2, bps) - 1, range];
  257. },
  258. constructSampledFromIR: function constructSampledFromIR(_ref7) {
  259. var xref = _ref7.xref,
  260. isEvalSupported = _ref7.isEvalSupported,
  261. IR = _ref7.IR;
  262. function interpolate(x, xmin, xmax, ymin, ymax) {
  263. return ymin + (x - xmin) * ((ymax - ymin) / (xmax - xmin));
  264. }
  265. return function constructSampledFromIRResult(src, srcOffset, dest, destOffset) {
  266. var m = IR[1];
  267. var domain = IR[2];
  268. var encode = IR[3];
  269. var decode = IR[4];
  270. var samples = IR[5];
  271. var size = IR[6];
  272. var n = IR[7];
  273. var range = IR[9];
  274. var cubeVertices = 1 << m;
  275. var cubeN = new Float64Array(cubeVertices);
  276. var cubeVertex = new Uint32Array(cubeVertices);
  277. var i, j;
  278. for (j = 0; j < cubeVertices; j++) {
  279. cubeN[j] = 1;
  280. }
  281. var k = n,
  282. pos = 1;
  283. for (i = 0; i < m; ++i) {
  284. var domain_2i = domain[i][0];
  285. var domain_2i_1 = domain[i][1];
  286. var xi = Math.min(Math.max(src[srcOffset + i], domain_2i), domain_2i_1);
  287. var e = interpolate(xi, domain_2i, domain_2i_1, encode[i][0], encode[i][1]);
  288. var size_i = size[i];
  289. e = Math.min(Math.max(e, 0), size_i - 1);
  290. var e0 = e < size_i - 1 ? Math.floor(e) : e - 1;
  291. var n0 = e0 + 1 - e;
  292. var n1 = e - e0;
  293. var offset0 = e0 * k;
  294. var offset1 = offset0 + k;
  295. for (j = 0; j < cubeVertices; j++) {
  296. if (j & pos) {
  297. cubeN[j] *= n1;
  298. cubeVertex[j] += offset1;
  299. } else {
  300. cubeN[j] *= n0;
  301. cubeVertex[j] += offset0;
  302. }
  303. }
  304. k *= size_i;
  305. pos <<= 1;
  306. }
  307. for (j = 0; j < n; ++j) {
  308. var rj = 0;
  309. for (i = 0; i < cubeVertices; i++) {
  310. rj += samples[cubeVertex[i] + j] * cubeN[i];
  311. }
  312. rj = interpolate(rj, 0, 1, decode[j][0], decode[j][1]);
  313. dest[destOffset + j] = Math.min(Math.max(rj, range[j][0]), range[j][1]);
  314. }
  315. };
  316. },
  317. constructInterpolated: function constructInterpolated(_ref8) {
  318. var xref = _ref8.xref,
  319. isEvalSupported = _ref8.isEvalSupported,
  320. fn = _ref8.fn,
  321. dict = _ref8.dict;
  322. var c0 = dict.getArray('C0') || [0];
  323. var c1 = dict.getArray('C1') || [1];
  324. var n = dict.get('N');
  325. if (!Array.isArray(c0) || !Array.isArray(c1)) {
  326. throw new _util.FormatError('Illegal dictionary for interpolated function');
  327. }
  328. var length = c0.length;
  329. var diff = [];
  330. for (var i = 0; i < length; ++i) {
  331. diff.push(c1[i] - c0[i]);
  332. }
  333. return [CONSTRUCT_INTERPOLATED, c0, diff, n];
  334. },
  335. constructInterpolatedFromIR: function constructInterpolatedFromIR(_ref9) {
  336. var xref = _ref9.xref,
  337. isEvalSupported = _ref9.isEvalSupported,
  338. IR = _ref9.IR;
  339. var c0 = IR[1];
  340. var diff = IR[2];
  341. var n = IR[3];
  342. var length = diff.length;
  343. return function constructInterpolatedFromIRResult(src, srcOffset, dest, destOffset) {
  344. var x = n === 1 ? src[srcOffset] : Math.pow(src[srcOffset], n);
  345. for (var j = 0; j < length; ++j) {
  346. dest[destOffset + j] = c0[j] + x * diff[j];
  347. }
  348. };
  349. },
  350. constructStiched: function constructStiched(_ref10) {
  351. var xref = _ref10.xref,
  352. isEvalSupported = _ref10.isEvalSupported,
  353. fn = _ref10.fn,
  354. dict = _ref10.dict;
  355. var domain = dict.getArray('Domain');
  356. if (!domain) {
  357. throw new _util.FormatError('No domain');
  358. }
  359. var inputSize = domain.length / 2;
  360. if (inputSize !== 1) {
  361. throw new _util.FormatError('Bad domain for stiched function');
  362. }
  363. var fnRefs = dict.get('Functions');
  364. var fns = [];
  365. for (var i = 0, ii = fnRefs.length; i < ii; ++i) {
  366. fns.push(this.getIR({
  367. xref: xref,
  368. isEvalSupported: isEvalSupported,
  369. fn: xref.fetchIfRef(fnRefs[i])
  370. }));
  371. }
  372. var bounds = dict.getArray('Bounds');
  373. var encode = dict.getArray('Encode');
  374. return [CONSTRUCT_STICHED, domain, bounds, encode, fns];
  375. },
  376. constructStichedFromIR: function constructStichedFromIR(_ref11) {
  377. var xref = _ref11.xref,
  378. isEvalSupported = _ref11.isEvalSupported,
  379. IR = _ref11.IR;
  380. var domain = IR[1];
  381. var bounds = IR[2];
  382. var encode = IR[3];
  383. var fnsIR = IR[4];
  384. var fns = [];
  385. var tmpBuf = new Float32Array(1);
  386. for (var i = 0, ii = fnsIR.length; i < ii; i++) {
  387. fns.push(this.fromIR({
  388. xref: xref,
  389. isEvalSupported: isEvalSupported,
  390. IR: fnsIR[i]
  391. }));
  392. }
  393. return function constructStichedFromIRResult(src, srcOffset, dest, destOffset) {
  394. var clip = function constructStichedFromIRClip(v, min, max) {
  395. if (v > max) {
  396. v = max;
  397. } else if (v < min) {
  398. v = min;
  399. }
  400. return v;
  401. };
  402. var v = clip(src[srcOffset], domain[0], domain[1]);
  403. for (var i = 0, ii = bounds.length; i < ii; ++i) {
  404. if (v < bounds[i]) {
  405. break;
  406. }
  407. }
  408. var dmin = domain[0];
  409. if (i > 0) {
  410. dmin = bounds[i - 1];
  411. }
  412. var dmax = domain[1];
  413. if (i < bounds.length) {
  414. dmax = bounds[i];
  415. }
  416. var rmin = encode[2 * i];
  417. var rmax = encode[2 * i + 1];
  418. tmpBuf[0] = dmin === dmax ? rmin : rmin + (v - dmin) * (rmax - rmin) / (dmax - dmin);
  419. fns[i](tmpBuf, 0, dest, destOffset);
  420. };
  421. },
  422. constructPostScript: function constructPostScript(_ref12) {
  423. var xref = _ref12.xref,
  424. isEvalSupported = _ref12.isEvalSupported,
  425. fn = _ref12.fn,
  426. dict = _ref12.dict;
  427. var domain = dict.getArray('Domain');
  428. var range = dict.getArray('Range');
  429. if (!domain) {
  430. throw new _util.FormatError('No domain.');
  431. }
  432. if (!range) {
  433. throw new _util.FormatError('No range.');
  434. }
  435. var lexer = new _ps_parser.PostScriptLexer(fn);
  436. var parser = new _ps_parser.PostScriptParser(lexer);
  437. var code = parser.parse();
  438. return [CONSTRUCT_POSTSCRIPT, domain, range, code];
  439. },
  440. constructPostScriptFromIR: function constructPostScriptFromIR(_ref13) {
  441. var xref = _ref13.xref,
  442. isEvalSupported = _ref13.isEvalSupported,
  443. IR = _ref13.IR;
  444. var domain = IR[1];
  445. var range = IR[2];
  446. var code = IR[3];
  447. if (isEvalSupported && IsEvalSupportedCached.value) {
  448. var compiled = new PostScriptCompiler().compile(code, domain, range);
  449. if (compiled) {
  450. return new Function('src', 'srcOffset', 'dest', 'destOffset', compiled);
  451. }
  452. }
  453. (0, _util.info)('Unable to compile PS function');
  454. var numOutputs = range.length >> 1;
  455. var numInputs = domain.length >> 1;
  456. var evaluator = new PostScriptEvaluator(code);
  457. var cache = Object.create(null);
  458. var MAX_CACHE_SIZE = 2048 * 4;
  459. var cache_available = MAX_CACHE_SIZE;
  460. var tmpBuf = new Float32Array(numInputs);
  461. return function constructPostScriptFromIRResult(src, srcOffset, dest, destOffset) {
  462. var i, value;
  463. var key = '';
  464. var input = tmpBuf;
  465. for (i = 0; i < numInputs; i++) {
  466. value = src[srcOffset + i];
  467. input[i] = value;
  468. key += value + '_';
  469. }
  470. var cachedValue = cache[key];
  471. if (cachedValue !== undefined) {
  472. dest.set(cachedValue, destOffset);
  473. return;
  474. }
  475. var output = new Float32Array(numOutputs);
  476. var stack = evaluator.execute(input);
  477. var stackIndex = stack.length - numOutputs;
  478. for (i = 0; i < numOutputs; i++) {
  479. value = stack[stackIndex + i];
  480. var bound = range[i * 2];
  481. if (value < bound) {
  482. value = bound;
  483. } else {
  484. bound = range[i * 2 + 1];
  485. if (value > bound) {
  486. value = bound;
  487. }
  488. }
  489. output[i] = value;
  490. }
  491. if (cache_available > 0) {
  492. cache_available--;
  493. cache[key] = output;
  494. }
  495. dest.set(output, destOffset);
  496. };
  497. }
  498. };
  499. }();
  500. function isPDFFunction(v) {
  501. var fnDict;
  502. if ((typeof v === 'undefined' ? 'undefined' : _typeof(v)) !== 'object') {
  503. return false;
  504. } else if ((0, _primitives.isDict)(v)) {
  505. fnDict = v;
  506. } else if ((0, _primitives.isStream)(v)) {
  507. fnDict = v.dict;
  508. } else {
  509. return false;
  510. }
  511. return fnDict.has('FunctionType');
  512. }
  513. var PostScriptStack = function PostScriptStackClosure() {
  514. var MAX_STACK_SIZE = 100;
  515. function PostScriptStack(initialStack) {
  516. this.stack = !initialStack ? [] : Array.prototype.slice.call(initialStack, 0);
  517. }
  518. PostScriptStack.prototype = {
  519. push: function PostScriptStack_push(value) {
  520. if (this.stack.length >= MAX_STACK_SIZE) {
  521. throw new Error('PostScript function stack overflow.');
  522. }
  523. this.stack.push(value);
  524. },
  525. pop: function PostScriptStack_pop() {
  526. if (this.stack.length <= 0) {
  527. throw new Error('PostScript function stack underflow.');
  528. }
  529. return this.stack.pop();
  530. },
  531. copy: function PostScriptStack_copy(n) {
  532. if (this.stack.length + n >= MAX_STACK_SIZE) {
  533. throw new Error('PostScript function stack overflow.');
  534. }
  535. var stack = this.stack;
  536. for (var i = stack.length - n, j = n - 1; j >= 0; j--, i++) {
  537. stack.push(stack[i]);
  538. }
  539. },
  540. index: function PostScriptStack_index(n) {
  541. this.push(this.stack[this.stack.length - n - 1]);
  542. },
  543. roll: function PostScriptStack_roll(n, p) {
  544. var stack = this.stack;
  545. var l = stack.length - n;
  546. var r = stack.length - 1,
  547. c = l + (p - Math.floor(p / n) * n),
  548. i,
  549. j,
  550. t;
  551. for (i = l, j = r; i < j; i++, j--) {
  552. t = stack[i];
  553. stack[i] = stack[j];
  554. stack[j] = t;
  555. }
  556. for (i = l, j = c - 1; i < j; i++, j--) {
  557. t = stack[i];
  558. stack[i] = stack[j];
  559. stack[j] = t;
  560. }
  561. for (i = c, j = r; i < j; i++, j--) {
  562. t = stack[i];
  563. stack[i] = stack[j];
  564. stack[j] = t;
  565. }
  566. }
  567. };
  568. return PostScriptStack;
  569. }();
  570. var PostScriptEvaluator = function PostScriptEvaluatorClosure() {
  571. function PostScriptEvaluator(operators) {
  572. this.operators = operators;
  573. }
  574. PostScriptEvaluator.prototype = {
  575. execute: function PostScriptEvaluator_execute(initialStack) {
  576. var stack = new PostScriptStack(initialStack);
  577. var counter = 0;
  578. var operators = this.operators;
  579. var length = operators.length;
  580. var operator, a, b;
  581. while (counter < length) {
  582. operator = operators[counter++];
  583. if (typeof operator === 'number') {
  584. stack.push(operator);
  585. continue;
  586. }
  587. switch (operator) {
  588. case 'jz':
  589. b = stack.pop();
  590. a = stack.pop();
  591. if (!a) {
  592. counter = b;
  593. }
  594. break;
  595. case 'j':
  596. a = stack.pop();
  597. counter = a;
  598. break;
  599. case 'abs':
  600. a = stack.pop();
  601. stack.push(Math.abs(a));
  602. break;
  603. case 'add':
  604. b = stack.pop();
  605. a = stack.pop();
  606. stack.push(a + b);
  607. break;
  608. case 'and':
  609. b = stack.pop();
  610. a = stack.pop();
  611. if ((0, _util.isBool)(a) && (0, _util.isBool)(b)) {
  612. stack.push(a && b);
  613. } else {
  614. stack.push(a & b);
  615. }
  616. break;
  617. case 'atan':
  618. a = stack.pop();
  619. stack.push(Math.atan(a));
  620. break;
  621. case 'bitshift':
  622. b = stack.pop();
  623. a = stack.pop();
  624. if (a > 0) {
  625. stack.push(a << b);
  626. } else {
  627. stack.push(a >> b);
  628. }
  629. break;
  630. case 'ceiling':
  631. a = stack.pop();
  632. stack.push(Math.ceil(a));
  633. break;
  634. case 'copy':
  635. a = stack.pop();
  636. stack.copy(a);
  637. break;
  638. case 'cos':
  639. a = stack.pop();
  640. stack.push(Math.cos(a));
  641. break;
  642. case 'cvi':
  643. a = stack.pop() | 0;
  644. stack.push(a);
  645. break;
  646. case 'cvr':
  647. break;
  648. case 'div':
  649. b = stack.pop();
  650. a = stack.pop();
  651. stack.push(a / b);
  652. break;
  653. case 'dup':
  654. stack.copy(1);
  655. break;
  656. case 'eq':
  657. b = stack.pop();
  658. a = stack.pop();
  659. stack.push(a === b);
  660. break;
  661. case 'exch':
  662. stack.roll(2, 1);
  663. break;
  664. case 'exp':
  665. b = stack.pop();
  666. a = stack.pop();
  667. stack.push(Math.pow(a, b));
  668. break;
  669. case 'false':
  670. stack.push(false);
  671. break;
  672. case 'floor':
  673. a = stack.pop();
  674. stack.push(Math.floor(a));
  675. break;
  676. case 'ge':
  677. b = stack.pop();
  678. a = stack.pop();
  679. stack.push(a >= b);
  680. break;
  681. case 'gt':
  682. b = stack.pop();
  683. a = stack.pop();
  684. stack.push(a > b);
  685. break;
  686. case 'idiv':
  687. b = stack.pop();
  688. a = stack.pop();
  689. stack.push(a / b | 0);
  690. break;
  691. case 'index':
  692. a = stack.pop();
  693. stack.index(a);
  694. break;
  695. case 'le':
  696. b = stack.pop();
  697. a = stack.pop();
  698. stack.push(a <= b);
  699. break;
  700. case 'ln':
  701. a = stack.pop();
  702. stack.push(Math.log(a));
  703. break;
  704. case 'log':
  705. a = stack.pop();
  706. stack.push(Math.log(a) / Math.LN10);
  707. break;
  708. case 'lt':
  709. b = stack.pop();
  710. a = stack.pop();
  711. stack.push(a < b);
  712. break;
  713. case 'mod':
  714. b = stack.pop();
  715. a = stack.pop();
  716. stack.push(a % b);
  717. break;
  718. case 'mul':
  719. b = stack.pop();
  720. a = stack.pop();
  721. stack.push(a * b);
  722. break;
  723. case 'ne':
  724. b = stack.pop();
  725. a = stack.pop();
  726. stack.push(a !== b);
  727. break;
  728. case 'neg':
  729. a = stack.pop();
  730. stack.push(-a);
  731. break;
  732. case 'not':
  733. a = stack.pop();
  734. if ((0, _util.isBool)(a)) {
  735. stack.push(!a);
  736. } else {
  737. stack.push(~a);
  738. }
  739. break;
  740. case 'or':
  741. b = stack.pop();
  742. a = stack.pop();
  743. if ((0, _util.isBool)(a) && (0, _util.isBool)(b)) {
  744. stack.push(a || b);
  745. } else {
  746. stack.push(a | b);
  747. }
  748. break;
  749. case 'pop':
  750. stack.pop();
  751. break;
  752. case 'roll':
  753. b = stack.pop();
  754. a = stack.pop();
  755. stack.roll(a, b);
  756. break;
  757. case 'round':
  758. a = stack.pop();
  759. stack.push(Math.round(a));
  760. break;
  761. case 'sin':
  762. a = stack.pop();
  763. stack.push(Math.sin(a));
  764. break;
  765. case 'sqrt':
  766. a = stack.pop();
  767. stack.push(Math.sqrt(a));
  768. break;
  769. case 'sub':
  770. b = stack.pop();
  771. a = stack.pop();
  772. stack.push(a - b);
  773. break;
  774. case 'true':
  775. stack.push(true);
  776. break;
  777. case 'truncate':
  778. a = stack.pop();
  779. a = a < 0 ? Math.ceil(a) : Math.floor(a);
  780. stack.push(a);
  781. break;
  782. case 'xor':
  783. b = stack.pop();
  784. a = stack.pop();
  785. if ((0, _util.isBool)(a) && (0, _util.isBool)(b)) {
  786. stack.push(a !== b);
  787. } else {
  788. stack.push(a ^ b);
  789. }
  790. break;
  791. default:
  792. throw new _util.FormatError('Unknown operator ' + operator);
  793. }
  794. }
  795. return stack.stack;
  796. }
  797. };
  798. return PostScriptEvaluator;
  799. }();
  800. var PostScriptCompiler = function PostScriptCompilerClosure() {
  801. function AstNode(type) {
  802. this.type = type;
  803. }
  804. AstNode.prototype.visit = function (visitor) {
  805. (0, _util.unreachable)('abstract method');
  806. };
  807. function AstArgument(index, min, max) {
  808. AstNode.call(this, 'args');
  809. this.index = index;
  810. this.min = min;
  811. this.max = max;
  812. }
  813. AstArgument.prototype = Object.create(AstNode.prototype);
  814. AstArgument.prototype.visit = function (visitor) {
  815. visitor.visitArgument(this);
  816. };
  817. function AstLiteral(number) {
  818. AstNode.call(this, 'literal');
  819. this.number = number;
  820. this.min = number;
  821. this.max = number;
  822. }
  823. AstLiteral.prototype = Object.create(AstNode.prototype);
  824. AstLiteral.prototype.visit = function (visitor) {
  825. visitor.visitLiteral(this);
  826. };
  827. function AstBinaryOperation(op, arg1, arg2, min, max) {
  828. AstNode.call(this, 'binary');
  829. this.op = op;
  830. this.arg1 = arg1;
  831. this.arg2 = arg2;
  832. this.min = min;
  833. this.max = max;
  834. }
  835. AstBinaryOperation.prototype = Object.create(AstNode.prototype);
  836. AstBinaryOperation.prototype.visit = function (visitor) {
  837. visitor.visitBinaryOperation(this);
  838. };
  839. function AstMin(arg, max) {
  840. AstNode.call(this, 'max');
  841. this.arg = arg;
  842. this.min = arg.min;
  843. this.max = max;
  844. }
  845. AstMin.prototype = Object.create(AstNode.prototype);
  846. AstMin.prototype.visit = function (visitor) {
  847. visitor.visitMin(this);
  848. };
  849. function AstVariable(index, min, max) {
  850. AstNode.call(this, 'var');
  851. this.index = index;
  852. this.min = min;
  853. this.max = max;
  854. }
  855. AstVariable.prototype = Object.create(AstNode.prototype);
  856. AstVariable.prototype.visit = function (visitor) {
  857. visitor.visitVariable(this);
  858. };
  859. function AstVariableDefinition(variable, arg) {
  860. AstNode.call(this, 'definition');
  861. this.variable = variable;
  862. this.arg = arg;
  863. }
  864. AstVariableDefinition.prototype = Object.create(AstNode.prototype);
  865. AstVariableDefinition.prototype.visit = function (visitor) {
  866. visitor.visitVariableDefinition(this);
  867. };
  868. function ExpressionBuilderVisitor() {
  869. this.parts = [];
  870. }
  871. ExpressionBuilderVisitor.prototype = {
  872. visitArgument: function visitArgument(arg) {
  873. this.parts.push('Math.max(', arg.min, ', Math.min(', arg.max, ', src[srcOffset + ', arg.index, ']))');
  874. },
  875. visitVariable: function visitVariable(variable) {
  876. this.parts.push('v', variable.index);
  877. },
  878. visitLiteral: function visitLiteral(literal) {
  879. this.parts.push(literal.number);
  880. },
  881. visitBinaryOperation: function visitBinaryOperation(operation) {
  882. this.parts.push('(');
  883. operation.arg1.visit(this);
  884. this.parts.push(' ', operation.op, ' ');
  885. operation.arg2.visit(this);
  886. this.parts.push(')');
  887. },
  888. visitVariableDefinition: function visitVariableDefinition(definition) {
  889. this.parts.push('var ');
  890. definition.variable.visit(this);
  891. this.parts.push(' = ');
  892. definition.arg.visit(this);
  893. this.parts.push(';');
  894. },
  895. visitMin: function visitMin(max) {
  896. this.parts.push('Math.min(');
  897. max.arg.visit(this);
  898. this.parts.push(', ', max.max, ')');
  899. },
  900. toString: function toString() {
  901. return this.parts.join('');
  902. }
  903. };
  904. function buildAddOperation(num1, num2) {
  905. if (num2.type === 'literal' && num2.number === 0) {
  906. return num1;
  907. }
  908. if (num1.type === 'literal' && num1.number === 0) {
  909. return num2;
  910. }
  911. if (num2.type === 'literal' && num1.type === 'literal') {
  912. return new AstLiteral(num1.number + num2.number);
  913. }
  914. return new AstBinaryOperation('+', num1, num2, num1.min + num2.min, num1.max + num2.max);
  915. }
  916. function buildMulOperation(num1, num2) {
  917. if (num2.type === 'literal') {
  918. if (num2.number === 0) {
  919. return new AstLiteral(0);
  920. } else if (num2.number === 1) {
  921. return num1;
  922. } else if (num1.type === 'literal') {
  923. return new AstLiteral(num1.number * num2.number);
  924. }
  925. }
  926. if (num1.type === 'literal') {
  927. if (num1.number === 0) {
  928. return new AstLiteral(0);
  929. } else if (num1.number === 1) {
  930. return num2;
  931. }
  932. }
  933. var min = Math.min(num1.min * num2.min, num1.min * num2.max, num1.max * num2.min, num1.max * num2.max);
  934. var max = Math.max(num1.min * num2.min, num1.min * num2.max, num1.max * num2.min, num1.max * num2.max);
  935. return new AstBinaryOperation('*', num1, num2, min, max);
  936. }
  937. function buildSubOperation(num1, num2) {
  938. if (num2.type === 'literal') {
  939. if (num2.number === 0) {
  940. return num1;
  941. } else if (num1.type === 'literal') {
  942. return new AstLiteral(num1.number - num2.number);
  943. }
  944. }
  945. if (num2.type === 'binary' && num2.op === '-' && num1.type === 'literal' && num1.number === 1 && num2.arg1.type === 'literal' && num2.arg1.number === 1) {
  946. return num2.arg2;
  947. }
  948. return new AstBinaryOperation('-', num1, num2, num1.min - num2.max, num1.max - num2.min);
  949. }
  950. function buildMinOperation(num1, max) {
  951. if (num1.min >= max) {
  952. return new AstLiteral(max);
  953. } else if (num1.max <= max) {
  954. return num1;
  955. }
  956. return new AstMin(num1, max);
  957. }
  958. function PostScriptCompiler() {}
  959. PostScriptCompiler.prototype = {
  960. compile: function PostScriptCompiler_compile(code, domain, range) {
  961. var stack = [];
  962. var i, ii;
  963. var instructions = [];
  964. var inputSize = domain.length >> 1,
  965. outputSize = range.length >> 1;
  966. var lastRegister = 0;
  967. var n, j;
  968. var num1, num2, ast1, ast2, tmpVar, item;
  969. for (i = 0; i < inputSize; i++) {
  970. stack.push(new AstArgument(i, domain[i * 2], domain[i * 2 + 1]));
  971. }
  972. for (i = 0, ii = code.length; i < ii; i++) {
  973. item = code[i];
  974. if (typeof item === 'number') {
  975. stack.push(new AstLiteral(item));
  976. continue;
  977. }
  978. switch (item) {
  979. case 'add':
  980. if (stack.length < 2) {
  981. return null;
  982. }
  983. num2 = stack.pop();
  984. num1 = stack.pop();
  985. stack.push(buildAddOperation(num1, num2));
  986. break;
  987. case 'cvr':
  988. if (stack.length < 1) {
  989. return null;
  990. }
  991. break;
  992. case 'mul':
  993. if (stack.length < 2) {
  994. return null;
  995. }
  996. num2 = stack.pop();
  997. num1 = stack.pop();
  998. stack.push(buildMulOperation(num1, num2));
  999. break;
  1000. case 'sub':
  1001. if (stack.length < 2) {
  1002. return null;
  1003. }
  1004. num2 = stack.pop();
  1005. num1 = stack.pop();
  1006. stack.push(buildSubOperation(num1, num2));
  1007. break;
  1008. case 'exch':
  1009. if (stack.length < 2) {
  1010. return null;
  1011. }
  1012. ast1 = stack.pop();
  1013. ast2 = stack.pop();
  1014. stack.push(ast1, ast2);
  1015. break;
  1016. case 'pop':
  1017. if (stack.length < 1) {
  1018. return null;
  1019. }
  1020. stack.pop();
  1021. break;
  1022. case 'index':
  1023. if (stack.length < 1) {
  1024. return null;
  1025. }
  1026. num1 = stack.pop();
  1027. if (num1.type !== 'literal') {
  1028. return null;
  1029. }
  1030. n = num1.number;
  1031. if (n < 0 || !Number.isInteger(n) || stack.length < n) {
  1032. return null;
  1033. }
  1034. ast1 = stack[stack.length - n - 1];
  1035. if (ast1.type === 'literal' || ast1.type === 'var') {
  1036. stack.push(ast1);
  1037. break;
  1038. }
  1039. tmpVar = new AstVariable(lastRegister++, ast1.min, ast1.max);
  1040. stack[stack.length - n - 1] = tmpVar;
  1041. stack.push(tmpVar);
  1042. instructions.push(new AstVariableDefinition(tmpVar, ast1));
  1043. break;
  1044. case 'dup':
  1045. if (stack.length < 1) {
  1046. return null;
  1047. }
  1048. if (typeof code[i + 1] === 'number' && code[i + 2] === 'gt' && code[i + 3] === i + 7 && code[i + 4] === 'jz' && code[i + 5] === 'pop' && code[i + 6] === code[i + 1]) {
  1049. num1 = stack.pop();
  1050. stack.push(buildMinOperation(num1, code[i + 1]));
  1051. i += 6;
  1052. break;
  1053. }
  1054. ast1 = stack[stack.length - 1];
  1055. if (ast1.type === 'literal' || ast1.type === 'var') {
  1056. stack.push(ast1);
  1057. break;
  1058. }
  1059. tmpVar = new AstVariable(lastRegister++, ast1.min, ast1.max);
  1060. stack[stack.length - 1] = tmpVar;
  1061. stack.push(tmpVar);
  1062. instructions.push(new AstVariableDefinition(tmpVar, ast1));
  1063. break;
  1064. case 'roll':
  1065. if (stack.length < 2) {
  1066. return null;
  1067. }
  1068. num2 = stack.pop();
  1069. num1 = stack.pop();
  1070. if (num2.type !== 'literal' || num1.type !== 'literal') {
  1071. return null;
  1072. }
  1073. j = num2.number;
  1074. n = num1.number;
  1075. if (n <= 0 || !Number.isInteger(n) || !Number.isInteger(j) || stack.length < n) {
  1076. return null;
  1077. }
  1078. j = (j % n + n) % n;
  1079. if (j === 0) {
  1080. break;
  1081. }
  1082. Array.prototype.push.apply(stack, stack.splice(stack.length - n, n - j));
  1083. break;
  1084. default:
  1085. return null;
  1086. }
  1087. }
  1088. if (stack.length !== outputSize) {
  1089. return null;
  1090. }
  1091. var result = [];
  1092. instructions.forEach(function (instruction) {
  1093. var statementBuilder = new ExpressionBuilderVisitor();
  1094. instruction.visit(statementBuilder);
  1095. result.push(statementBuilder.toString());
  1096. });
  1097. stack.forEach(function (expr, i) {
  1098. var statementBuilder = new ExpressionBuilderVisitor();
  1099. expr.visit(statementBuilder);
  1100. var min = range[i * 2],
  1101. max = range[i * 2 + 1];
  1102. var out = [statementBuilder.toString()];
  1103. if (min > expr.min) {
  1104. out.unshift('Math.max(', min, ', ');
  1105. out.push(')');
  1106. }
  1107. if (max < expr.max) {
  1108. out.unshift('Math.min(', max, ', ');
  1109. out.push(')');
  1110. }
  1111. out.unshift('dest[destOffset + ', i, '] = ');
  1112. out.push(';');
  1113. result.push(out.join(''));
  1114. });
  1115. return result.join('\n');
  1116. }
  1117. };
  1118. return PostScriptCompiler;
  1119. }();
  1120. exports.isPDFFunction = isPDFFunction;
  1121. exports.PDFFunctionFactory = PDFFunctionFactory;
  1122. exports.PostScriptEvaluator = PostScriptEvaluator;
  1123. exports.PostScriptCompiler = PostScriptCompiler;