function.js 31 KB

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