debugger.js 19 KB

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