debugger.js 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616
  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 = 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 newArgs = [];
  345. let str = [];
  346. for (let j = 0; j < glyphs.length; j++) {
  347. const glyph = glyphs[j];
  348. if (typeof glyph === "object" && glyph !== null) {
  349. str.push(glyph.fontChar);
  350. } else {
  351. if (str.length > 0) {
  352. newArgs.push(str.join(""));
  353. str = [];
  354. }
  355. newArgs.push(glyph); // null or number
  356. }
  357. }
  358. if (str.length > 0) {
  359. newArgs.push(str.join(""));
  360. }
  361. decArgs = [newArgs];
  362. }
  363. line.appendChild(c("td", fn));
  364. line.appendChild(c("td", JSON.stringify(simplifyArgs(decArgs))));
  365. }
  366. if (operatorsToDisplay < operatorList.fnArray.length) {
  367. const lastCell = c("td", "...");
  368. lastCell.colspan = 4;
  369. chunk.appendChild(lastCell);
  370. }
  371. this.operatorListIdx = operatorList.fnArray.length;
  372. this.table.appendChild(chunk);
  373. }
  374. getNextBreakPoint() {
  375. this.breakPoints.sort(function (a, b) {
  376. return a - b;
  377. });
  378. for (let i = 0; i < this.breakPoints.length; i++) {
  379. if (this.breakPoints[i] > this.currentIdx) {
  380. return this.breakPoints[i];
  381. }
  382. }
  383. return null;
  384. }
  385. breakIt(idx, callback) {
  386. StepperManager.selectStepper(this.pageIndex, true);
  387. this.currentIdx = idx;
  388. const listener = evt => {
  389. switch (evt.keyCode) {
  390. case 83: // step
  391. document.removeEventListener("keydown", listener);
  392. this.nextBreakPoint = this.currentIdx + 1;
  393. this.goTo(-1);
  394. callback();
  395. break;
  396. case 67: // continue
  397. document.removeEventListener("keydown", listener);
  398. this.nextBreakPoint = this.getNextBreakPoint();
  399. this.goTo(-1);
  400. callback();
  401. break;
  402. }
  403. };
  404. document.addEventListener("keydown", listener);
  405. this.goTo(idx);
  406. }
  407. goTo(idx) {
  408. const allRows = this.panel.getElementsByClassName("line");
  409. for (let x = 0, xx = allRows.length; x < xx; ++x) {
  410. const row = allRows[x];
  411. if ((row.dataset.idx | 0) === idx) {
  412. row.style.backgroundColor = "rgb(251,250,207)";
  413. row.scrollIntoView();
  414. } else {
  415. row.style.backgroundColor = null;
  416. }
  417. }
  418. }
  419. }
  420. return Stepper;
  421. })();
  422. // eslint-disable-next-line no-var
  423. var Stats = (function Stats() {
  424. let stats = [];
  425. function clear(node) {
  426. while (node.hasChildNodes()) {
  427. node.removeChild(node.lastChild);
  428. }
  429. }
  430. function getStatIndex(pageNumber) {
  431. for (let i = 0, ii = stats.length; i < ii; ++i) {
  432. if (stats[i].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(pdfjsLib) {},
  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. const b = stats[statsIndex];
  455. this.panel.removeChild(b.div);
  456. stats.splice(statsIndex, 1);
  457. }
  458. const wrapper = document.createElement("div");
  459. wrapper.className = "stats";
  460. const title = document.createElement("div");
  461. title.className = "title";
  462. title.textContent = "Page: " + pageNumber;
  463. const statsDiv = document.createElement("div");
  464. statsDiv.textContent = stat.toString();
  465. wrapper.appendChild(title);
  466. wrapper.appendChild(statsDiv);
  467. stats.push({ pageNumber, div: wrapper });
  468. stats.sort(function (a, b) {
  469. return a.pageNumber - b.pageNumber;
  470. });
  471. clear(this.panel);
  472. for (let i = 0, ii = stats.length; i < ii; ++i) {
  473. this.panel.appendChild(stats[i].div);
  474. }
  475. },
  476. cleanup() {
  477. stats = [];
  478. clear(this.panel);
  479. },
  480. };
  481. })();
  482. // Manages all the debugging tools.
  483. window.PDFBug = (function PDFBugClosure() {
  484. const panelWidth = 300;
  485. const buttons = [];
  486. let activePanel = null;
  487. return {
  488. tools: [FontInspector, StepperManager, Stats],
  489. enable(ids) {
  490. const all = ids.length === 1 && ids[0] === "all";
  491. const tools = this.tools;
  492. for (let i = 0; i < tools.length; ++i) {
  493. const tool = tools[i];
  494. if (all || ids.includes(tool.id)) {
  495. tool.enabled = true;
  496. }
  497. }
  498. if (!all) {
  499. // Sort the tools by the order they are enabled.
  500. tools.sort(function (a, b) {
  501. let indexA = ids.indexOf(a.id);
  502. indexA = indexA < 0 ? tools.length : indexA;
  503. let indexB = ids.indexOf(b.id);
  504. indexB = indexB < 0 ? tools.length : indexB;
  505. return indexA - indexB;
  506. });
  507. }
  508. },
  509. init(pdfjsLib, container) {
  510. /*
  511. * Basic Layout:
  512. * PDFBug
  513. * Controls
  514. * Panels
  515. * Panel
  516. * Panel
  517. * ...
  518. */
  519. const ui = document.createElement("div");
  520. ui.id = "PDFBug";
  521. const controls = document.createElement("div");
  522. controls.setAttribute("class", "controls");
  523. ui.appendChild(controls);
  524. const panels = document.createElement("div");
  525. panels.setAttribute("class", "panels");
  526. ui.appendChild(panels);
  527. container.appendChild(ui);
  528. container.style.right = panelWidth + "px";
  529. // Initialize all the debugging tools.
  530. const tools = this.tools;
  531. const self = this;
  532. for (let i = 0; i < tools.length; ++i) {
  533. const tool = tools[i];
  534. const panel = document.createElement("div");
  535. const panelButton = document.createElement("button");
  536. panelButton.textContent = tool.name;
  537. panelButton.addEventListener(
  538. "click",
  539. (function (selected) {
  540. return function (event) {
  541. event.preventDefault();
  542. self.selectPanel(selected);
  543. };
  544. })(i)
  545. );
  546. controls.appendChild(panelButton);
  547. panels.appendChild(panel);
  548. tool.panel = panel;
  549. tool.manager = this;
  550. if (tool.enabled) {
  551. tool.init(pdfjsLib);
  552. } else {
  553. panel.textContent =
  554. tool.name +
  555. " is disabled. To enable add " +
  556. ' "' +
  557. tool.id +
  558. '" to the pdfBug parameter ' +
  559. "and refresh (separate multiple by commas).";
  560. }
  561. buttons.push(panelButton);
  562. }
  563. this.selectPanel(0);
  564. },
  565. cleanup() {
  566. for (let i = 0, ii = this.tools.length; i < ii; i++) {
  567. if (this.tools[i].enabled) {
  568. this.tools[i].cleanup();
  569. }
  570. }
  571. },
  572. selectPanel(index) {
  573. if (typeof index !== "number") {
  574. index = this.tools.indexOf(index);
  575. }
  576. if (index === activePanel) {
  577. return;
  578. }
  579. activePanel = index;
  580. const tools = this.tools;
  581. for (let j = 0; j < tools.length; ++j) {
  582. const isActive = j === index;
  583. buttons[j].classList.toggle("active", isActive);
  584. tools[j].active = isActive;
  585. tools[j].panel.hidden = !isActive;
  586. }
  587. },
  588. };
  589. })();