debugger.js 19 KB

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