Nevar pievienot vairāk kā 25 tēmas Tēmai ir jāsākas ar burtu vai ciparu, tā var saturēt domu zīmes ('-') un var būt līdz 35 simboliem gara.

624 rindas
18KB

  1. /* Copyright 2012 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. const { OPS } = globalThis.pdfjsLib || (await import("pdfjs-lib"));
  16. const opMap = Object.create(null);
  17. for (const key in OPS) {
  18. opMap[OPS[key]] = key;
  19. }
  20. const FontInspector = (function FontInspectorClosure() {
  21. let fonts;
  22. let active = false;
  23. const fontAttribute = "data-font-name";
  24. function removeSelection() {
  25. const divs = document.querySelectorAll(`span[${fontAttribute}]`);
  26. for (const div of divs) {
  27. div.className = "";
  28. }
  29. }
  30. function resetSelection() {
  31. const divs = document.querySelectorAll(`span[${fontAttribute}]`);
  32. for (const div of divs) {
  33. div.className = "debuggerHideText";
  34. }
  35. }
  36. function selectFont(fontName, show) {
  37. const divs = document.querySelectorAll(
  38. `span[${fontAttribute}=${fontName}]`
  39. );
  40. for (const div of divs) {
  41. div.className = show ? "debuggerShowText" : "debuggerHideText";
  42. }
  43. }
  44. function textLayerClick(e) {
  45. if (
  46. !e.target.dataset.fontName ||
  47. e.target.tagName.toUpperCase() !== "SPAN"
  48. ) {
  49. return;
  50. }
  51. const fontName = e.target.dataset.fontName;
  52. const selects = document.getElementsByTagName("input");
  53. for (const select of selects) {
  54. if (select.dataset.fontName !== fontName) {
  55. continue;
  56. }
  57. select.checked = !select.checked;
  58. selectFont(fontName, select.checked);
  59. select.scrollIntoView();
  60. }
  61. }
  62. return {
  63. // Properties/functions needed by PDFBug.
  64. id: "FontInspector",
  65. name: "Font Inspector",
  66. panel: null,
  67. manager: null,
  68. init() {
  69. const panel = this.panel;
  70. const tmp = document.createElement("button");
  71. tmp.addEventListener("click", resetSelection);
  72. tmp.textContent = "Refresh";
  73. panel.append(tmp);
  74. fonts = document.createElement("div");
  75. panel.append(fonts);
  76. },
  77. cleanup() {
  78. fonts.textContent = "";
  79. },
  80. enabled: false,
  81. get active() {
  82. return active;
  83. },
  84. set active(value) {
  85. active = value;
  86. if (active) {
  87. document.body.addEventListener("click", textLayerClick, true);
  88. resetSelection();
  89. } else {
  90. document.body.removeEventListener("click", textLayerClick, true);
  91. removeSelection();
  92. }
  93. },
  94. // FontInspector specific functions.
  95. fontAdded(fontObj, url) {
  96. function properties(obj, list) {
  97. const moreInfo = document.createElement("table");
  98. for (const entry of list) {
  99. const tr = document.createElement("tr");
  100. const td1 = document.createElement("td");
  101. td1.textContent = entry;
  102. tr.append(td1);
  103. const td2 = document.createElement("td");
  104. td2.textContent = obj[entry].toString();
  105. tr.append(td2);
  106. moreInfo.append(tr);
  107. }
  108. return moreInfo;
  109. }
  110. const moreInfo = fontObj.css
  111. ? properties(fontObj, ["baseFontName"])
  112. : properties(fontObj, ["name", "type"]);
  113. const fontName = fontObj.loadedName;
  114. const font = document.createElement("div");
  115. const name = document.createElement("span");
  116. name.textContent = fontName;
  117. let download;
  118. if (!fontObj.css) {
  119. download = document.createElement("a");
  120. if (url) {
  121. url = /url\(['"]?([^)"']+)/.exec(url);
  122. download.href = url[1];
  123. } else if (fontObj.data) {
  124. download.href = URL.createObjectURL(
  125. new Blob([fontObj.data], { type: fontObj.mimetype })
  126. );
  127. }
  128. download.textContent = "Download";
  129. }
  130. const logIt = document.createElement("a");
  131. logIt.href = "";
  132. logIt.textContent = "Log";
  133. logIt.addEventListener("click", function (event) {
  134. event.preventDefault();
  135. console.log(fontObj);
  136. });
  137. const select = document.createElement("input");
  138. select.setAttribute("type", "checkbox");
  139. select.dataset.fontName = fontName;
  140. select.addEventListener("click", function () {
  141. selectFont(fontName, select.checked);
  142. });
  143. if (download) {
  144. font.append(select, name, " ", download, " ", logIt, moreInfo);
  145. } else {
  146. font.append(select, name, " ", logIt, moreInfo);
  147. }
  148. fonts.append(font);
  149. // Somewhat of a hack, should probably add a hook for when the text layer
  150. // is done rendering.
  151. setTimeout(() => {
  152. if (this.active) {
  153. resetSelection();
  154. }
  155. }, 2000);
  156. },
  157. };
  158. })();
  159. // Manages all the page steppers.
  160. const StepperManager = (function StepperManagerClosure() {
  161. let steppers = [];
  162. let stepperDiv = null;
  163. let stepperControls = null;
  164. let stepperChooser = null;
  165. let breakPoints = Object.create(null);
  166. return {
  167. // Properties/functions needed by PDFBug.
  168. id: "Stepper",
  169. name: "Stepper",
  170. panel: null,
  171. manager: null,
  172. init() {
  173. const self = this;
  174. stepperControls = document.createElement("div");
  175. stepperChooser = document.createElement("select");
  176. stepperChooser.addEventListener("change", function (event) {
  177. self.selectStepper(this.value);
  178. });
  179. stepperControls.append(stepperChooser);
  180. stepperDiv = document.createElement("div");
  181. this.panel.append(stepperControls, stepperDiv);
  182. if (sessionStorage.getItem("pdfjsBreakPoints")) {
  183. breakPoints = JSON.parse(sessionStorage.getItem("pdfjsBreakPoints"));
  184. }
  185. },
  186. cleanup() {
  187. stepperChooser.textContent = "";
  188. stepperDiv.textContent = "";
  189. steppers = [];
  190. },
  191. enabled: false,
  192. active: false,
  193. // Stepper specific functions.
  194. create(pageIndex) {
  195. const debug = document.createElement("div");
  196. debug.id = "stepper" + pageIndex;
  197. debug.hidden = true;
  198. debug.className = "stepper";
  199. stepperDiv.append(debug);
  200. const b = document.createElement("option");
  201. b.textContent = "Page " + (pageIndex + 1);
  202. b.value = pageIndex;
  203. stepperChooser.append(b);
  204. const initBreakPoints = breakPoints[pageIndex] || [];
  205. const stepper = new Stepper(debug, pageIndex, initBreakPoints);
  206. steppers.push(stepper);
  207. if (steppers.length === 1) {
  208. this.selectStepper(pageIndex, false);
  209. }
  210. return stepper;
  211. },
  212. selectStepper(pageIndex, selectPanel) {
  213. pageIndex |= 0;
  214. if (selectPanel) {
  215. this.manager.selectPanel(this);
  216. }
  217. for (const stepper of steppers) {
  218. stepper.panel.hidden = stepper.pageIndex !== pageIndex;
  219. }
  220. for (const option of stepperChooser.options) {
  221. option.selected = (option.value | 0) === pageIndex;
  222. }
  223. },
  224. saveBreakPoints(pageIndex, bps) {
  225. breakPoints[pageIndex] = bps;
  226. sessionStorage.setItem("pdfjsBreakPoints", JSON.stringify(breakPoints));
  227. },
  228. };
  229. })();
  230. // The stepper for each page's operatorList.
  231. class Stepper {
  232. // Shorter way to create element and optionally set textContent.
  233. #c(tag, textContent) {
  234. const d = document.createElement(tag);
  235. if (textContent) {
  236. d.textContent = textContent;
  237. }
  238. return d;
  239. }
  240. #simplifyArgs(args) {
  241. if (typeof args === "string") {
  242. const MAX_STRING_LENGTH = 75;
  243. return args.length <= MAX_STRING_LENGTH
  244. ? args
  245. : args.substring(0, MAX_STRING_LENGTH) + "...";
  246. }
  247. if (typeof args !== "object" || args === null) {
  248. return args;
  249. }
  250. if ("length" in args) {
  251. // array
  252. const MAX_ITEMS = 10,
  253. simpleArgs = [];
  254. let i, ii;
  255. for (i = 0, ii = Math.min(MAX_ITEMS, args.length); i < ii; i++) {
  256. simpleArgs.push(this.#simplifyArgs(args[i]));
  257. }
  258. if (i < args.length) {
  259. simpleArgs.push("...");
  260. }
  261. return simpleArgs;
  262. }
  263. const simpleObj = {};
  264. for (const key in args) {
  265. simpleObj[key] = this.#simplifyArgs(args[key]);
  266. }
  267. return simpleObj;
  268. }
  269. constructor(panel, pageIndex, initialBreakPoints) {
  270. this.panel = panel;
  271. this.breakPoint = 0;
  272. this.nextBreakPoint = null;
  273. this.pageIndex = pageIndex;
  274. this.breakPoints = initialBreakPoints;
  275. this.currentIdx = -1;
  276. this.operatorListIdx = 0;
  277. this.indentLevel = 0;
  278. }
  279. init(operatorList) {
  280. const panel = this.panel;
  281. const content = this.#c("div", "c=continue, s=step");
  282. const table = this.#c("table");
  283. content.append(table);
  284. table.cellSpacing = 0;
  285. const headerRow = this.#c("tr");
  286. table.append(headerRow);
  287. headerRow.append(
  288. this.#c("th", "Break"),
  289. this.#c("th", "Idx"),
  290. this.#c("th", "fn"),
  291. this.#c("th", "args")
  292. );
  293. panel.append(content);
  294. this.table = table;
  295. this.updateOperatorList(operatorList);
  296. }
  297. updateOperatorList(operatorList) {
  298. const self = this;
  299. function cboxOnClick() {
  300. const x = +this.dataset.idx;
  301. if (this.checked) {
  302. self.breakPoints.push(x);
  303. } else {
  304. self.breakPoints.splice(self.breakPoints.indexOf(x), 1);
  305. }
  306. StepperManager.saveBreakPoints(self.pageIndex, self.breakPoints);
  307. }
  308. const MAX_OPERATORS_COUNT = 15000;
  309. if (this.operatorListIdx > MAX_OPERATORS_COUNT) {
  310. return;
  311. }
  312. const chunk = document.createDocumentFragment();
  313. const operatorsToDisplay = Math.min(
  314. MAX_OPERATORS_COUNT,
  315. operatorList.fnArray.length
  316. );
  317. for (let i = this.operatorListIdx; i < operatorsToDisplay; i++) {
  318. const line = this.#c("tr");
  319. line.className = "line";
  320. line.dataset.idx = i;
  321. chunk.append(line);
  322. const checked = this.breakPoints.includes(i);
  323. const args = operatorList.argsArray[i] || [];
  324. const breakCell = this.#c("td");
  325. const cbox = this.#c("input");
  326. cbox.type = "checkbox";
  327. cbox.className = "points";
  328. cbox.checked = checked;
  329. cbox.dataset.idx = i;
  330. cbox.onclick = cboxOnClick;
  331. breakCell.append(cbox);
  332. line.append(breakCell, this.#c("td", i.toString()));
  333. const fn = opMap[operatorList.fnArray[i]];
  334. let decArgs = args;
  335. if (fn === "showText") {
  336. const glyphs = args[0];
  337. const charCodeRow = this.#c("tr");
  338. const fontCharRow = this.#c("tr");
  339. const unicodeRow = this.#c("tr");
  340. for (const glyph of glyphs) {
  341. if (typeof glyph === "object" && glyph !== null) {
  342. charCodeRow.append(this.#c("td", glyph.originalCharCode));
  343. fontCharRow.append(this.#c("td", glyph.fontChar));
  344. unicodeRow.append(this.#c("td", glyph.unicode));
  345. } else {
  346. // null or number
  347. const advanceEl = this.#c("td", glyph);
  348. advanceEl.classList.add("advance");
  349. charCodeRow.append(advanceEl);
  350. fontCharRow.append(this.#c("td"));
  351. unicodeRow.append(this.#c("td"));
  352. }
  353. }
  354. decArgs = this.#c("td");
  355. const table = this.#c("table");
  356. table.classList.add("showText");
  357. decArgs.append(table);
  358. table.append(charCodeRow, fontCharRow, unicodeRow);
  359. } else if (fn === "restore" && this.indentLevel > 0) {
  360. this.indentLevel--;
  361. }
  362. line.append(this.#c("td", " ".repeat(this.indentLevel * 2) + fn));
  363. if (fn === "save") {
  364. this.indentLevel++;
  365. }
  366. if (decArgs instanceof HTMLElement) {
  367. line.append(decArgs);
  368. } else {
  369. line.append(this.#c("td", JSON.stringify(this.#simplifyArgs(decArgs))));
  370. }
  371. }
  372. if (operatorsToDisplay < operatorList.fnArray.length) {
  373. const lastCell = this.#c("td", "...");
  374. lastCell.colspan = 4;
  375. chunk.append(lastCell);
  376. }
  377. this.operatorListIdx = operatorList.fnArray.length;
  378. this.table.append(chunk);
  379. }
  380. getNextBreakPoint() {
  381. this.breakPoints.sort(function (a, b) {
  382. return a - b;
  383. });
  384. for (const breakPoint of this.breakPoints) {
  385. if (breakPoint > this.currentIdx) {
  386. return breakPoint;
  387. }
  388. }
  389. return null;
  390. }
  391. breakIt(idx, callback) {
  392. StepperManager.selectStepper(this.pageIndex, true);
  393. this.currentIdx = idx;
  394. const listener = evt => {
  395. switch (evt.keyCode) {
  396. case 83: // step
  397. document.removeEventListener("keydown", listener);
  398. this.nextBreakPoint = this.currentIdx + 1;
  399. this.goTo(-1);
  400. callback();
  401. break;
  402. case 67: // continue
  403. document.removeEventListener("keydown", listener);
  404. this.nextBreakPoint = this.getNextBreakPoint();
  405. this.goTo(-1);
  406. callback();
  407. break;
  408. }
  409. };
  410. document.addEventListener("keydown", listener);
  411. this.goTo(idx);
  412. }
  413. goTo(idx) {
  414. const allRows = this.panel.getElementsByClassName("line");
  415. for (const row of allRows) {
  416. if ((row.dataset.idx | 0) === idx) {
  417. row.style.backgroundColor = "rgb(251,250,207)";
  418. row.scrollIntoView();
  419. } else {
  420. row.style.backgroundColor = null;
  421. }
  422. }
  423. }
  424. }
  425. const Stats = (function Stats() {
  426. let stats = [];
  427. function clear(node) {
  428. node.textContent = ""; // Remove any `node` contents from the DOM.
  429. }
  430. function getStatIndex(pageNumber) {
  431. for (const [i, stat] of stats.entries()) {
  432. if (stat.pageNumber === pageNumber) {
  433. return i;
  434. }
  435. }
  436. return false;
  437. }
  438. return {
  439. // Properties/functions needed by PDFBug.
  440. id: "Stats",
  441. name: "Stats",
  442. panel: null,
  443. manager: null,
  444. init() {},
  445. enabled: false,
  446. active: false,
  447. // Stats specific functions.
  448. add(pageNumber, stat) {
  449. if (!stat) {
  450. return;
  451. }
  452. const statsIndex = getStatIndex(pageNumber);
  453. if (statsIndex !== false) {
  454. stats[statsIndex].div.remove();
  455. stats.splice(statsIndex, 1);
  456. }
  457. const wrapper = document.createElement("div");
  458. wrapper.className = "stats";
  459. const title = document.createElement("div");
  460. title.className = "title";
  461. title.textContent = "Page: " + pageNumber;
  462. const statsDiv = document.createElement("div");
  463. statsDiv.textContent = stat.toString();
  464. wrapper.append(title, statsDiv);
  465. stats.push({ pageNumber, div: wrapper });
  466. stats.sort(function (a, b) {
  467. return a.pageNumber - b.pageNumber;
  468. });
  469. clear(this.panel);
  470. for (const entry of stats) {
  471. this.panel.append(entry.div);
  472. }
  473. },
  474. cleanup() {
  475. stats = [];
  476. clear(this.panel);
  477. },
  478. };
  479. })();
  480. // Manages all the debugging tools.
  481. class PDFBug {
  482. static #buttons = [];
  483. static #activePanel = null;
  484. static tools = [FontInspector, StepperManager, Stats];
  485. static enable(ids) {
  486. const all = ids.length === 1 && ids[0] === "all";
  487. const tools = this.tools;
  488. for (const tool of tools) {
  489. if (all || ids.includes(tool.id)) {
  490. tool.enabled = true;
  491. }
  492. }
  493. if (!all) {
  494. // Sort the tools by the order they are enabled.
  495. tools.sort(function (a, b) {
  496. let indexA = ids.indexOf(a.id);
  497. indexA = indexA < 0 ? tools.length : indexA;
  498. let indexB = ids.indexOf(b.id);
  499. indexB = indexB < 0 ? tools.length : indexB;
  500. return indexA - indexB;
  501. });
  502. }
  503. }
  504. static init(container, ids) {
  505. this.loadCSS();
  506. this.enable(ids);
  507. /*
  508. * Basic Layout:
  509. * PDFBug
  510. * Controls
  511. * Panels
  512. * Panel
  513. * Panel
  514. * ...
  515. */
  516. const ui = document.createElement("div");
  517. ui.id = "PDFBug";
  518. const controls = document.createElement("div");
  519. controls.setAttribute("class", "controls");
  520. ui.append(controls);
  521. const panels = document.createElement("div");
  522. panels.setAttribute("class", "panels");
  523. ui.append(panels);
  524. container.append(ui);
  525. container.style.right = "var(--panel-width)";
  526. // Initialize all the debugging tools.
  527. for (const tool of this.tools) {
  528. const panel = document.createElement("div");
  529. const panelButton = document.createElement("button");
  530. panelButton.textContent = tool.name;
  531. panelButton.addEventListener("click", event => {
  532. event.preventDefault();
  533. this.selectPanel(tool);
  534. });
  535. controls.append(panelButton);
  536. panels.append(panel);
  537. tool.panel = panel;
  538. tool.manager = this;
  539. if (tool.enabled) {
  540. tool.init();
  541. } else {
  542. panel.textContent =
  543. `${tool.name} is disabled. To enable add "${tool.id}" to ` +
  544. "the pdfBug parameter and refresh (separate multiple by commas).";
  545. }
  546. this.#buttons.push(panelButton);
  547. }
  548. this.selectPanel(0);
  549. }
  550. static loadCSS() {
  551. const { url } = import.meta;
  552. const link = document.createElement("link");
  553. link.rel = "stylesheet";
  554. link.href = url.replace(/\.mjs$/, ".css");
  555. document.head.append(link);
  556. }
  557. static cleanup() {
  558. for (const tool of this.tools) {
  559. if (tool.enabled) {
  560. tool.cleanup();
  561. }
  562. }
  563. }
  564. static selectPanel(index) {
  565. if (typeof index !== "number") {
  566. index = this.tools.indexOf(index);
  567. }
  568. if (index === this.#activePanel) {
  569. return;
  570. }
  571. this.#activePanel = index;
  572. for (const [j, tool] of this.tools.entries()) {
  573. const isActive = j === index;
  574. this.#buttons[j].classList.toggle("active", isActive);
  575. tool.active = isActive;
  576. tool.panel.hidden = !isActive;
  577. }
  578. }
  579. }
  580. globalThis.FontInspector = FontInspector;
  581. globalThis.StepperManager = StepperManager;
  582. globalThis.Stats = Stats;
  583. export { PDFBug };