2
0

function.js 31 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982
  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. (0, _util.error)('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 (!(0, _util.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. (0, _util.error)('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 (!(0, _util.isArray)(c0) || !(0, _util.isArray)(c1)) {
  205. (0, _util.error)('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. (0, _util.error)('No domain');
  230. }
  231. var inputSize = domain.length / 2;
  232. if (inputSize !== 1) {
  233. (0, _util.error)('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. (0, _util.error)('No domain.');
  288. }
  289. if (!range) {
  290. (0, _util.error)('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. (0, _util.error)('PostScript function stack overflow.');
  374. }
  375. this.stack.push(value);
  376. },
  377. pop: function PostScriptStack_pop() {
  378. if (this.stack.length <= 0) {
  379. (0, _util.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. (0, _util.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. (0, _util.error)('Unknown operator ' + operator);
  645. break;
  646. }
  647. }
  648. return stack.stack;
  649. }
  650. };
  651. return PostScriptEvaluator;
  652. }();
  653. var PostScriptCompiler = function PostScriptCompilerClosure() {
  654. function AstNode(type) {
  655. this.type = type;
  656. }
  657. AstNode.prototype.visit = function (visitor) {
  658. throw new Error('abstract method');
  659. };
  660. function AstArgument(index, min, max) {
  661. AstNode.call(this, 'args');
  662. this.index = index;
  663. this.min = min;
  664. this.max = max;
  665. }
  666. AstArgument.prototype = Object.create(AstNode.prototype);
  667. AstArgument.prototype.visit = function (visitor) {
  668. visitor.visitArgument(this);
  669. };
  670. function AstLiteral(number) {
  671. AstNode.call(this, 'literal');
  672. this.number = number;
  673. this.min = number;
  674. this.max = number;
  675. }
  676. AstLiteral.prototype = Object.create(AstNode.prototype);
  677. AstLiteral.prototype.visit = function (visitor) {
  678. visitor.visitLiteral(this);
  679. };
  680. function AstBinaryOperation(op, arg1, arg2, min, max) {
  681. AstNode.call(this, 'binary');
  682. this.op = op;
  683. this.arg1 = arg1;
  684. this.arg2 = arg2;
  685. this.min = min;
  686. this.max = max;
  687. }
  688. AstBinaryOperation.prototype = Object.create(AstNode.prototype);
  689. AstBinaryOperation.prototype.visit = function (visitor) {
  690. visitor.visitBinaryOperation(this);
  691. };
  692. function AstMin(arg, max) {
  693. AstNode.call(this, 'max');
  694. this.arg = arg;
  695. this.min = arg.min;
  696. this.max = max;
  697. }
  698. AstMin.prototype = Object.create(AstNode.prototype);
  699. AstMin.prototype.visit = function (visitor) {
  700. visitor.visitMin(this);
  701. };
  702. function AstVariable(index, min, max) {
  703. AstNode.call(this, 'var');
  704. this.index = index;
  705. this.min = min;
  706. this.max = max;
  707. }
  708. AstVariable.prototype = Object.create(AstNode.prototype);
  709. AstVariable.prototype.visit = function (visitor) {
  710. visitor.visitVariable(this);
  711. };
  712. function AstVariableDefinition(variable, arg) {
  713. AstNode.call(this, 'definition');
  714. this.variable = variable;
  715. this.arg = arg;
  716. }
  717. AstVariableDefinition.prototype = Object.create(AstNode.prototype);
  718. AstVariableDefinition.prototype.visit = function (visitor) {
  719. visitor.visitVariableDefinition(this);
  720. };
  721. function ExpressionBuilderVisitor() {
  722. this.parts = [];
  723. }
  724. ExpressionBuilderVisitor.prototype = {
  725. visitArgument: function visitArgument(arg) {
  726. this.parts.push('Math.max(', arg.min, ', Math.min(', arg.max, ', src[srcOffset + ', arg.index, ']))');
  727. },
  728. visitVariable: function visitVariable(variable) {
  729. this.parts.push('v', variable.index);
  730. },
  731. visitLiteral: function visitLiteral(literal) {
  732. this.parts.push(literal.number);
  733. },
  734. visitBinaryOperation: function visitBinaryOperation(operation) {
  735. this.parts.push('(');
  736. operation.arg1.visit(this);
  737. this.parts.push(' ', operation.op, ' ');
  738. operation.arg2.visit(this);
  739. this.parts.push(')');
  740. },
  741. visitVariableDefinition: function visitVariableDefinition(definition) {
  742. this.parts.push('var ');
  743. definition.variable.visit(this);
  744. this.parts.push(' = ');
  745. definition.arg.visit(this);
  746. this.parts.push(';');
  747. },
  748. visitMin: function visitMin(max) {
  749. this.parts.push('Math.min(');
  750. max.arg.visit(this);
  751. this.parts.push(', ', max.max, ')');
  752. },
  753. toString: function toString() {
  754. return this.parts.join('');
  755. }
  756. };
  757. function buildAddOperation(num1, num2) {
  758. if (num2.type === 'literal' && num2.number === 0) {
  759. return num1;
  760. }
  761. if (num1.type === 'literal' && num1.number === 0) {
  762. return num2;
  763. }
  764. if (num2.type === 'literal' && num1.type === 'literal') {
  765. return new AstLiteral(num1.number + num2.number);
  766. }
  767. return new AstBinaryOperation('+', num1, num2, num1.min + num2.min, num1.max + num2.max);
  768. }
  769. function buildMulOperation(num1, num2) {
  770. if (num2.type === 'literal') {
  771. if (num2.number === 0) {
  772. return new AstLiteral(0);
  773. } else if (num2.number === 1) {
  774. return num1;
  775. } else if (num1.type === 'literal') {
  776. return new AstLiteral(num1.number * num2.number);
  777. }
  778. }
  779. if (num1.type === 'literal') {
  780. if (num1.number === 0) {
  781. return new AstLiteral(0);
  782. } else if (num1.number === 1) {
  783. return num2;
  784. }
  785. }
  786. var min = Math.min(num1.min * num2.min, num1.min * num2.max, num1.max * num2.min, num1.max * num2.max);
  787. var max = Math.max(num1.min * num2.min, num1.min * num2.max, num1.max * num2.min, num1.max * num2.max);
  788. return new AstBinaryOperation('*', num1, num2, min, max);
  789. }
  790. function buildSubOperation(num1, num2) {
  791. if (num2.type === 'literal') {
  792. if (num2.number === 0) {
  793. return num1;
  794. } else if (num1.type === 'literal') {
  795. return new AstLiteral(num1.number - num2.number);
  796. }
  797. }
  798. if (num2.type === 'binary' && num2.op === '-' && num1.type === 'literal' && num1.number === 1 && num2.arg1.type === 'literal' && num2.arg1.number === 1) {
  799. return num2.arg2;
  800. }
  801. return new AstBinaryOperation('-', num1, num2, num1.min - num2.max, num1.max - num2.min);
  802. }
  803. function buildMinOperation(num1, max) {
  804. if (num1.min >= max) {
  805. return new AstLiteral(max);
  806. } else if (num1.max <= max) {
  807. return num1;
  808. }
  809. return new AstMin(num1, max);
  810. }
  811. function PostScriptCompiler() {}
  812. PostScriptCompiler.prototype = {
  813. compile: function PostScriptCompiler_compile(code, domain, range) {
  814. var stack = [];
  815. var i, ii;
  816. var instructions = [];
  817. var inputSize = domain.length >> 1,
  818. outputSize = range.length >> 1;
  819. var lastRegister = 0;
  820. var n, j;
  821. var num1, num2, ast1, ast2, tmpVar, item;
  822. for (i = 0; i < inputSize; i++) {
  823. stack.push(new AstArgument(i, domain[i * 2], domain[i * 2 + 1]));
  824. }
  825. for (i = 0, ii = code.length; i < ii; i++) {
  826. item = code[i];
  827. if (typeof item === 'number') {
  828. stack.push(new AstLiteral(item));
  829. continue;
  830. }
  831. switch (item) {
  832. case 'add':
  833. if (stack.length < 2) {
  834. return null;
  835. }
  836. num2 = stack.pop();
  837. num1 = stack.pop();
  838. stack.push(buildAddOperation(num1, num2));
  839. break;
  840. case 'cvr':
  841. if (stack.length < 1) {
  842. return null;
  843. }
  844. break;
  845. case 'mul':
  846. if (stack.length < 2) {
  847. return null;
  848. }
  849. num2 = stack.pop();
  850. num1 = stack.pop();
  851. stack.push(buildMulOperation(num1, num2));
  852. break;
  853. case 'sub':
  854. if (stack.length < 2) {
  855. return null;
  856. }
  857. num2 = stack.pop();
  858. num1 = stack.pop();
  859. stack.push(buildSubOperation(num1, num2));
  860. break;
  861. case 'exch':
  862. if (stack.length < 2) {
  863. return null;
  864. }
  865. ast1 = stack.pop();
  866. ast2 = stack.pop();
  867. stack.push(ast1, ast2);
  868. break;
  869. case 'pop':
  870. if (stack.length < 1) {
  871. return null;
  872. }
  873. stack.pop();
  874. break;
  875. case 'index':
  876. if (stack.length < 1) {
  877. return null;
  878. }
  879. num1 = stack.pop();
  880. if (num1.type !== 'literal') {
  881. return null;
  882. }
  883. n = num1.number;
  884. if (n < 0 || (n | 0) !== n || stack.length < n) {
  885. return null;
  886. }
  887. ast1 = stack[stack.length - n - 1];
  888. if (ast1.type === 'literal' || ast1.type === 'var') {
  889. stack.push(ast1);
  890. break;
  891. }
  892. tmpVar = new AstVariable(lastRegister++, ast1.min, ast1.max);
  893. stack[stack.length - n - 1] = tmpVar;
  894. stack.push(tmpVar);
  895. instructions.push(new AstVariableDefinition(tmpVar, ast1));
  896. break;
  897. case 'dup':
  898. if (stack.length < 1) {
  899. return null;
  900. }
  901. 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]) {
  902. num1 = stack.pop();
  903. stack.push(buildMinOperation(num1, code[i + 1]));
  904. i += 6;
  905. break;
  906. }
  907. ast1 = stack[stack.length - 1];
  908. if (ast1.type === 'literal' || ast1.type === 'var') {
  909. stack.push(ast1);
  910. break;
  911. }
  912. tmpVar = new AstVariable(lastRegister++, ast1.min, ast1.max);
  913. stack[stack.length - 1] = tmpVar;
  914. stack.push(tmpVar);
  915. instructions.push(new AstVariableDefinition(tmpVar, ast1));
  916. break;
  917. case 'roll':
  918. if (stack.length < 2) {
  919. return null;
  920. }
  921. num2 = stack.pop();
  922. num1 = stack.pop();
  923. if (num2.type !== 'literal' || num1.type !== 'literal') {
  924. return null;
  925. }
  926. j = num2.number;
  927. n = num1.number;
  928. if (n <= 0 || (n | 0) !== n || (j | 0) !== j || stack.length < n) {
  929. return null;
  930. }
  931. j = (j % n + n) % n;
  932. if (j === 0) {
  933. break;
  934. }
  935. Array.prototype.push.apply(stack, stack.splice(stack.length - n, n - j));
  936. break;
  937. default:
  938. return null;
  939. }
  940. }
  941. if (stack.length !== outputSize) {
  942. return null;
  943. }
  944. var result = [];
  945. instructions.forEach(function (instruction) {
  946. var statementBuilder = new ExpressionBuilderVisitor();
  947. instruction.visit(statementBuilder);
  948. result.push(statementBuilder.toString());
  949. });
  950. stack.forEach(function (expr, i) {
  951. var statementBuilder = new ExpressionBuilderVisitor();
  952. expr.visit(statementBuilder);
  953. var min = range[i * 2],
  954. max = range[i * 2 + 1];
  955. var out = [statementBuilder.toString()];
  956. if (min > expr.min) {
  957. out.unshift('Math.max(', min, ', ');
  958. out.push(')');
  959. }
  960. if (max < expr.max) {
  961. out.unshift('Math.min(', max, ', ');
  962. out.push(')');
  963. }
  964. out.unshift('dest[destOffset + ', i, '] = ');
  965. out.push(';');
  966. result.push(out.join(''));
  967. });
  968. return result.join('\n');
  969. }
  970. };
  971. return PostScriptCompiler;
  972. }();
  973. exports.isPDFFunction = isPDFFunction;
  974. exports.PDFFunction = PDFFunction;
  975. exports.PostScriptEvaluator = PostScriptEvaluator;
  976. exports.PostScriptCompiler = PostScriptCompiler;