debugger.js 19 KB

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