debugger.js 18 KB

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