2
0

function.js 26 KB

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