function.js 31 KB

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