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