debugger.js 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627
  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. }
  287. init(operatorList) {
  288. const panel = this.panel;
  289. const content = c("div", "c=continue, s=step");
  290. const table = c("table");
  291. content.appendChild(table);
  292. table.cellSpacing = 0;
  293. const headerRow = c("tr");
  294. table.appendChild(headerRow);
  295. headerRow.appendChild(c("th", "Break"));
  296. headerRow.appendChild(c("th", "Idx"));
  297. headerRow.appendChild(c("th", "fn"));
  298. headerRow.appendChild(c("th", "args"));
  299. panel.appendChild(content);
  300. this.table = table;
  301. this.updateOperatorList(operatorList);
  302. }
  303. updateOperatorList(operatorList) {
  304. const self = this;
  305. function cboxOnClick() {
  306. const x = +this.dataset.idx;
  307. if (this.checked) {
  308. self.breakPoints.push(x);
  309. } else {
  310. self.breakPoints.splice(self.breakPoints.indexOf(x), 1);
  311. }
  312. StepperManager.saveBreakPoints(self.pageIndex, self.breakPoints);
  313. }
  314. const MAX_OPERATORS_COUNT = 15000;
  315. if (this.operatorListIdx > MAX_OPERATORS_COUNT) {
  316. return;
  317. }
  318. const chunk = document.createDocumentFragment();
  319. const operatorsToDisplay = Math.min(
  320. MAX_OPERATORS_COUNT,
  321. operatorList.fnArray.length
  322. );
  323. for (let i = this.operatorListIdx; i < operatorsToDisplay; i++) {
  324. const line = c("tr");
  325. line.className = "line";
  326. line.dataset.idx = i;
  327. chunk.appendChild(line);
  328. const checked = this.breakPoints.includes(i);
  329. const args = operatorList.argsArray[i] || [];
  330. const breakCell = c("td");
  331. const cbox = c("input");
  332. cbox.type = "checkbox";
  333. cbox.className = "points";
  334. cbox.checked = checked;
  335. cbox.dataset.idx = i;
  336. cbox.onclick = cboxOnClick;
  337. breakCell.appendChild(cbox);
  338. line.appendChild(breakCell);
  339. line.appendChild(c("td", i.toString()));
  340. const fn = opMap[operatorList.fnArray[i]];
  341. let decArgs = args;
  342. if (fn === "showText") {
  343. const glyphs = args[0];
  344. const charCodeRow = c("tr");
  345. const fontCharRow = c("tr");
  346. const unicodeRow = c("tr");
  347. for (let j = 0; j < glyphs.length; j++) {
  348. const glyph = glyphs[j];
  349. if (typeof glyph === "object" && glyph !== null) {
  350. charCodeRow.appendChild(c("td", glyph.originalCharCode));
  351. fontCharRow.appendChild(c("td", glyph.fontChar));
  352. unicodeRow.appendChild(c("td", glyph.unicode));
  353. } else {
  354. // null or number
  355. const advanceEl = c("td", glyph);
  356. advanceEl.classList.add("advance");
  357. charCodeRow.appendChild(advanceEl);
  358. fontCharRow.appendChild(c("td"));
  359. unicodeRow.appendChild(c("td"));
  360. }
  361. }
  362. decArgs = c("td");
  363. const table = c("table");
  364. table.classList.add("showText");
  365. decArgs.appendChild(table);
  366. table.appendChild(charCodeRow);
  367. table.appendChild(fontCharRow);
  368. table.appendChild(unicodeRow);
  369. }
  370. line.appendChild(c("td", fn));
  371. if (decArgs instanceof HTMLElement) {
  372. line.appendChild(decArgs);
  373. } else {
  374. line.appendChild(c("td", JSON.stringify(simplifyArgs(decArgs))));
  375. }
  376. }
  377. if (operatorsToDisplay < operatorList.fnArray.length) {
  378. const lastCell = c("td", "...");
  379. lastCell.colspan = 4;
  380. chunk.appendChild(lastCell);
  381. }
  382. this.operatorListIdx = operatorList.fnArray.length;
  383. this.table.appendChild(chunk);
  384. }
  385. getNextBreakPoint() {
  386. this.breakPoints.sort(function (a, b) {
  387. return a - b;
  388. });
  389. for (let i = 0; i < this.breakPoints.length; i++) {
  390. if (this.breakPoints[i] > this.currentIdx) {
  391. return this.breakPoints[i];
  392. }
  393. }
  394. return null;
  395. }
  396. breakIt(idx, callback) {
  397. StepperManager.selectStepper(this.pageIndex, true);
  398. this.currentIdx = idx;
  399. const listener = evt => {
  400. switch (evt.keyCode) {
  401. case 83: // step
  402. document.removeEventListener("keydown", listener);
  403. this.nextBreakPoint = this.currentIdx + 1;
  404. this.goTo(-1);
  405. callback();
  406. break;
  407. case 67: // continue
  408. document.removeEventListener("keydown", listener);
  409. this.nextBreakPoint = this.getNextBreakPoint();
  410. this.goTo(-1);
  411. callback();
  412. break;
  413. }
  414. };
  415. document.addEventListener("keydown", listener);
  416. this.goTo(idx);
  417. }
  418. goTo(idx) {
  419. const allRows = this.panel.getElementsByClassName("line");
  420. for (let x = 0, xx = allRows.length; x < xx; ++x) {
  421. const row = allRows[x];
  422. if ((row.dataset.idx | 0) === idx) {
  423. row.style.backgroundColor = "rgb(251,250,207)";
  424. row.scrollIntoView();
  425. } else {
  426. row.style.backgroundColor = null;
  427. }
  428. }
  429. }
  430. }
  431. return Stepper;
  432. })();
  433. // eslint-disable-next-line no-var
  434. var Stats = (function Stats() {
  435. let stats = [];
  436. function clear(node) {
  437. while (node.hasChildNodes()) {
  438. node.removeChild(node.lastChild);
  439. }
  440. }
  441. function getStatIndex(pageNumber) {
  442. for (let i = 0, ii = stats.length; i < ii; ++i) {
  443. if (stats[i].pageNumber === pageNumber) {
  444. return i;
  445. }
  446. }
  447. return false;
  448. }
  449. return {
  450. // Properties/functions needed by PDFBug.
  451. id: "Stats",
  452. name: "Stats",
  453. panel: null,
  454. manager: null,
  455. init(pdfjsLib) {},
  456. enabled: false,
  457. active: false,
  458. // Stats specific functions.
  459. add(pageNumber, stat) {
  460. if (!stat) {
  461. return;
  462. }
  463. const statsIndex = getStatIndex(pageNumber);
  464. if (statsIndex !== false) {
  465. const b = stats[statsIndex];
  466. this.panel.removeChild(b.div);
  467. stats.splice(statsIndex, 1);
  468. }
  469. const wrapper = document.createElement("div");
  470. wrapper.className = "stats";
  471. const title = document.createElement("div");
  472. title.className = "title";
  473. title.textContent = "Page: " + pageNumber;
  474. const statsDiv = document.createElement("div");
  475. statsDiv.textContent = stat.toString();
  476. wrapper.appendChild(title);
  477. wrapper.appendChild(statsDiv);
  478. stats.push({ pageNumber, div: wrapper });
  479. stats.sort(function (a, b) {
  480. return a.pageNumber - b.pageNumber;
  481. });
  482. clear(this.panel);
  483. for (let i = 0, ii = stats.length; i < ii; ++i) {
  484. this.panel.appendChild(stats[i].div);
  485. }
  486. },
  487. cleanup() {
  488. stats = [];
  489. clear(this.panel);
  490. },
  491. };
  492. })();
  493. // Manages all the debugging tools.
  494. window.PDFBug = (function PDFBugClosure() {
  495. const panelWidth = 300;
  496. const buttons = [];
  497. let activePanel = null;
  498. return {
  499. tools: [FontInspector, StepperManager, Stats],
  500. enable(ids) {
  501. const all = ids.length === 1 && ids[0] === "all";
  502. const tools = this.tools;
  503. for (let i = 0; i < tools.length; ++i) {
  504. const tool = tools[i];
  505. if (all || ids.includes(tool.id)) {
  506. tool.enabled = true;
  507. }
  508. }
  509. if (!all) {
  510. // Sort the tools by the order they are enabled.
  511. tools.sort(function (a, b) {
  512. let indexA = ids.indexOf(a.id);
  513. indexA = indexA < 0 ? tools.length : indexA;
  514. let indexB = ids.indexOf(b.id);
  515. indexB = indexB < 0 ? tools.length : indexB;
  516. return indexA - indexB;
  517. });
  518. }
  519. },
  520. init(pdfjsLib, container) {
  521. /*
  522. * Basic Layout:
  523. * PDFBug
  524. * Controls
  525. * Panels
  526. * Panel
  527. * Panel
  528. * ...
  529. */
  530. const ui = document.createElement("div");
  531. ui.id = "PDFBug";
  532. const controls = document.createElement("div");
  533. controls.setAttribute("class", "controls");
  534. ui.appendChild(controls);
  535. const panels = document.createElement("div");
  536. panels.setAttribute("class", "panels");
  537. ui.appendChild(panels);
  538. container.appendChild(ui);
  539. container.style.right = panelWidth + "px";
  540. // Initialize all the debugging tools.
  541. const tools = this.tools;
  542. const self = this;
  543. for (let i = 0; i < tools.length; ++i) {
  544. const tool = tools[i];
  545. const panel = document.createElement("div");
  546. const panelButton = document.createElement("button");
  547. panelButton.textContent = tool.name;
  548. panelButton.addEventListener(
  549. "click",
  550. (function (selected) {
  551. return function (event) {
  552. event.preventDefault();
  553. self.selectPanel(selected);
  554. };
  555. })(i)
  556. );
  557. controls.appendChild(panelButton);
  558. panels.appendChild(panel);
  559. tool.panel = panel;
  560. tool.manager = this;
  561. if (tool.enabled) {
  562. tool.init(pdfjsLib);
  563. } else {
  564. panel.textContent =
  565. tool.name +
  566. " is disabled. To enable add " +
  567. ' "' +
  568. tool.id +
  569. '" to the pdfBug parameter ' +
  570. "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. })();