debugger.mjs 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619
  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((a, b) => a - b);
  382. for (const breakPoint of this.breakPoints) {
  383. if (breakPoint > this.currentIdx) {
  384. return breakPoint;
  385. }
  386. }
  387. return null;
  388. }
  389. breakIt(idx, callback) {
  390. StepperManager.selectStepper(this.pageIndex, true);
  391. this.currentIdx = idx;
  392. const listener = evt => {
  393. switch (evt.keyCode) {
  394. case 83: // step
  395. document.removeEventListener("keydown", listener);
  396. this.nextBreakPoint = this.currentIdx + 1;
  397. this.goTo(-1);
  398. callback();
  399. break;
  400. case 67: // continue
  401. document.removeEventListener("keydown", listener);
  402. this.nextBreakPoint = this.getNextBreakPoint();
  403. this.goTo(-1);
  404. callback();
  405. break;
  406. }
  407. };
  408. document.addEventListener("keydown", listener);
  409. this.goTo(idx);
  410. }
  411. goTo(idx) {
  412. const allRows = this.panel.getElementsByClassName("line");
  413. for (const row of allRows) {
  414. if ((row.dataset.idx | 0) === idx) {
  415. row.style.backgroundColor = "rgb(251,250,207)";
  416. row.scrollIntoView();
  417. } else {
  418. row.style.backgroundColor = null;
  419. }
  420. }
  421. }
  422. }
  423. const Stats = (function Stats() {
  424. let stats = [];
  425. function clear(node) {
  426. node.textContent = ""; // Remove any `node` contents from the DOM.
  427. }
  428. function getStatIndex(pageNumber) {
  429. for (const [i, stat] of stats.entries()) {
  430. if (stat.pageNumber === pageNumber) {
  431. return i;
  432. }
  433. }
  434. return false;
  435. }
  436. return {
  437. // Properties/functions needed by PDFBug.
  438. id: "Stats",
  439. name: "Stats",
  440. panel: null,
  441. manager: null,
  442. init() {},
  443. enabled: false,
  444. active: false,
  445. // Stats specific functions.
  446. add(pageNumber, stat) {
  447. if (!stat) {
  448. return;
  449. }
  450. const statsIndex = getStatIndex(pageNumber);
  451. if (statsIndex !== false) {
  452. stats[statsIndex].div.remove();
  453. stats.splice(statsIndex, 1);
  454. }
  455. const wrapper = document.createElement("div");
  456. wrapper.className = "stats";
  457. const title = document.createElement("div");
  458. title.className = "title";
  459. title.textContent = "Page: " + pageNumber;
  460. const statsDiv = document.createElement("div");
  461. statsDiv.textContent = stat.toString();
  462. wrapper.append(title, statsDiv);
  463. stats.push({ pageNumber, div: wrapper });
  464. stats.sort((a, b) => a.pageNumber - b.pageNumber);
  465. clear(this.panel);
  466. for (const entry of stats) {
  467. this.panel.append(entry.div);
  468. }
  469. },
  470. cleanup() {
  471. stats = [];
  472. clear(this.panel);
  473. },
  474. };
  475. })();
  476. // Manages all the debugging tools.
  477. class PDFBug {
  478. static #buttons = [];
  479. static #activePanel = null;
  480. static tools = [FontInspector, StepperManager, Stats];
  481. static enable(ids) {
  482. const all = ids.length === 1 && ids[0] === "all";
  483. const tools = this.tools;
  484. for (const tool of tools) {
  485. if (all || ids.includes(tool.id)) {
  486. tool.enabled = true;
  487. }
  488. }
  489. if (!all) {
  490. // Sort the tools by the order they are enabled.
  491. tools.sort(function (a, b) {
  492. let indexA = ids.indexOf(a.id);
  493. indexA = indexA < 0 ? tools.length : indexA;
  494. let indexB = ids.indexOf(b.id);
  495. indexB = indexB < 0 ? tools.length : indexB;
  496. return indexA - indexB;
  497. });
  498. }
  499. }
  500. static init(container, ids) {
  501. this.loadCSS();
  502. this.enable(ids);
  503. /*
  504. * Basic Layout:
  505. * PDFBug
  506. * Controls
  507. * Panels
  508. * Panel
  509. * Panel
  510. * ...
  511. */
  512. const ui = document.createElement("div");
  513. ui.id = "PDFBug";
  514. const controls = document.createElement("div");
  515. controls.setAttribute("class", "controls");
  516. ui.append(controls);
  517. const panels = document.createElement("div");
  518. panels.setAttribute("class", "panels");
  519. ui.append(panels);
  520. container.append(ui);
  521. container.style.right = "var(--panel-width)";
  522. // Initialize all the debugging tools.
  523. for (const tool of this.tools) {
  524. const panel = document.createElement("div");
  525. const panelButton = document.createElement("button");
  526. panelButton.textContent = tool.name;
  527. panelButton.addEventListener("click", event => {
  528. event.preventDefault();
  529. this.selectPanel(tool);
  530. });
  531. controls.append(panelButton);
  532. panels.append(panel);
  533. tool.panel = panel;
  534. tool.manager = this;
  535. if (tool.enabled) {
  536. tool.init();
  537. } else {
  538. panel.textContent =
  539. `${tool.name} is disabled. To enable add "${tool.id}" to ` +
  540. "the pdfBug parameter and refresh (separate multiple by commas).";
  541. }
  542. this.#buttons.push(panelButton);
  543. }
  544. this.selectPanel(0);
  545. }
  546. static loadCSS() {
  547. const { url } = import.meta;
  548. const link = document.createElement("link");
  549. link.rel = "stylesheet";
  550. link.href = url.replace(/\.mjs$/, ".css");
  551. document.head.append(link);
  552. }
  553. static cleanup() {
  554. for (const tool of this.tools) {
  555. if (tool.enabled) {
  556. tool.cleanup();
  557. }
  558. }
  559. }
  560. static selectPanel(index) {
  561. if (typeof index !== "number") {
  562. index = this.tools.indexOf(index);
  563. }
  564. if (index === this.#activePanel) {
  565. return;
  566. }
  567. this.#activePanel = index;
  568. for (const [j, tool] of this.tools.entries()) {
  569. const isActive = j === index;
  570. this.#buttons[j].classList.toggle("active", isActive);
  571. tool.active = isActive;
  572. tool.panel.hidden = !isActive;
  573. }
  574. }
  575. }
  576. globalThis.FontInspector = FontInspector;
  577. globalThis.StepperManager = StepperManager;
  578. globalThis.Stats = Stats;
  579. export { PDFBug };