function.js 35 KB

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