core_utils.js 10.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414
  1. /**
  2. * @licstart The following is the entire license notice for the
  3. * Javascript code in this page
  4. *
  5. * Copyright 2021 Mozilla Foundation
  6. *
  7. * Licensed under the Apache License, Version 2.0 (the "License");
  8. * you may not use this file except in compliance with the License.
  9. * You may obtain a copy of the License at
  10. *
  11. * http://www.apache.org/licenses/LICENSE-2.0
  12. *
  13. * Unless required by applicable law or agreed to in writing, software
  14. * distributed under the License is distributed on an "AS IS" BASIS,
  15. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  16. * See the License for the specific language governing permissions and
  17. * limitations under the License.
  18. *
  19. * @licend The above is the entire license notice for the
  20. * Javascript code in this page
  21. */
  22. "use strict";
  23. Object.defineProperty(exports, "__esModule", {
  24. value: true
  25. });
  26. exports.collectActions = collectActions;
  27. exports.encodeToXmlString = encodeToXmlString;
  28. exports.escapePDFName = escapePDFName;
  29. exports.getArrayLookupTableFactory = getArrayLookupTableFactory;
  30. exports.getInheritableProperty = getInheritableProperty;
  31. exports.getLookupTableFactory = getLookupTableFactory;
  32. exports.isWhiteSpace = isWhiteSpace;
  33. exports.log2 = log2;
  34. exports.parseXFAPath = parseXFAPath;
  35. exports.readInt8 = readInt8;
  36. exports.readUint16 = readUint16;
  37. exports.readUint32 = readUint32;
  38. exports.toRomanNumerals = toRomanNumerals;
  39. exports.validateCSSFont = validateCSSFont;
  40. exports.XRefParseException = exports.XRefEntryException = exports.ParserEOFException = exports.MissingDataException = void 0;
  41. var _util = require("../shared/util.js");
  42. var _primitives = require("./primitives.js");
  43. function getLookupTableFactory(initializer) {
  44. let lookup;
  45. return function () {
  46. if (initializer) {
  47. lookup = Object.create(null);
  48. initializer(lookup);
  49. initializer = null;
  50. }
  51. return lookup;
  52. };
  53. }
  54. function getArrayLookupTableFactory(initializer) {
  55. let lookup;
  56. return function () {
  57. if (initializer) {
  58. let arr = initializer();
  59. initializer = null;
  60. lookup = Object.create(null);
  61. for (let i = 0, ii = arr.length; i < ii; i += 2) {
  62. lookup[arr[i]] = arr[i + 1];
  63. }
  64. arr = null;
  65. }
  66. return lookup;
  67. };
  68. }
  69. class MissingDataException extends _util.BaseException {
  70. constructor(begin, end) {
  71. super(`Missing data [${begin}, ${end})`);
  72. this.begin = begin;
  73. this.end = end;
  74. }
  75. }
  76. exports.MissingDataException = MissingDataException;
  77. class ParserEOFException extends _util.BaseException {}
  78. exports.ParserEOFException = ParserEOFException;
  79. class XRefEntryException extends _util.BaseException {}
  80. exports.XRefEntryException = XRefEntryException;
  81. class XRefParseException extends _util.BaseException {}
  82. exports.XRefParseException = XRefParseException;
  83. function getInheritableProperty({
  84. dict,
  85. key,
  86. getArray = false,
  87. stopWhenFound = true
  88. }) {
  89. let values;
  90. const visited = new _primitives.RefSet();
  91. while (dict instanceof _primitives.Dict && !(dict.objId && visited.has(dict.objId))) {
  92. if (dict.objId) {
  93. visited.put(dict.objId);
  94. }
  95. const value = getArray ? dict.getArray(key) : dict.get(key);
  96. if (value !== undefined) {
  97. if (stopWhenFound) {
  98. return value;
  99. }
  100. if (!values) {
  101. values = [];
  102. }
  103. values.push(value);
  104. }
  105. dict = dict.get("Parent");
  106. }
  107. return values;
  108. }
  109. const ROMAN_NUMBER_MAP = ["", "C", "CC", "CCC", "CD", "D", "DC", "DCC", "DCCC", "CM", "", "X", "XX", "XXX", "XL", "L", "LX", "LXX", "LXXX", "XC", "", "I", "II", "III", "IV", "V", "VI", "VII", "VIII", "IX"];
  110. function toRomanNumerals(number, lowerCase = false) {
  111. (0, _util.assert)(Number.isInteger(number) && number > 0, "The number should be a positive integer.");
  112. const romanBuf = [];
  113. let pos;
  114. while (number >= 1000) {
  115. number -= 1000;
  116. romanBuf.push("M");
  117. }
  118. pos = number / 100 | 0;
  119. number %= 100;
  120. romanBuf.push(ROMAN_NUMBER_MAP[pos]);
  121. pos = number / 10 | 0;
  122. number %= 10;
  123. romanBuf.push(ROMAN_NUMBER_MAP[10 + pos]);
  124. romanBuf.push(ROMAN_NUMBER_MAP[20 + number]);
  125. const romanStr = romanBuf.join("");
  126. return lowerCase ? romanStr.toLowerCase() : romanStr;
  127. }
  128. function log2(x) {
  129. if (x <= 0) {
  130. return 0;
  131. }
  132. return Math.ceil(Math.log2(x));
  133. }
  134. function readInt8(data, offset) {
  135. return data[offset] << 24 >> 24;
  136. }
  137. function readUint16(data, offset) {
  138. return data[offset] << 8 | data[offset + 1];
  139. }
  140. function readUint32(data, offset) {
  141. return (data[offset] << 24 | data[offset + 1] << 16 | data[offset + 2] << 8 | data[offset + 3]) >>> 0;
  142. }
  143. function isWhiteSpace(ch) {
  144. return ch === 0x20 || ch === 0x09 || ch === 0x0d || ch === 0x0a;
  145. }
  146. function parseXFAPath(path) {
  147. const positionPattern = /(.+)\[([0-9]+)\]$/;
  148. return path.split(".").map(component => {
  149. const m = component.match(positionPattern);
  150. if (m) {
  151. return {
  152. name: m[1],
  153. pos: parseInt(m[2], 10)
  154. };
  155. }
  156. return {
  157. name: component,
  158. pos: 0
  159. };
  160. });
  161. }
  162. function escapePDFName(str) {
  163. const buffer = [];
  164. let start = 0;
  165. for (let i = 0, ii = str.length; i < ii; i++) {
  166. const char = str.charCodeAt(i);
  167. if (char < 0x21 || char > 0x7e || char === 0x23 || char === 0x28 || char === 0x29 || char === 0x3c || char === 0x3e || char === 0x5b || char === 0x5d || char === 0x7b || char === 0x7d || char === 0x2f || char === 0x25) {
  168. if (start < i) {
  169. buffer.push(str.substring(start, i));
  170. }
  171. buffer.push(`#${char.toString(16)}`);
  172. start = i + 1;
  173. }
  174. }
  175. if (buffer.length === 0) {
  176. return str;
  177. }
  178. if (start < str.length) {
  179. buffer.push(str.substring(start, str.length));
  180. }
  181. return buffer.join("");
  182. }
  183. function _collectJS(entry, xref, list, parents) {
  184. if (!entry) {
  185. return;
  186. }
  187. let parent = null;
  188. if ((0, _primitives.isRef)(entry)) {
  189. if (parents.has(entry)) {
  190. return;
  191. }
  192. parent = entry;
  193. parents.put(parent);
  194. entry = xref.fetch(entry);
  195. }
  196. if (Array.isArray(entry)) {
  197. for (const element of entry) {
  198. _collectJS(element, xref, list, parents);
  199. }
  200. } else if (entry instanceof _primitives.Dict) {
  201. if ((0, _primitives.isName)(entry.get("S"), "JavaScript") && entry.has("JS")) {
  202. const js = entry.get("JS");
  203. let code;
  204. if ((0, _primitives.isStream)(js)) {
  205. code = js.getString();
  206. } else {
  207. code = js;
  208. }
  209. code = (0, _util.stringToPDFString)(code);
  210. if (code) {
  211. list.push(code);
  212. }
  213. }
  214. _collectJS(entry.getRaw("Next"), xref, list, parents);
  215. }
  216. if (parent) {
  217. parents.remove(parent);
  218. }
  219. }
  220. function collectActions(xref, dict, eventType) {
  221. const actions = Object.create(null);
  222. const additionalActionsDicts = getInheritableProperty({
  223. dict,
  224. key: "AA",
  225. stopWhenFound: false
  226. });
  227. if (additionalActionsDicts) {
  228. for (let i = additionalActionsDicts.length - 1; i >= 0; i--) {
  229. const additionalActions = additionalActionsDicts[i];
  230. if (!(additionalActions instanceof _primitives.Dict)) {
  231. continue;
  232. }
  233. for (const key of additionalActions.getKeys()) {
  234. const action = eventType[key];
  235. if (!action) {
  236. continue;
  237. }
  238. const actionDict = additionalActions.getRaw(key);
  239. const parents = new _primitives.RefSet();
  240. const list = [];
  241. _collectJS(actionDict, xref, list, parents);
  242. if (list.length > 0) {
  243. actions[action] = list;
  244. }
  245. }
  246. }
  247. }
  248. if (dict.has("A")) {
  249. const actionDict = dict.get("A");
  250. const parents = new _primitives.RefSet();
  251. const list = [];
  252. _collectJS(actionDict, xref, list, parents);
  253. if (list.length > 0) {
  254. actions.Action = list;
  255. }
  256. }
  257. return (0, _util.objectSize)(actions) > 0 ? actions : null;
  258. }
  259. const XMLEntities = {
  260. 0x3c: "&lt;",
  261. 0x3e: "&gt;",
  262. 0x26: "&amp;",
  263. 0x22: "&quot;",
  264. 0x27: "&apos;"
  265. };
  266. function encodeToXmlString(str) {
  267. const buffer = [];
  268. let start = 0;
  269. for (let i = 0, ii = str.length; i < ii; i++) {
  270. const char = str.codePointAt(i);
  271. if (0x20 <= char && char <= 0x7e) {
  272. const entity = XMLEntities[char];
  273. if (entity) {
  274. if (start < i) {
  275. buffer.push(str.substring(start, i));
  276. }
  277. buffer.push(entity);
  278. start = i + 1;
  279. }
  280. } else {
  281. if (start < i) {
  282. buffer.push(str.substring(start, i));
  283. }
  284. buffer.push(`&#x${char.toString(16).toUpperCase()};`);
  285. if (char > 0xd7ff && (char < 0xe000 || char > 0xfffd)) {
  286. i++;
  287. }
  288. start = i + 1;
  289. }
  290. }
  291. if (buffer.length === 0) {
  292. return str;
  293. }
  294. if (start < str.length) {
  295. buffer.push(str.substring(start, str.length));
  296. }
  297. return buffer.join("");
  298. }
  299. function validateCSSFont(cssFontInfo) {
  300. const DEFAULT_CSS_FONT_OBLIQUE = "14";
  301. const DEFAULT_CSS_FONT_WEIGHT = "400";
  302. const CSS_FONT_WEIGHT_VALUES = new Set(["100", "200", "300", "400", "500", "600", "700", "800", "900", "1000", "normal", "bold", "bolder", "lighter"]);
  303. const {
  304. fontFamily,
  305. fontWeight,
  306. italicAngle
  307. } = cssFontInfo;
  308. if (/^".*"$/.test(fontFamily)) {
  309. if (/[^\\]"/.test(fontFamily.slice(1, fontFamily.length - 1))) {
  310. (0, _util.warn)(`XFA - FontFamily contains some unescaped ": ${fontFamily}.`);
  311. return false;
  312. }
  313. } else if (/^'.*'$/.test(fontFamily)) {
  314. if (/[^\\]'/.test(fontFamily.slice(1, fontFamily.length - 1))) {
  315. (0, _util.warn)(`XFA - FontFamily contains some unescaped ': ${fontFamily}.`);
  316. return false;
  317. }
  318. } else {
  319. for (const ident of fontFamily.split(/[ \t]+/)) {
  320. if (/^([0-9]|(-([0-9]|-)))/.test(ident) || !/^[a-zA-Z0-9\-_\\]+$/.test(ident)) {
  321. (0, _util.warn)(`XFA - FontFamily contains some invalid <custom-ident>: ${fontFamily}.`);
  322. return false;
  323. }
  324. }
  325. }
  326. const weight = fontWeight ? fontWeight.toString() : "";
  327. cssFontInfo.fontWeight = CSS_FONT_WEIGHT_VALUES.has(weight) ? weight : DEFAULT_CSS_FONT_WEIGHT;
  328. const angle = parseFloat(italicAngle);
  329. cssFontInfo.italicAngle = isNaN(angle) || angle < -90 || angle > 90 ? DEFAULT_CSS_FONT_OBLIQUE : italicAngle.toString();
  330. return true;
  331. }