function.js 30 KB

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