PageRenderTime 101ms CodeModel.GetById 20ms RepoModel.GetById 0ms app.codeStats 2ms

/libs/pdf.js/1.0.1040/viewer.js

https://gitlab.com/mba811/static
JavaScript | 6952 lines | 5293 code | 862 blank | 797 comment | 863 complexity | 1824a6c2b1d7f8f9134f78b7d79ca9e1 MD5 | raw file
Possible License(s): BSD-3-Clause, Apache-2.0
  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, PDFBug, FirefoxCom, Stats, Cache, ProgressBar,
  18. DownloadManager, getFileName, scrollIntoView, getPDFFileNameFromURL,
  19. PDFHistory, Preferences, SidebarView, ViewHistory, PageView,
  20. PDFThumbnailViewer, URL, noContextMenuHandler, SecondaryToolbar,
  21. PasswordPrompt, PresentationMode, HandTool, Promise,
  22. DocumentProperties, DocumentOutlineView, DocumentAttachmentsView,
  23. OverlayManager, PDFFindController, PDFFindBar, getVisibleElements,
  24. watchScroll, PDFViewer, PDFRenderingQueue, PresentationModeState,
  25. RenderingStates, DEFAULT_SCALE, UNKNOWN_SCALE,
  26. IGNORE_CURRENT_POSITION_ON_ZOOM: true */
  27. 'use strict';
  28. var DEFAULT_URL = 'compressed.tracemonkey-pldi-09.pdf';
  29. var DEFAULT_SCALE_DELTA = 1.1;
  30. var MIN_SCALE = 0.25;
  31. var MAX_SCALE = 10.0;
  32. var VIEW_HISTORY_MEMORY = 20;
  33. var SCALE_SELECT_CONTAINER_PADDING = 8;
  34. var SCALE_SELECT_PADDING = 22;
  35. var PAGE_NUMBER_LOADING_INDICATOR = 'visiblePageIsLoading';
  36. var DISABLE_AUTO_FETCH_LOADING_BAR_TIMEOUT = 5000;
  37. PDFJS.imageResourcesPath = './images/';
  38. PDFJS.workerSrc = '../build/pdf.worker.js';
  39. PDFJS.cMapUrl = '../web/cmaps/';
  40. PDFJS.cMapPacked = true;
  41. var mozL10n = document.mozL10n || document.webL10n;
  42. var CSS_UNITS = 96.0 / 72.0;
  43. var DEFAULT_SCALE = 'auto';
  44. var UNKNOWN_SCALE = 0;
  45. var MAX_AUTO_SCALE = 1.25;
  46. var SCROLLBAR_PADDING = 40;
  47. var VERTICAL_PADDING = 5;
  48. var DEFAULT_CACHE_SIZE = 10;
  49. // optimised CSS custom property getter/setter
  50. var CustomStyle = (function CustomStyleClosure() {
  51. // As noted on: http://www.zachstronaut.com/posts/2009/02/17/
  52. // animate-css-transforms-firefox-webkit.html
  53. // in some versions of IE9 it is critical that ms appear in this list
  54. // before Moz
  55. var prefixes = ['ms', 'Moz', 'Webkit', 'O'];
  56. var _cache = {};
  57. function CustomStyle() {}
  58. CustomStyle.getProp = function get(propName, element) {
  59. // check cache only when no element is given
  60. if (arguments.length === 1 && typeof _cache[propName] === 'string') {
  61. return _cache[propName];
  62. }
  63. element = element || document.documentElement;
  64. var style = element.style, prefixed, uPropName;
  65. // test standard property first
  66. if (typeof style[propName] === 'string') {
  67. return (_cache[propName] = propName);
  68. }
  69. // capitalize
  70. uPropName = propName.charAt(0).toUpperCase() + propName.slice(1);
  71. // test vendor specific properties
  72. for (var i = 0, l = prefixes.length; i < l; i++) {
  73. prefixed = prefixes[i] + uPropName;
  74. if (typeof style[prefixed] === 'string') {
  75. return (_cache[propName] = prefixed);
  76. }
  77. }
  78. //if all fails then set to undefined
  79. return (_cache[propName] = 'undefined');
  80. };
  81. CustomStyle.setProp = function set(propName, element, str) {
  82. var prop = this.getProp(propName);
  83. if (prop !== 'undefined') {
  84. element.style[prop] = str;
  85. }
  86. };
  87. return CustomStyle;
  88. })();
  89. function getFileName(url) {
  90. var anchor = url.indexOf('#');
  91. var query = url.indexOf('?');
  92. var end = Math.min(
  93. anchor > 0 ? anchor : url.length,
  94. query > 0 ? query : url.length);
  95. return url.substring(url.lastIndexOf('/', end) + 1, end);
  96. }
  97. /**
  98. * Returns scale factor for the canvas. It makes sense for the HiDPI displays.
  99. * @return {Object} The object with horizontal (sx) and vertical (sy)
  100. scales. The scaled property is set to false if scaling is
  101. not required, true otherwise.
  102. */
  103. function getOutputScale(ctx) {
  104. var devicePixelRatio = window.devicePixelRatio || 1;
  105. var backingStoreRatio = ctx.webkitBackingStorePixelRatio ||
  106. ctx.mozBackingStorePixelRatio ||
  107. ctx.msBackingStorePixelRatio ||
  108. ctx.oBackingStorePixelRatio ||
  109. ctx.backingStorePixelRatio || 1;
  110. var pixelRatio = devicePixelRatio / backingStoreRatio;
  111. return {
  112. sx: pixelRatio,
  113. sy: pixelRatio,
  114. scaled: pixelRatio !== 1
  115. };
  116. }
  117. /**
  118. * Scrolls specified element into view of its parent.
  119. * element {Object} The element to be visible.
  120. * spot {Object} An object with optional top and left properties,
  121. * specifying the offset from the top left edge.
  122. */
  123. function scrollIntoView(element, spot) {
  124. // Assuming offsetParent is available (it's not available when viewer is in
  125. // hidden iframe or object). We have to scroll: if the offsetParent is not set
  126. // producing the error. See also animationStartedClosure.
  127. var parent = element.offsetParent;
  128. var offsetY = element.offsetTop + element.clientTop;
  129. var offsetX = element.offsetLeft + element.clientLeft;
  130. if (!parent) {
  131. console.error('offsetParent is not set -- cannot scroll');
  132. return;
  133. }
  134. while (parent.clientHeight === parent.scrollHeight) {
  135. if (parent.dataset._scaleY) {
  136. offsetY /= parent.dataset._scaleY;
  137. offsetX /= parent.dataset._scaleX;
  138. }
  139. offsetY += parent.offsetTop;
  140. offsetX += parent.offsetLeft;
  141. parent = parent.offsetParent;
  142. if (!parent) {
  143. return; // no need to scroll
  144. }
  145. }
  146. if (spot) {
  147. if (spot.top !== undefined) {
  148. offsetY += spot.top;
  149. }
  150. if (spot.left !== undefined) {
  151. offsetX += spot.left;
  152. parent.scrollLeft = offsetX;
  153. }
  154. }
  155. parent.scrollTop = offsetY;
  156. }
  157. /**
  158. * Helper function to start monitoring the scroll event and converting them into
  159. * PDF.js friendly one: with scroll debounce and scroll direction.
  160. */
  161. function watchScroll(viewAreaElement, callback) {
  162. var debounceScroll = function debounceScroll(evt) {
  163. if (rAF) {
  164. return;
  165. }
  166. // schedule an invocation of scroll for next animation frame.
  167. rAF = window.requestAnimationFrame(function viewAreaElementScrolled() {
  168. rAF = null;
  169. var currentY = viewAreaElement.scrollTop;
  170. var lastY = state.lastY;
  171. if (currentY > lastY) {
  172. state.down = true;
  173. } else if (currentY < lastY) {
  174. state.down = false;
  175. }
  176. state.lastY = currentY;
  177. // else do nothing and use previous value
  178. callback(state);
  179. });
  180. };
  181. var state = {
  182. down: true,
  183. lastY: viewAreaElement.scrollTop,
  184. _eventHandler: debounceScroll
  185. };
  186. var rAF = null;
  187. viewAreaElement.addEventListener('scroll', debounceScroll, true);
  188. return state;
  189. }
  190. /**
  191. * Generic helper to find out what elements are visible within a scroll pane.
  192. */
  193. function getVisibleElements(scrollEl, views, sortByVisibility) {
  194. var top = scrollEl.scrollTop, bottom = top + scrollEl.clientHeight;
  195. var left = scrollEl.scrollLeft, right = left + scrollEl.clientWidth;
  196. var visible = [], view;
  197. var currentHeight, viewHeight, hiddenHeight, percentHeight;
  198. var currentWidth, viewWidth;
  199. for (var i = 0, ii = views.length; i < ii; ++i) {
  200. view = views[i];
  201. currentHeight = view.el.offsetTop + view.el.clientTop;
  202. viewHeight = view.el.clientHeight;
  203. if ((currentHeight + viewHeight) < top) {
  204. continue;
  205. }
  206. if (currentHeight > bottom) {
  207. break;
  208. }
  209. currentWidth = view.el.offsetLeft + view.el.clientLeft;
  210. viewWidth = view.el.clientWidth;
  211. if ((currentWidth + viewWidth) < left || currentWidth > right) {
  212. continue;
  213. }
  214. hiddenHeight = Math.max(0, top - currentHeight) +
  215. Math.max(0, currentHeight + viewHeight - bottom);
  216. percentHeight = ((viewHeight - hiddenHeight) * 100 / viewHeight) | 0;
  217. visible.push({ id: view.id, x: currentWidth, y: currentHeight,
  218. view: view, percent: percentHeight });
  219. }
  220. var first = visible[0];
  221. var last = visible[visible.length - 1];
  222. if (sortByVisibility) {
  223. visible.sort(function(a, b) {
  224. var pc = a.percent - b.percent;
  225. if (Math.abs(pc) > 0.001) {
  226. return -pc;
  227. }
  228. return a.id - b.id; // ensure stability
  229. });
  230. }
  231. return {first: first, last: last, views: visible};
  232. }
  233. /**
  234. * Event handler to suppress context menu.
  235. */
  236. function noContextMenuHandler(e) {
  237. e.preventDefault();
  238. }
  239. /**
  240. * Returns the filename or guessed filename from the url (see issue 3455).
  241. * url {String} The original PDF location.
  242. * @return {String} Guessed PDF file name.
  243. */
  244. function getPDFFileNameFromURL(url) {
  245. var reURI = /^(?:([^:]+:)?\/\/[^\/]+)?([^?#]*)(\?[^#]*)?(#.*)?$/;
  246. // SCHEME HOST 1.PATH 2.QUERY 3.REF
  247. // Pattern to get last matching NAME.pdf
  248. var reFilename = /[^\/?#=]+\.pdf\b(?!.*\.pdf\b)/i;
  249. var splitURI = reURI.exec(url);
  250. var suggestedFilename = reFilename.exec(splitURI[1]) ||
  251. reFilename.exec(splitURI[2]) ||
  252. reFilename.exec(splitURI[3]);
  253. if (suggestedFilename) {
  254. suggestedFilename = suggestedFilename[0];
  255. if (suggestedFilename.indexOf('%') !== -1) {
  256. // URL-encoded %2Fpath%2Fto%2Ffile.pdf should be file.pdf
  257. try {
  258. suggestedFilename =
  259. reFilename.exec(decodeURIComponent(suggestedFilename))[0];
  260. } catch(e) { // Possible (extremely rare) errors:
  261. // URIError "Malformed URI", e.g. for "%AA.pdf"
  262. // TypeError "null has no properties", e.g. for "%2F.pdf"
  263. }
  264. }
  265. }
  266. return suggestedFilename || 'document.pdf';
  267. }
  268. var ProgressBar = (function ProgressBarClosure() {
  269. function clamp(v, min, max) {
  270. return Math.min(Math.max(v, min), max);
  271. }
  272. function ProgressBar(id, opts) {
  273. this.visible = true;
  274. // Fetch the sub-elements for later.
  275. this.div = document.querySelector(id + ' .progress');
  276. // Get the loading bar element, so it can be resized to fit the viewer.
  277. this.bar = this.div.parentNode;
  278. // Get options, with sensible defaults.
  279. this.height = opts.height || 100;
  280. this.width = opts.width || 100;
  281. this.units = opts.units || '%';
  282. // Initialize heights.
  283. this.div.style.height = this.height + this.units;
  284. this.percent = 0;
  285. }
  286. ProgressBar.prototype = {
  287. updateBar: function ProgressBar_updateBar() {
  288. if (this._indeterminate) {
  289. this.div.classList.add('indeterminate');
  290. this.div.style.width = this.width + this.units;
  291. return;
  292. }
  293. this.div.classList.remove('indeterminate');
  294. var progressSize = this.width * this._percent / 100;
  295. this.div.style.width = progressSize + this.units;
  296. },
  297. get percent() {
  298. return this._percent;
  299. },
  300. set percent(val) {
  301. this._indeterminate = isNaN(val);
  302. this._percent = clamp(val, 0, 100);
  303. this.updateBar();
  304. },
  305. setWidth: function ProgressBar_setWidth(viewer) {
  306. if (viewer) {
  307. var container = viewer.parentNode;
  308. var scrollbarWidth = container.offsetWidth - viewer.offsetWidth;
  309. if (scrollbarWidth > 0) {
  310. this.bar.setAttribute('style', 'width: calc(100% - ' +
  311. scrollbarWidth + 'px);');
  312. }
  313. }
  314. },
  315. hide: function ProgressBar_hide() {
  316. if (!this.visible) {
  317. return;
  318. }
  319. this.visible = false;
  320. this.bar.classList.add('hidden');
  321. document.body.classList.remove('loadingInProgress');
  322. },
  323. show: function ProgressBar_show() {
  324. if (this.visible) {
  325. return;
  326. }
  327. this.visible = true;
  328. document.body.classList.add('loadingInProgress');
  329. this.bar.classList.remove('hidden');
  330. }
  331. };
  332. return ProgressBar;
  333. })();
  334. var Cache = function cacheCache(size) {
  335. var data = [];
  336. this.push = function cachePush(view) {
  337. var i = data.indexOf(view);
  338. if (i >= 0) {
  339. data.splice(i, 1);
  340. }
  341. data.push(view);
  342. if (data.length > size) {
  343. data.shift().destroy();
  344. }
  345. };
  346. this.resize = function (newSize) {
  347. size = newSize;
  348. while (data.length > size) {
  349. data.shift().destroy();
  350. }
  351. };
  352. };
  353. var DEFAULT_PREFERENCES = {
  354. showPreviousViewOnLoad: true,
  355. defaultZoomValue: '',
  356. sidebarViewOnLoad: 0,
  357. enableHandToolOnLoad: false,
  358. enableWebGL: false,
  359. pdfBugEnabled: false,
  360. disableRange: false,
  361. disableStream: false,
  362. disableAutoFetch: false,
  363. disableFontFace: false,
  364. disableTextLayer: false,
  365. useOnlyCssZoom: false
  366. };
  367. var SidebarView = {
  368. NONE: 0,
  369. THUMBS: 1,
  370. OUTLINE: 2,
  371. ATTACHMENTS: 3
  372. };
  373. /**
  374. * Preferences - Utility for storing persistent settings.
  375. * Used for settings that should be applied to all opened documents,
  376. * or every time the viewer is loaded.
  377. */
  378. var Preferences = {
  379. prefs: Object.create(DEFAULT_PREFERENCES),
  380. isInitializedPromiseResolved: false,
  381. initializedPromise: null,
  382. /**
  383. * Initialize and fetch the current preference values from storage.
  384. * @return {Promise} A promise that is resolved when the preferences
  385. * have been initialized.
  386. */
  387. initialize: function preferencesInitialize() {
  388. return this.initializedPromise =
  389. this._readFromStorage(DEFAULT_PREFERENCES).then(function(prefObj) {
  390. this.isInitializedPromiseResolved = true;
  391. if (prefObj) {
  392. this.prefs = prefObj;
  393. }
  394. }.bind(this));
  395. },
  396. /**
  397. * Stub function for writing preferences to storage.
  398. * NOTE: This should be overridden by a build-specific function defined below.
  399. * @param {Object} prefObj The preferences that should be written to storage.
  400. * @return {Promise} A promise that is resolved when the preference values
  401. * have been written.
  402. */
  403. _writeToStorage: function preferences_writeToStorage(prefObj) {
  404. return Promise.resolve();
  405. },
  406. /**
  407. * Stub function for reading preferences from storage.
  408. * NOTE: This should be overridden by a build-specific function defined below.
  409. * @param {Object} prefObj The preferences that should be read from storage.
  410. * @return {Promise} A promise that is resolved with an {Object} containing
  411. * the preferences that have been read.
  412. */
  413. _readFromStorage: function preferences_readFromStorage(prefObj) {
  414. return Promise.resolve();
  415. },
  416. /**
  417. * Reset the preferences to their default values and update storage.
  418. * @return {Promise} A promise that is resolved when the preference values
  419. * have been reset.
  420. */
  421. reset: function preferencesReset() {
  422. return this.initializedPromise.then(function() {
  423. this.prefs = Object.create(DEFAULT_PREFERENCES);
  424. return this._writeToStorage(DEFAULT_PREFERENCES);
  425. }.bind(this));
  426. },
  427. /**
  428. * Replace the current preference values with the ones from storage.
  429. * @return {Promise} A promise that is resolved when the preference values
  430. * have been updated.
  431. */
  432. reload: function preferencesReload() {
  433. return this.initializedPromise.then(function () {
  434. this._readFromStorage(DEFAULT_PREFERENCES).then(function(prefObj) {
  435. if (prefObj) {
  436. this.prefs = prefObj;
  437. }
  438. }.bind(this));
  439. }.bind(this));
  440. },
  441. /**
  442. * Set the value of a preference.
  443. * @param {string} name The name of the preference that should be changed.
  444. * @param {boolean|number|string} value The new value of the preference.
  445. * @return {Promise} A promise that is resolved when the value has been set,
  446. * provided that the preference exists and the types match.
  447. */
  448. set: function preferencesSet(name, value) {
  449. return this.initializedPromise.then(function () {
  450. if (DEFAULT_PREFERENCES[name] === undefined) {
  451. throw new Error('preferencesSet: \'' + name + '\' is undefined.');
  452. } else if (value === undefined) {
  453. throw new Error('preferencesSet: no value is specified.');
  454. }
  455. var valueType = typeof value;
  456. var defaultType = typeof DEFAULT_PREFERENCES[name];
  457. if (valueType !== defaultType) {
  458. if (valueType === 'number' && defaultType === 'string') {
  459. value = value.toString();
  460. } else {
  461. throw new Error('Preferences_set: \'' + value + '\' is a \"' +
  462. valueType + '\", expected \"' + defaultType + '\".');
  463. }
  464. } else {
  465. if (valueType === 'number' && (value | 0) !== value) {
  466. throw new Error('Preferences_set: \'' + value +
  467. '\' must be an \"integer\".');
  468. }
  469. }
  470. this.prefs[name] = value;
  471. return this._writeToStorage(this.prefs);
  472. }.bind(this));
  473. },
  474. /**
  475. * Get the value of a preference.
  476. * @param {string} name The name of the preference whose value is requested.
  477. * @return {Promise} A promise that is resolved with a {boolean|number|string}
  478. * containing the value of the preference.
  479. */
  480. get: function preferencesGet(name) {
  481. return this.initializedPromise.then(function () {
  482. var defaultValue = DEFAULT_PREFERENCES[name];
  483. if (defaultValue === undefined) {
  484. throw new Error('preferencesGet: \'' + name + '\' is undefined.');
  485. } else {
  486. var prefValue = this.prefs[name];
  487. if (prefValue !== undefined) {
  488. return prefValue;
  489. }
  490. }
  491. return defaultValue;
  492. }.bind(this));
  493. }
  494. };
  495. Preferences._writeToStorage = function (prefObj) {
  496. return new Promise(function (resolve) {
  497. localStorage.setItem('pdfjs.preferences', JSON.stringify(prefObj));
  498. resolve();
  499. });
  500. };
  501. Preferences._readFromStorage = function (prefObj) {
  502. return new Promise(function (resolve) {
  503. var readPrefs = JSON.parse(localStorage.getItem('pdfjs.preferences'));
  504. resolve(readPrefs);
  505. });
  506. };
  507. (function mozPrintCallbackPolyfillClosure() {
  508. if ('mozPrintCallback' in document.createElement('canvas')) {
  509. return;
  510. }
  511. // Cause positive result on feature-detection:
  512. HTMLCanvasElement.prototype.mozPrintCallback = undefined;
  513. var canvases; // During print task: non-live NodeList of <canvas> elements
  514. var index; // Index of <canvas> element that is being processed
  515. var print = window.print;
  516. window.print = function print() {
  517. if (canvases) {
  518. console.warn('Ignored window.print() because of a pending print job.');
  519. return;
  520. }
  521. try {
  522. dispatchEvent('beforeprint');
  523. } finally {
  524. canvases = document.querySelectorAll('canvas');
  525. index = -1;
  526. next();
  527. }
  528. };
  529. function dispatchEvent(eventType) {
  530. var event = document.createEvent('CustomEvent');
  531. event.initCustomEvent(eventType, false, false, 'custom');
  532. window.dispatchEvent(event);
  533. }
  534. function next() {
  535. if (!canvases) {
  536. return; // Print task cancelled by user (state reset in abort())
  537. }
  538. renderProgress();
  539. if (++index < canvases.length) {
  540. var canvas = canvases[index];
  541. if (typeof canvas.mozPrintCallback === 'function') {
  542. canvas.mozPrintCallback({
  543. context: canvas.getContext('2d'),
  544. abort: abort,
  545. done: next
  546. });
  547. } else {
  548. next();
  549. }
  550. } else {
  551. renderProgress();
  552. print.call(window);
  553. setTimeout(abort, 20); // Tidy-up
  554. }
  555. }
  556. function abort() {
  557. if (canvases) {
  558. canvases = null;
  559. renderProgress();
  560. dispatchEvent('afterprint');
  561. }
  562. }
  563. function renderProgress() {
  564. var progressContainer = document.getElementById('mozPrintCallback-shim');
  565. if (canvases) {
  566. var progress = Math.round(100 * index / canvases.length);
  567. var progressBar = progressContainer.querySelector('progress');
  568. var progressPerc = progressContainer.querySelector('.relative-progress');
  569. progressBar.value = progress;
  570. progressPerc.textContent = progress + '%';
  571. progressContainer.removeAttribute('hidden');
  572. progressContainer.onclick = abort;
  573. } else {
  574. progressContainer.setAttribute('hidden', '');
  575. }
  576. }
  577. var hasAttachEvent = !!document.attachEvent;
  578. window.addEventListener('keydown', function(event) {
  579. // Intercept Cmd/Ctrl + P in all browsers.
  580. // Also intercept Cmd/Ctrl + Shift + P in Chrome and Opera
  581. if (event.keyCode === 80/*P*/ && (event.ctrlKey || event.metaKey) &&
  582. !event.altKey && (!event.shiftKey || window.chrome || window.opera)) {
  583. window.print();
  584. if (hasAttachEvent) {
  585. // Only attachEvent can cancel Ctrl + P dialog in IE <=10
  586. // attachEvent is gone in IE11, so the dialog will re-appear in IE11.
  587. return;
  588. }
  589. event.preventDefault();
  590. if (event.stopImmediatePropagation) {
  591. event.stopImmediatePropagation();
  592. } else {
  593. event.stopPropagation();
  594. }
  595. return;
  596. }
  597. if (event.keyCode === 27 && canvases) { // Esc
  598. abort();
  599. }
  600. }, true);
  601. if (hasAttachEvent) {
  602. document.attachEvent('onkeydown', function(event) {
  603. event = event || window.event;
  604. if (event.keyCode === 80/*P*/ && event.ctrlKey) {
  605. event.keyCode = 0;
  606. return false;
  607. }
  608. });
  609. }
  610. if ('onbeforeprint' in window) {
  611. // Do not propagate before/afterprint events when they are not triggered
  612. // from within this polyfill. (FF/IE).
  613. var stopPropagationIfNeeded = function(event) {
  614. if (event.detail !== 'custom' && event.stopImmediatePropagation) {
  615. event.stopImmediatePropagation();
  616. }
  617. };
  618. window.addEventListener('beforeprint', stopPropagationIfNeeded, false);
  619. window.addEventListener('afterprint', stopPropagationIfNeeded, false);
  620. }
  621. })();
  622. var DownloadManager = (function DownloadManagerClosure() {
  623. function download(blobUrl, filename) {
  624. var a = document.createElement('a');
  625. if (a.click) {
  626. // Use a.click() if available. Otherwise, Chrome might show
  627. // "Unsafe JavaScript attempt to initiate a navigation change
  628. // for frame with URL" and not open the PDF at all.
  629. // Supported by (not mentioned = untested):
  630. // - Firefox 6 - 19 (4- does not support a.click, 5 ignores a.click)
  631. // - Chrome 19 - 26 (18- does not support a.click)
  632. // - Opera 9 - 12.15
  633. // - Internet Explorer 6 - 10
  634. // - Safari 6 (5.1- does not support a.click)
  635. a.href = blobUrl;
  636. a.target = '_parent';
  637. // Use a.download if available. This increases the likelihood that
  638. // the file is downloaded instead of opened by another PDF plugin.
  639. if ('download' in a) {
  640. a.download = filename;
  641. }
  642. // <a> must be in the document for IE and recent Firefox versions.
  643. // (otherwise .click() is ignored)
  644. (document.body || document.documentElement).appendChild(a);
  645. a.click();
  646. a.parentNode.removeChild(a);
  647. } else {
  648. if (window.top === window &&
  649. blobUrl.split('#')[0] === window.location.href.split('#')[0]) {
  650. // If _parent == self, then opening an identical URL with different
  651. // location hash will only cause a navigation, not a download.
  652. var padCharacter = blobUrl.indexOf('?') === -1 ? '?' : '&';
  653. blobUrl = blobUrl.replace(/#|$/, padCharacter + '$&');
  654. }
  655. window.open(blobUrl, '_parent');
  656. }
  657. }
  658. function DownloadManager() {}
  659. DownloadManager.prototype = {
  660. downloadUrl: function DownloadManager_downloadUrl(url, filename) {
  661. if (!PDFJS.isValidUrl(url, true)) {
  662. return; // restricted/invalid URL
  663. }
  664. download(url + '#pdfjs.action=download', filename);
  665. },
  666. downloadData: function DownloadManager_downloadData(data, filename,
  667. contentType) {
  668. if (navigator.msSaveBlob) { // IE10 and above
  669. return navigator.msSaveBlob(new Blob([data], { type: contentType }),
  670. filename);
  671. }
  672. var blobUrl = PDFJS.createObjectURL(data, contentType);
  673. download(blobUrl, filename);
  674. },
  675. download: function DownloadManager_download(blob, url, filename) {
  676. if (!URL) {
  677. // URL.createObjectURL is not supported
  678. this.downloadUrl(url, filename);
  679. return;
  680. }
  681. if (navigator.msSaveBlob) {
  682. // IE10 / IE11
  683. if (!navigator.msSaveBlob(blob, filename)) {
  684. this.downloadUrl(url, filename);
  685. }
  686. return;
  687. }
  688. var blobUrl = URL.createObjectURL(blob);
  689. download(blobUrl, filename);
  690. }
  691. };
  692. return DownloadManager;
  693. })();
  694. /**
  695. * View History - This is a utility for saving various view parameters for
  696. * recently opened files.
  697. *
  698. * The way that the view parameters are stored depends on how PDF.js is built,
  699. * for 'node make <flag>' the following cases exist:
  700. * - FIREFOX or MOZCENTRAL - uses sessionStorage.
  701. * - B2G - uses asyncStorage.
  702. * - GENERIC or CHROME - uses localStorage, if it is available.
  703. */
  704. var ViewHistory = (function ViewHistoryClosure() {
  705. function ViewHistory(fingerprint) {
  706. this.fingerprint = fingerprint;
  707. this.isInitializedPromiseResolved = false;
  708. this.initializedPromise =
  709. this._readFromStorage().then(function (databaseStr) {
  710. this.isInitializedPromiseResolved = true;
  711. var database = JSON.parse(databaseStr || '{}');
  712. if (!('files' in database)) {
  713. database.files = [];
  714. }
  715. if (database.files.length >= VIEW_HISTORY_MEMORY) {
  716. database.files.shift();
  717. }
  718. var index;
  719. for (var i = 0, length = database.files.length; i < length; i++) {
  720. var branch = database.files[i];
  721. if (branch.fingerprint === this.fingerprint) {
  722. index = i;
  723. break;
  724. }
  725. }
  726. if (typeof index !== 'number') {
  727. index = database.files.push({fingerprint: this.fingerprint}) - 1;
  728. }
  729. this.file = database.files[index];
  730. this.database = database;
  731. }.bind(this));
  732. }
  733. ViewHistory.prototype = {
  734. _writeToStorage: function ViewHistory_writeToStorage() {
  735. return new Promise(function (resolve) {
  736. var databaseStr = JSON.stringify(this.database);
  737. localStorage.setItem('database', databaseStr);
  738. resolve();
  739. }.bind(this));
  740. },
  741. _readFromStorage: function ViewHistory_readFromStorage() {
  742. return new Promise(function (resolve) {
  743. resolve(localStorage.getItem('database'));
  744. });
  745. },
  746. set: function ViewHistory_set(name, val) {
  747. if (!this.isInitializedPromiseResolved) {
  748. return;
  749. }
  750. this.file[name] = val;
  751. return this._writeToStorage();
  752. },
  753. setMultiple: function ViewHistory_setMultiple(properties) {
  754. if (!this.isInitializedPromiseResolved) {
  755. return;
  756. }
  757. for (var name in properties) {
  758. this.file[name] = properties[name];
  759. }
  760. return this._writeToStorage();
  761. },
  762. get: function ViewHistory_get(name, defaultValue) {
  763. if (!this.isInitializedPromiseResolved) {
  764. return defaultValue;
  765. }
  766. return this.file[name] || defaultValue;
  767. }
  768. };
  769. return ViewHistory;
  770. })();
  771. /**
  772. * Creates a "search bar" given a set of DOM elements that act as controls
  773. * for searching or for setting search preferences in the UI. This object
  774. * also sets up the appropriate events for the controls. Actual searching
  775. * is done by PDFFindController.
  776. */
  777. var PDFFindBar = (function PDFFindBarClosure() {
  778. function PDFFindBar(options) {
  779. this.opened = false;
  780. this.bar = options.bar || null;
  781. this.toggleButton = options.toggleButton || null;
  782. this.findField = options.findField || null;
  783. this.highlightAll = options.highlightAllCheckbox || null;
  784. this.caseSensitive = options.caseSensitiveCheckbox || null;
  785. this.findMsg = options.findMsg || null;
  786. this.findStatusIcon = options.findStatusIcon || null;
  787. this.findPreviousButton = options.findPreviousButton || null;
  788. this.findNextButton = options.findNextButton || null;
  789. this.findController = options.findController || null;
  790. if (this.findController === null) {
  791. throw new Error('PDFFindBar cannot be used without a ' +
  792. 'PDFFindController instance.');
  793. }
  794. // Add event listeners to the DOM elements.
  795. var self = this;
  796. this.toggleButton.addEventListener('click', function() {
  797. self.toggle();
  798. });
  799. this.findField.addEventListener('input', function() {
  800. self.dispatchEvent('');
  801. });
  802. this.bar.addEventListener('keydown', function(evt) {
  803. switch (evt.keyCode) {
  804. case 13: // Enter
  805. if (evt.target === self.findField) {
  806. self.dispatchEvent('again', evt.shiftKey);
  807. }
  808. break;
  809. case 27: // Escape
  810. self.close();
  811. break;
  812. }
  813. });
  814. this.findPreviousButton.addEventListener('click', function() {
  815. self.dispatchEvent('again', true);
  816. });
  817. this.findNextButton.addEventListener('click', function() {
  818. self.dispatchEvent('again', false);
  819. });
  820. this.highlightAll.addEventListener('click', function() {
  821. self.dispatchEvent('highlightallchange');
  822. });
  823. this.caseSensitive.addEventListener('click', function() {
  824. self.dispatchEvent('casesensitivitychange');
  825. });
  826. }
  827. PDFFindBar.prototype = {
  828. dispatchEvent: function PDFFindBar_dispatchEvent(type, findPrev) {
  829. var event = document.createEvent('CustomEvent');
  830. event.initCustomEvent('find' + type, true, true, {
  831. query: this.findField.value,
  832. caseSensitive: this.caseSensitive.checked,
  833. highlightAll: this.highlightAll.checked,
  834. findPrevious: findPrev
  835. });
  836. return window.dispatchEvent(event);
  837. },
  838. updateUIState: function PDFFindBar_updateUIState(state, previous) {
  839. var notFound = false;
  840. var findMsg = '';
  841. var status = '';
  842. switch (state) {
  843. case FindStates.FIND_FOUND:
  844. break;
  845. case FindStates.FIND_PENDING:
  846. status = 'pending';
  847. break;
  848. case FindStates.FIND_NOTFOUND:
  849. findMsg = mozL10n.get('find_not_found', null, 'Phrase not found');
  850. notFound = true;
  851. break;
  852. case FindStates.FIND_WRAPPED:
  853. if (previous) {
  854. findMsg = mozL10n.get('find_reached_top', null,
  855. 'Reached top of document, continued from bottom');
  856. } else {
  857. findMsg = mozL10n.get('find_reached_bottom', null,
  858. 'Reached end of document, continued from top');
  859. }
  860. break;
  861. }
  862. if (notFound) {
  863. this.findField.classList.add('notFound');
  864. } else {
  865. this.findField.classList.remove('notFound');
  866. }
  867. this.findField.setAttribute('data-status', status);
  868. this.findMsg.textContent = findMsg;
  869. },
  870. open: function PDFFindBar_open() {
  871. if (!this.opened) {
  872. this.opened = true;
  873. this.toggleButton.classList.add('toggled');
  874. this.bar.classList.remove('hidden');
  875. }
  876. this.findField.select();
  877. this.findField.focus();
  878. },
  879. close: function PDFFindBar_close() {
  880. if (!this.opened) {
  881. return;
  882. }
  883. this.opened = false;
  884. this.toggleButton.classList.remove('toggled');
  885. this.bar.classList.add('hidden');
  886. this.findController.active = false;
  887. },
  888. toggle: function PDFFindBar_toggle() {
  889. if (this.opened) {
  890. this.close();
  891. } else {
  892. this.open();
  893. }
  894. }
  895. };
  896. return PDFFindBar;
  897. })();
  898. var FindStates = {
  899. FIND_FOUND: 0,
  900. FIND_NOTFOUND: 1,
  901. FIND_WRAPPED: 2,
  902. FIND_PENDING: 3
  903. };
  904. /**
  905. * Provides "search" or "find" functionality for the PDF.
  906. * This object actually performs the search for a given string.
  907. */
  908. var PDFFindController = (function PDFFindControllerClosure() {
  909. function PDFFindController(options) {
  910. this.startedTextExtraction = false;
  911. this.extractTextPromises = [];
  912. this.pendingFindMatches = {};
  913. this.active = false; // If active, find results will be highlighted.
  914. this.pageContents = []; // Stores the text for each page.
  915. this.pageMatches = [];
  916. this.selected = { // Currently selected match.
  917. pageIdx: -1,
  918. matchIdx: -1
  919. };
  920. this.offset = { // Where the find algorithm currently is in the document.
  921. pageIdx: null,
  922. matchIdx: null
  923. };
  924. this.pagesToSearch = null;
  925. this.resumePageIdx = null;
  926. this.state = null;
  927. this.dirtyMatch = false;
  928. this.findTimeout = null;
  929. this.pdfViewer = options.pdfViewer || null;
  930. this.integratedFind = options.integratedFind || false;
  931. this.charactersToNormalize = {
  932. '\u2018': '\'', // Left single quotation mark
  933. '\u2019': '\'', // Right single quotation mark
  934. '\u201A': '\'', // Single low-9 quotation mark
  935. '\u201B': '\'', // Single high-reversed-9 quotation mark
  936. '\u201C': '"', // Left double quotation mark
  937. '\u201D': '"', // Right double quotation mark
  938. '\u201E': '"', // Double low-9 quotation mark
  939. '\u201F': '"', // Double high-reversed-9 quotation mark
  940. '\u00BC': '1/4', // Vulgar fraction one quarter
  941. '\u00BD': '1/2', // Vulgar fraction one half
  942. '\u00BE': '3/4' // Vulgar fraction three quarters
  943. };
  944. this.findBar = options.findBar || null;
  945. // Compile the regular expression for text normalization once
  946. var replace = Object.keys(this.charactersToNormalize).join('');
  947. this.normalizationRegex = new RegExp('[' + replace + ']', 'g');
  948. var events = [
  949. 'find',
  950. 'findagain',
  951. 'findhighlightallchange',
  952. 'findcasesensitivitychange'
  953. ];
  954. this.firstPagePromise = new Promise(function (resolve) {
  955. this.resolveFirstPage = resolve;
  956. }.bind(this));
  957. this.handleEvent = this.handleEvent.bind(this);
  958. for (var i = 0, len = events.length; i < len; i++) {
  959. window.addEventListener(events[i], this.handleEvent);
  960. }
  961. }
  962. PDFFindController.prototype = {
  963. setFindBar: function PDFFindController_setFindBar(findBar) {
  964. this.findBar = findBar;
  965. },
  966. reset: function PDFFindController_reset() {
  967. this.startedTextExtraction = false;
  968. this.extractTextPromises = [];
  969. this.active = false;
  970. },
  971. normalize: function PDFFindController_normalize(text) {
  972. var self = this;
  973. return text.replace(this.normalizationRegex, function (ch) {
  974. return self.charactersToNormalize[ch];
  975. });
  976. },
  977. calcFindMatch: function PDFFindController_calcFindMatch(pageIndex) {
  978. var pageContent = this.normalize(this.pageContents[pageIndex]);
  979. var query = this.normalize(this.state.query);
  980. var caseSensitive = this.state.caseSensitive;
  981. var queryLen = query.length;
  982. if (queryLen === 0) {
  983. return; // Do nothing: the matches should be wiped out already.
  984. }
  985. if (!caseSensitive) {
  986. pageContent = pageContent.toLowerCase();
  987. query = query.toLowerCase();
  988. }
  989. var matches = [];
  990. var matchIdx = -queryLen;
  991. while (true) {
  992. matchIdx = pageContent.indexOf(query, matchIdx + queryLen);
  993. if (matchIdx === -1) {
  994. break;
  995. }
  996. matches.push(matchIdx);
  997. }
  998. this.pageMatches[pageIndex] = matches;
  999. this.updatePage(pageIndex);
  1000. if (this.resumePageIdx === pageIndex) {
  1001. this.resumePageIdx = null;
  1002. this.nextPageMatch();
  1003. }
  1004. },
  1005. extractText: function PDFFindController_extractText() {
  1006. if (this.startedTextExtraction) {
  1007. return;
  1008. }
  1009. this.startedTextExtraction = true;
  1010. this.pageContents = [];
  1011. var extractTextPromisesResolves = [];
  1012. var numPages = this.pdfViewer.pagesCount;
  1013. for (var i = 0; i < numPages; i++) {
  1014. this.extractTextPromises.push(new Promise(function (resolve) {
  1015. extractTextPromisesResolves.push(resolve);
  1016. }));
  1017. }
  1018. var self = this;
  1019. function extractPageText(pageIndex) {
  1020. self.pdfViewer.getPageTextContent(pageIndex).then(
  1021. function textContentResolved(textContent) {
  1022. var textItems = textContent.items;
  1023. var str = [];
  1024. for (var i = 0, len = textItems.length; i < len; i++) {
  1025. str.push(textItems[i].str);
  1026. }
  1027. // Store the pageContent as a string.
  1028. self.pageContents.push(str.join(''));
  1029. extractTextPromisesResolves[pageIndex](pageIndex);
  1030. if ((pageIndex + 1) < self.pdfViewer.pagesCount) {
  1031. extractPageText(pageIndex + 1);
  1032. }
  1033. }
  1034. );
  1035. }
  1036. extractPageText(0);
  1037. },
  1038. handleEvent: function PDFFindController_handleEvent(e) {
  1039. if (this.state === null || e.type !== 'findagain') {
  1040. this.dirtyMatch = true;
  1041. }
  1042. this.state = e.detail;
  1043. this.updateUIState(FindStates.FIND_PENDING);
  1044. this.firstPagePromise.then(function() {
  1045. this.extractText();
  1046. clearTimeout(this.findTimeout);
  1047. if (e.type === 'find') {
  1048. // Only trigger the find action after 250ms of silence.
  1049. this.findTimeout = setTimeout(this.nextMatch.bind(this), 250);
  1050. } else {
  1051. this.nextMatch();
  1052. }
  1053. }.bind(this));
  1054. },
  1055. updatePage: function PDFFindController_updatePage(index) {
  1056. var page = this.pdfViewer.getPageView(index);
  1057. if (this.selected.pageIdx === index) {
  1058. // If the page is selected, scroll the page into view, which triggers
  1059. // rendering the page, which adds the textLayer. Once the textLayer is
  1060. // build, it will scroll onto the selected match.
  1061. this.pdfViewer.scrollPageIntoView(index + 1);
  1062. }
  1063. if (page.textLayer) {
  1064. page.textLayer.updateMatches();
  1065. }
  1066. },
  1067. nextMatch: function PDFFindController_nextMatch() {
  1068. var previous = this.state.findPrevious;
  1069. var currentPageIndex = this.pdfViewer.currentPageNumber - 1;
  1070. var numPages = this.pdfViewer.pagesCount;
  1071. this.active = true;
  1072. if (this.dirtyMatch) {
  1073. // Need to recalculate the matches, reset everything.
  1074. this.dirtyMatch = false;
  1075. this.selected.pageIdx = this.selected.matchIdx = -1;
  1076. this.offset.pageIdx = currentPageIndex;
  1077. this.offset.matchIdx = null;
  1078. this.hadMatch = false;
  1079. this.resumePageIdx = null;
  1080. this.pageMatches = [];
  1081. var self = this;
  1082. for (var i = 0; i < numPages; i++) {
  1083. // Wipe out any previous highlighted matches.
  1084. this.updatePage(i);
  1085. // As soon as the text is extracted start finding the matches.
  1086. if (!(i in this.pendingFindMatches)) {
  1087. this.pendingFindMatches[i] = true;
  1088. this.extractTextPromises[i].then(function(pageIdx) {
  1089. delete self.pendingFindMatches[pageIdx];
  1090. self.calcFindMatch(pageIdx);
  1091. });
  1092. }
  1093. }
  1094. }
  1095. // If there's no query there's no point in searching.
  1096. if (this.state.query === '') {
  1097. this.updateUIState(FindStates.FIND_FOUND);
  1098. return;
  1099. }
  1100. // If we're waiting on a page, we return since we can't do anything else.
  1101. if (this.resumePageIdx) {
  1102. return;
  1103. }
  1104. var offset = this.offset;
  1105. // Keep track of how many pages we should maximally iterate through.
  1106. this.pagesToSearch = numPages;
  1107. // If there's already a matchIdx that means we are iterating through a
  1108. // page's matches.
  1109. if (offset.matchIdx !== null) {
  1110. var numPageMatches = this.pageMatches[offset.pageIdx].length;
  1111. if ((!previous && offset.matchIdx + 1 < numPageMatches) ||
  1112. (previous && offset.matchIdx > 0)) {
  1113. // The simple case; we just have advance the matchIdx to select
  1114. // the next match on the page.
  1115. this.hadMatch = true;
  1116. offset.matchIdx = (previous ? offset.matchIdx - 1 :
  1117. offset.matchIdx + 1);
  1118. this.updateMatch(true);
  1119. return;
  1120. }
  1121. // We went beyond the current page's matches, so we advance to
  1122. // the next page.
  1123. this.advanceOffsetPage(previous);
  1124. }
  1125. // Start searching through the page.
  1126. this.nextPageMatch();
  1127. },
  1128. matchesReady: function PDFFindController_matchesReady(matches) {
  1129. var offset = this.offset;
  1130. var numMatches = matches.length;
  1131. var previous = this.state.findPrevious;
  1132. if (numMatches) {
  1133. // There were matches for the page, so initialize the matchIdx.
  1134. this.hadMatch = true;
  1135. offset.matchIdx = (previous ? numMatches - 1 : 0);
  1136. this.updateMatch(true);
  1137. return true;
  1138. } else {
  1139. // No matches, so attempt to search the next page.
  1140. this.advanceOffsetPage(previous);
  1141. if (offset.wrapped) {
  1142. offset.matchIdx = null;
  1143. if (this.pagesToSearch < 0) {
  1144. // No point in wrapping again, there were no matches.
  1145. this.updateMatch(false);
  1146. // while matches were not found, searching for a page
  1147. // with matches should nevertheless halt.
  1148. return true;
  1149. }
  1150. }
  1151. // Matches were not found (and searching is not done).
  1152. return false;
  1153. }
  1154. },
  1155. nextPageMatch: function PDFFindController_nextPageMatch() {
  1156. if (this.resumePageIdx !== null) {
  1157. console.error('There can only be one pending page.');
  1158. }
  1159. do {
  1160. var pageIdx = this.offset.pageIdx;
  1161. var matches = this.pageMatches[pageIdx];
  1162. if (!matches) {
  1163. // The matches don't exist yet for processing by "matchesReady",
  1164. // so set a resume point for when they do exist.
  1165. this.resumePageIdx = pageIdx;
  1166. break;
  1167. }
  1168. } while (!this.matchesReady(matches));
  1169. },
  1170. advanceOffsetPage: function PDFFindController_advanceOffsetPage(previous) {
  1171. var offset = this.offset;
  1172. var numPages = this.extractTextPromises.length;
  1173. offset.pageIdx = (previous ? offset.pageIdx - 1 : offset.pageIdx + 1);
  1174. offset.matchIdx = null;
  1175. this.pagesToSearch--;
  1176. if (offset.pageIdx >= numPages || offset.pageIdx < 0) {
  1177. offset.pageIdx = (previous ? numPages - 1 : 0);
  1178. offset.wrapped = true;
  1179. }
  1180. },
  1181. updateMatch: function PDFFindController_updateMatch(found) {
  1182. var state = FindStates.FIND_NOTFOUND;
  1183. var wrapped = this.offset.wrapped;
  1184. this.offset.wrapped = false;
  1185. if (found) {
  1186. var previousPage = this.selected.pageIdx;
  1187. this.selected.pageIdx = this.offset.pageIdx;
  1188. this.selected.matchIdx = this.offset.matchIdx;
  1189. state = (wrapped ? FindStates.FIND_WRAPPED : FindStates.FIND_FOUND);
  1190. // Update the currently selected page to wipe out any selected matches.
  1191. if (previousPage !== -1 && previousPage !== this.selected.pageIdx) {
  1192. this.updatePage(previousPage);
  1193. }
  1194. }
  1195. this.updateUIState(state, this.state.findPrevious);
  1196. if (this.selected.pageIdx !== -1) {
  1197. this.updatePage(this.selected.pageIdx);
  1198. }
  1199. },
  1200. updateUIState: function PDFFindController_updateUIState(state, previous) {
  1201. if (this.integratedFind) {
  1202. FirefoxCom.request('updateFindControlState',
  1203. { result: state, findPrevious: previous });
  1204. return;
  1205. }
  1206. if (this.findBar === null) {
  1207. throw new Error('PDFFindController is not initialized with a ' +
  1208. 'PDFFindBar instance.');
  1209. }
  1210. this.findBar.updateUIState(state, previous);
  1211. }
  1212. };
  1213. return PDFFindController;
  1214. })();
  1215. var PDFHistory = {
  1216. initialized: false,
  1217. initialDestination: null,
  1218. /**
  1219. * @param {string} fingerprint
  1220. * @param {IPDFLinkService} linkService
  1221. */
  1222. initialize: function pdfHistoryInitialize(fingerprint, linkService) {
  1223. this.initialized = true;
  1224. this.reInitialized = false;
  1225. this.allowHashChange = true;
  1226. this.historyUnlocked = true;
  1227. this.previousHash = window.location.hash.substring(1);
  1228. this.currentBookmark = '';
  1229. this.currentPage = 0;
  1230. this.updatePreviousBookmark = false;
  1231. this.previousBookmark = '';
  1232. this.previousPage = 0;
  1233. this.nextHashParam = '';
  1234. this.fingerprint = fingerprint;
  1235. this.linkService = linkService;
  1236. this.currentUid = this.uid = 0;
  1237. this.current = {};
  1238. var state = window.history.state;
  1239. if (this._isStateObjectDefined(state)) {
  1240. // This corresponds to navigating back to the document
  1241. // from another page in the browser history.
  1242. if (state.target.dest) {
  1243. this.initialDestination = state.target.dest;
  1244. } else {
  1245. linkService.setHash(state.target.hash);
  1246. }
  1247. this.currentUid = state.uid;
  1248. this.uid = state.uid + 1;
  1249. this.current = state.target;
  1250. } else {
  1251. // This corresponds to the loading of a new document.
  1252. if (state && state.fingerprint &&
  1253. this.fingerprint !== state.fingerprint) {
  1254. // Reinitialize the browsing history when a new document
  1255. // is opened in the web viewer.
  1256. this.reInitialized = true;
  1257. }
  1258. this._pushOrReplaceState({ fingerprint: this.fingerprint }, true);
  1259. }
  1260. var self = this;
  1261. window.addEventListener('popstate', function pdfHistoryPopstate(evt) {
  1262. evt.preventDefault();
  1263. evt.stopPropagation();
  1264. if (!self.historyUnlocked) {
  1265. return;
  1266. }
  1267. if (evt.state) {
  1268. // Move back/forward in the history.
  1269. self._goTo(evt.state);
  1270. } else {
  1271. // Handle the user modifying the hash of a loaded document.
  1272. self.previousHash = window.location.hash.substring(1);
  1273. // If the history is empty when the hash changes,
  1274. // update the previous entry in the browser history.
  1275. if (self.uid === 0) {
  1276. var previousParams = (self.previousHash && self.currentBookmark &&
  1277. self.previousHash !== self.currentBookmark) ?
  1278. { hash: self.currentBookmark, page: self.currentPage } :
  1279. { page: 1 };
  1280. self.historyUnlocked = false;
  1281. self.allowHashChange = false;
  1282. window.history.back();
  1283. self._pushToHistory(previousParams, false, true);
  1284. window.history.forward();
  1285. self.historyUnlocked = true;
  1286. }
  1287. self._pushToHistory({ hash: self.previousHash }, false, true);
  1288. self._updatePreviousBookmark();
  1289. }
  1290. }, false);
  1291. function pdfHistoryBeforeUnload() {
  1292. var previousParams = self._getPreviousParams(null, true);
  1293. if (previousParams) {
  1294. var replacePrevious = (!self.current.dest &&
  1295. self.current.hash !== self.previousHash);
  1296. self._pushToHistory(previousParams, false, replacePrevious);
  1297. self._updatePreviousBookmark();
  1298. }
  1299. // Remove the event listener when navigating away from the document,
  1300. // since 'beforeunload' prevents Firefox from caching the document.
  1301. window.removeEventListener('beforeunload', pdfHistoryBeforeUnload, false);
  1302. }
  1303. window.addEventListener('beforeunload', pdfHistoryBeforeUnload, false);
  1304. window.addEventListener('pageshow', function pdfHistoryPageShow(evt) {
  1305. // If the entire viewer (including the PDF file) is cached in the browser,
  1306. // we need to reattach the 'beforeunload' event listener since
  1307. // the 'DOMContentLoaded' event is not fired on 'pageshow'.
  1308. window.addEventListener('beforeunload', pdfHistoryBeforeUnload, false);
  1309. }, false);
  1310. },
  1311. _isStateObjectDefined: function pdfHistory_isStateObjectDefined(state) {
  1312. return (state && state.uid >= 0 &&
  1313. state.fingerprint && this.fingerprint === state.fingerprint &&
  1314. state.target && state.target.hash) ? true : false;
  1315. },
  1316. _pushOrReplaceState: function pdfHistory_pushOrReplaceState(stateObj,
  1317. replace) {
  1318. if (replace) {
  1319. window.history.replaceState(stateObj, '', document.URL);
  1320. } else {
  1321. window.history.pushState(stateObj, '', document.URL);
  1322. }
  1323. },
  1324. get isHashChangeUnlocked() {
  1325. if (!this.initialized) {
  1326. return true;
  1327. }
  1328. // If the current hash changes when moving back/forward in the history,
  1329. // this will trigger a 'popstate' event *as well* as a 'hashchange' event.
  1330. // Since the hash generally won't correspond to the exact the position
  1331. // stored in the history's state object, triggering the 'hashchange' event
  1332. // can thus corrupt the browser history.
  1333. //
  1334. // When the hash changes during a 'popstate' event, we *only* prevent the
  1335. // first 'hashchange' event and immediately reset allowHashChange.
  1336. // If it is not reset, the user would not be able to change the hash.
  1337. var temp = this.allowHashChange;
  1338. this.allowHashChange = true;
  1339. return temp;
  1340. },
  1341. _updatePreviousBookmark: function pdfHistory_updatePreviousBookmark() {
  1342. if (this.updatePreviousBookmark &&
  1343. this.currentBookmark && this.currentPage) {
  1344. this.previousBookmark = this.currentBookmark;
  1345. this.previousPage = this.currentPage;
  1346. this.updatePreviousBookmark = false;
  1347. }
  1348. },
  1349. updateCurrentBookmark: function pdfHistoryUpdateCurrentBookmark(bookmark,
  1350. pageNum) {
  1351. if (this.initialized) {
  1352. this.currentBookmark = bookmark.substring(1);
  1353. this.currentPage = pageNum | 0;
  1354. this._updatePreviousBookmark();
  1355. }
  1356. },
  1357. updateNextHashParam: function pdfHistoryUpdateNextHashParam(param) {
  1358. if (this.initialized) {
  1359. this.nextHashParam = param;
  1360. }
  1361. },
  1362. push: function pdfHistoryPush(params, isInitialBookmark) {
  1363. if (!(this.initialized && this.historyUnlocked)) {
  1364. return;
  1365. }
  1366. if (params.dest && !params.hash) {
  1367. params.hash = (this.current.hash && this.current.dest &&
  1368. this.current.dest === params.dest) ?
  1369. this.current.hash :
  1370. this.linkService.getDestinationHash(params.dest).split('#')[1];
  1371. }
  1372. if (params.page) {
  1373. params.page |= 0;
  1374. }
  1375. if (isInitialBookmark) {
  1376. var target = window.history.state.target;
  1377. if (!target) {
  1378. // Invoked when the user specifies an initial bookmark,
  1379. // thus setting initialBookmark, when the document is loaded.
  1380. this._pushToHistory(params, false);
  1381. this.previousHash = window.location.hash.substring(1);
  1382. }
  1383. this.updatePreviousBookmark = this.nextHashParam ? false : true;
  1384. if (target) {
  1385. // If the current document is reloaded,
  1386. // avoid creating duplicate entries in the history.
  1387. this._updatePreviousBookmark();
  1388. }
  1389. return;
  1390. }
  1391. if (this.nextHashParam) {
  1392. if (this.nextHashParam === params.hash) {
  1393. this.nextHashParam = null;
  1394. this.updatePreviousBookmark = true;
  1395. return;
  1396. } else {
  1397. this.nextHashParam = null;
  1398. }
  1399. }
  1400. if (params.hash) {
  1401. if (this.current.hash) {
  1402. if (this.current.hash !== params.hash) {
  1403. this._pushToHistory(params, true);
  1404. } else {
  1405. if (!this.current.page && params.page) {
  1406. this._pushToHistory(params, false, true);
  1407. }
  1408. this.updatePreviousBookmark = true;
  1409. }
  1410. } else {
  1411. this._pushToHistory(params, true);
  1412. }
  1413. } else if (this.current.page && params.page &&
  1414. this.current.page !== params.page) {
  1415. this._pushToHistory(params, true);
  1416. }
  1417. },
  1418. _getPreviousParams: function pdfHistory_getPreviousParams(onlyCheckPage,
  1419. beforeUnload) {
  1420. if (!(this.currentBookmark && this.currentPage)) {
  1421. return null;
  1422. } else if (this.updatePreviousBookmark) {
  1423. this.updatePreviousBookmark = false;
  1424. }
  1425. if (this.uid > 0 && !(this.previousBookmark && this.previousPage)) {
  1426. // Prevent the history from getting stuck in the current state,
  1427. // effectively preventing the user from going back/forward in the history.
  1428. //
  1429. // This happens if the current position in the document didn't change when
  1430. // the history was previously updated. The reasons for this are either:
  1431. // 1. The current zoom value is such that the document does not need to,
  1432. // or cannot, be scrolled to display the destination.
  1433. // 2. The previous destination is broken, and doesn't actally point to a
  1434. // position within the document.
  1435. // (This is either due to a bad PDF generator, or the user making a
  1436. // mistake when entering a destination in the hash parameters.)
  1437. return null;
  1438. }
  1439. if ((!this.current.dest && !onlyCheckPage) || beforeUnload) {
  1440. if (this.previousBookmark === this.currentBookmark) {
  1441. return null;
  1442. }
  1443. } else if (this.current.page || onlyCheckPage) {
  1444. if (this.previousPage === this.currentPage) {
  1445. return null;
  1446. }
  1447. } else {
  1448. return null;
  1449. }
  1450. var params = { hash: this.currentBookmark, page: this.currentPage };
  1451. if (PresentationMode.active) {
  1452. params.hash = null;
  1453. }
  1454. return params;
  1455. },
  1456. _stateObj: function pdfHistory_stateObj(params) {
  1457. return { fingerprint: this.fingerprint, uid: this.uid, target: params };
  1458. },
  1459. _pushToHistory: function pdfHistory_pushToHistory(params,
  1460. addPrevious, overwrite) {
  1461. if (!this.initialized) {
  1462. return;
  1463. }
  1464. if (!params.hash && params.page) {
  1465. params.hash = ('page=' + params.page);
  1466. }
  1467. if (addPrevious && !overwrite) {
  1468. var previousParams = this._getPreviousParams();
  1469. if (previousParams) {
  1470. var replacePrevious = (!this.current.dest &&
  1471. this.current.hash !== this.previousHash);
  1472. this._pushToHistory(previousParams, false, replacePrevious);
  1473. }
  1474. }
  1475. this._pushOrReplaceState(this._stateObj(params),
  1476. (overwrite || this.uid === 0));
  1477. this.currentUid = this.uid++;
  1478. this.current = params;
  1479. this.updatePreviousBookmark = true;
  1480. },
  1481. _goTo: function pdfHistory_goTo(state) {
  1482. if (!(this.initialized && this.historyUnlocked &&
  1483. this._isStateObjectDefined(state))) {
  1484. return;
  1485. }
  1486. if (!this.reInitialized && state.uid < this.currentUid) {
  1487. var previousParams = this._getPreviousParams(true);
  1488. if (previousParams) {
  1489. this._pushToHistory(this.current, false);
  1490. this._pushToHistory(previousParams, false);
  1491. this.currentUid = state.uid;
  1492. window.history.back();
  1493. return;
  1494. }
  1495. }
  1496. this.historyUnlocked = false;
  1497. if (state.target.dest) {
  1498. this.linkService.navigateTo(state.target.dest);
  1499. } else {
  1500. this.linkService.setHash(state.target.hash);
  1501. }
  1502. this.currentUid = state.uid;
  1503. if (state.uid > this.uid) {
  1504. this.uid = state.uid;
  1505. }
  1506. this.current = state.target;
  1507. this.updatePreviousBookmark = true;
  1508. var currentHash = window.location.hash.substring(1);
  1509. if (this.previousHash !== currentHash) {
  1510. this.allowHashChange = false;
  1511. }
  1512. this.previousHash = currentHash;
  1513. this.historyUnlocked = true;
  1514. },
  1515. back: function pdfHistoryBack() {
  1516. this.go(-1);
  1517. },
  1518. forward: function pdfHistoryForward() {
  1519. this.go(1);
  1520. },
  1521. go: function pdfHistoryGo(direction) {
  1522. if (this.initialized && this.historyUnlocked) {
  1523. var state = window.history.state;
  1524. if (direction === -1 && state && state.uid > 0) {
  1525. window.history.back();
  1526. } else if (direction === 1 && state && state.uid < (this.uid - 1)) {
  1527. window.history.forward();
  1528. }
  1529. }
  1530. }
  1531. };
  1532. var SecondaryToolbar = {
  1533. opened: false,
  1534. previousContainerHeight: null,
  1535. newContainerHeight: null,
  1536. initialize: function secondaryToolbarInitialize(options) {
  1537. this.toolbar = options.toolbar;
  1538. this.presentationMode = options.presentationMode;
  1539. this.documentProperties = options.documentProperties;
  1540. this.buttonContainer = this.toolbar.firstElementChild;
  1541. // Define the toolbar buttons.
  1542. this.toggleButton = options.toggleButton;
  1543. this.presentationModeButton = options.presentationModeButton;
  1544. this.openFile = options.openFile;
  1545. this.print = options.print;
  1546. this.download = options.download;
  1547. this.viewBookmark = options.viewBookmark;
  1548. this.firstPage = options.firstPage;
  1549. this.lastPage = options.lastPage;
  1550. this.pageRotateCw = options.pageRotateCw;
  1551. this.pageRotateCcw = options.pageRotateCcw;
  1552. this.documentPropertiesButton = options.documentPropertiesButton;
  1553. // Attach the event listeners.
  1554. var elements = [
  1555. // Button to toggle the visibility of the secondary toolbar:
  1556. { element: this.toggleButton, handler: this.toggle },
  1557. // All items within the secondary toolbar
  1558. // (except for toggleHandTool, hand_tool.js is responsible for it):
  1559. { element: this.presentationModeButton,
  1560. handler: this.presentationModeClick },
  1561. { element: this.openFile, handler: this.openFileClick },
  1562. { element: this.print, handler: this.printClick },
  1563. { element: this.download, handler: this.downloadClick },
  1564. { element: this.viewBookmark, handler: this.viewBookmarkClick },
  1565. { element: this.firstPage, handler: this.firstPageClick },
  1566. { element: this.lastPage, handler: this.lastPageClick },
  1567. { element: this.pageRotateCw, handler: this.pageRotateCwClick },
  1568. { element: this.pageRotateCcw, handler: this.pageRotateCcwClick },
  1569. { element: this.documentPropertiesButton,
  1570. handler: this.documentPropertiesClick }
  1571. ];
  1572. for (var item in elements) {
  1573. var element = elements[item].element;
  1574. if (element) {
  1575. element.addEventListener('click', elements[item].handler.bind(this));
  1576. }
  1577. }
  1578. },
  1579. // Event handling functions.
  1580. presentationModeClick: function secondaryToolbarPresentationModeClick(evt) {
  1581. this.presentationMode.request();
  1582. this.close();
  1583. },
  1584. openFileClick: function secondaryToolbarOpenFileClick(evt) {
  1585. document.getElementById('fileInput').click();
  1586. this.close();
  1587. },
  1588. printClick: function secondaryToolbarPrintClick(evt) {
  1589. window.print();
  1590. this.close();
  1591. },
  1592. downloadClick: function secondaryToolbarDownloadClick(evt) {
  1593. PDFViewerApplication.download();
  1594. this.close();
  1595. },
  1596. viewBookmarkClick: function secondaryToolbarViewBookmarkClick(evt) {
  1597. this.close();
  1598. },
  1599. firstPageClick: function secondaryToolbarFirstPageClick(evt) {
  1600. PDFViewerApplication.page = 1;
  1601. this.close();
  1602. },
  1603. lastPageClick: function secondaryToolbarLastPageClick(evt) {
  1604. if (PDFViewerApplication.pdfDocument) {
  1605. PDFViewerApplication.page = PDFViewerApplication.pagesCount;
  1606. }
  1607. this.close();
  1608. },
  1609. pageRotateCwClick: function secondaryToolbarPageRotateCwClick(evt) {
  1610. PDFViewerApplication.rotatePages(90);
  1611. },
  1612. pageRotateCcwClick: function secondaryToolbarPageRotateCcwClick(evt) {
  1613. PDFViewerApplication.rotatePages(-90);
  1614. },
  1615. documentPropertiesClick: function secondaryToolbarDocumentPropsClick(evt) {
  1616. this.documentProperties.open();
  1617. this.close();
  1618. },
  1619. // Misc. functions for interacting with the toolbar.
  1620. setMaxHeight: function secondaryToolbarSetMaxHeight(container) {
  1621. if (!container || !this.buttonContainer) {
  1622. return;
  1623. }
  1624. this.newContainerHeight = container.clientHeight;
  1625. if (this.previousContainerHeight === this.newContainerHeight) {
  1626. return;
  1627. }
  1628. this.buttonContainer.setAttribute('style',
  1629. 'max-height: ' + (this.newContainerHeight - SCROLLBAR_PADDING) + 'px;');
  1630. this.previousContainerHeight = this.newContainerHeight;
  1631. },
  1632. open: function secondaryToolbarOpen() {
  1633. if (this.opened) {
  1634. return;
  1635. }
  1636. this.opened = true;
  1637. this.toggleButton.classList.add('toggled');
  1638. this.toolbar.classList.remove('hidden');
  1639. },
  1640. close: function secondaryToolbarClose(target) {
  1641. if (!this.opened) {
  1642. return;
  1643. } else if (target && !this.toolbar.contains(target)) {
  1644. return;
  1645. }
  1646. this.opened = false;
  1647. this.toolbar.classList.add('hidden');
  1648. this.toggleButton.classList.remove('toggled');
  1649. },
  1650. toggle: function secondaryToolbarToggle() {
  1651. if (this.opened) {
  1652. this.close();
  1653. } else {
  1654. this.open();
  1655. }
  1656. }
  1657. };
  1658. var DELAY_BEFORE_HIDING_CONTROLS = 3000; // in ms
  1659. var SELECTOR = 'presentationControls';
  1660. var DELAY_BEFORE_RESETTING_SWITCH_IN_PROGRESS = 1000; // in ms
  1661. var PresentationMode = {
  1662. active: false,
  1663. args: null,
  1664. contextMenuOpen: false,
  1665. prevCoords: { x: null, y: null },
  1666. initialize: function presentationModeInitialize(options) {
  1667. this.container = options.container;
  1668. this.secondaryToolbar = options.secondaryToolbar;
  1669. this.viewer = this.container.firstElementChild;
  1670. this.firstPage = options.firstPage;
  1671. this.lastPage = options.lastPage;
  1672. this.pageRotateCw = options.pageRotateCw;
  1673. this.pageRotateCcw = options.pageRotateCcw;
  1674. this.firstPage.addEventListener('click', function() {
  1675. this.contextMenuOpen = false;
  1676. this.secondaryToolbar.firstPageClick();
  1677. }.bind(this));
  1678. this.lastPage.addEventListener('click', function() {
  1679. this.contextMenuOpen = false;
  1680. this.secondaryToolbar.lastPageClick();
  1681. }.bind(this));
  1682. this.pageRotateCw.addEventListener('click', function() {
  1683. this.contextMenuOpen = false;
  1684. this.secondaryToolbar.pageRotateCwClick();
  1685. }.bind(this));
  1686. this.pageRotateCcw.addEventListener('click', function() {
  1687. this.contextMenuOpen = false;
  1688. this.secondaryToolbar.pageRotateCcwClick();
  1689. }.bind(this));
  1690. },
  1691. get isFullscreen() {
  1692. return (document.fullscreenElement ||
  1693. document.mozFullScreen ||
  1694. document.webkitIsFullScreen ||
  1695. document.msFullscreenElement);
  1696. },
  1697. /**
  1698. * Initialize a timeout that is used to specify switchInProgress when the
  1699. * browser transitions to fullscreen mode. Since resize events are triggered
  1700. * multiple times during the switch to fullscreen mode, this is necessary in
  1701. * order to prevent the page from being scrolled partially, or completely,
  1702. * out of view when Presentation Mode is enabled.
  1703. * Note: This is only an issue at certain zoom levels, e.g. 'page-width'.
  1704. */
  1705. _setSwitchInProgress: function presentationMode_setSwitchInProgress() {
  1706. if (this.switchInProgress) {
  1707. clearTimeout(this.switchInProgress);
  1708. }
  1709. this.switchInProgress = setTimeout(function switchInProgressTimeout() {
  1710. delete this.switchInProgress;
  1711. this._notifyStateChange();
  1712. }.bind(this), DELAY_BEFORE_RESETTING_SWITCH_IN_PROGRESS);
  1713. },
  1714. _resetSwitchInProgress: function presentationMode_resetSwitchInProgress() {
  1715. if (this.switchInProgress) {
  1716. clearTimeout(this.switchInProgress);
  1717. delete this.switchInProgress;
  1718. }
  1719. },
  1720. request: function presentationModeRequest() {
  1721. if (!PDFViewerApplication.supportsFullscreen || this.isFullscreen ||
  1722. !this.viewer.hasChildNodes()) {
  1723. return false;
  1724. }
  1725. this._setSwitchInProgress();
  1726. this._notifyStateChange();
  1727. if (this.container.requestFullscreen) {
  1728. this.container.requestFullscreen();
  1729. } else if (this.container.mozRequestFullScreen) {
  1730. this.container.mozRequestFullScreen();
  1731. } else if (this.container.webkitRequestFullScreen) {
  1732. this.container.webkitRequestFullScreen(Element.ALLOW_KEYBOARD_INPUT);
  1733. } else if (this.container.msRequestFullscreen) {
  1734. this.container.msRequestFullscreen();
  1735. } else {
  1736. return false;
  1737. }
  1738. this.args = {
  1739. page: PDFViewerApplication.page,
  1740. previousScale: PDFViewerApplication.currentScaleValue
  1741. };
  1742. return true;
  1743. },
  1744. _notifyStateChange: function presentationModeNotifyStateChange() {
  1745. var event = document.createEvent('CustomEvent');
  1746. event.initCustomEvent('presentationmodechanged', true, true, {
  1747. active: PresentationMode.active,
  1748. switchInProgress: !!PresentationMode.switchInProgress
  1749. });
  1750. window.dispatchEvent(event);
  1751. },
  1752. enter: function presentationModeEnter() {
  1753. this.active = true;
  1754. this._resetSwitchInProgress();
  1755. this._notifyStateChange();
  1756. // Ensure that the correct page is scrolled into view when entering
  1757. // Presentation Mode, by waiting until fullscreen mode in enabled.
  1758. // Note: This is only necessary in non-Mozilla browsers.
  1759. setTimeout(function enterPresentationModeTimeout() {
  1760. PDFViewerApplication.page = this.args.page;
  1761. PDFViewerApplication.setScale('page-fit', true);
  1762. }.bind(this), 0);
  1763. window.addEventListener('mousemove', this.mouseMove, false);
  1764. window.addEventListener('mousedown', this.mouseDown, false);
  1765. window.addEventListener('contextmenu', this.contextMenu, false);
  1766. this.showControls();
  1767. HandTool.enterPresentationMode();
  1768. this.contextMenuOpen = false;
  1769. this.container.setAttribute('contextmenu', 'viewerContextMenu');
  1770. // Text selection is disabled in Presentation Mode, thus it's not possible
  1771. // for the user to deselect text that is selected (e.g. with "Select all")
  1772. // when entering Presentation Mode, hence we remove any active selection.
  1773. window.getSelection().removeAllRanges();
  1774. },
  1775. exit: function presentationModeExit() {
  1776. var page = PDFViewerApplication.page;
  1777. // Ensure that the correct page is scrolled into view when exiting
  1778. // Presentation Mode, by waiting until fullscreen mode is disabled.
  1779. // Note: This is only necessary in non-Mozilla browsers.
  1780. setTimeout(function exitPresentationModeTimeout() {
  1781. this.active = false;
  1782. this._notifyStateChange();
  1783. PDFViewerApplication.setScale(this.args.previousScale, true);
  1784. PDFViewerApplication.page = page;
  1785. this.args = null;
  1786. }.bind(this), 0);
  1787. window.removeEventListener('mousemove', this.mouseMove, false);
  1788. window.removeEventListener('mousedown', this.mouseDown, false);
  1789. window.removeEventListener('contextmenu', this.contextMenu, false);
  1790. this.hideControls();
  1791. PDFViewerApplication.clearMouseScrollState();
  1792. HandTool.exitPresentationMode();
  1793. this.container.removeAttribute('contextmenu');
  1794. this.contextMenuOpen = false;
  1795. // Ensure that the thumbnail of the current page is visible
  1796. // when exiting presentation mode.
  1797. scrollIntoView(document.getElementById('thumbnailContainer' + page));
  1798. },
  1799. showControls: function presentationModeShowControls() {
  1800. if (this.controlsTimeout) {
  1801. clearTimeout(this.controlsTimeout);
  1802. } else {
  1803. this.container.classList.add(SELECTOR);
  1804. }
  1805. this.controlsTimeout = setTimeout(function hideControlsTimeout() {
  1806. this.container.classList.remove(SELECTOR);
  1807. delete this.controlsTimeout;
  1808. }.bind(this), DELAY_BEFORE_HIDING_CONTROLS);
  1809. },
  1810. hideControls: function presentationModeHideControls() {
  1811. if (!this.controlsTimeout) {
  1812. return;
  1813. }
  1814. this.container.classList.remove(SELECTOR);
  1815. clearTimeout(this.controlsTimeout);
  1816. delete this.controlsTimeout;
  1817. },
  1818. mouseMove: function presentationModeMouseMove(evt) {
  1819. // Workaround for a bug in WebKit browsers that causes the 'mousemove' event
  1820. // to be fired when the cursor is changed. For details, see:
  1821. // http://code.google.com/p/chromium/issues/detail?id=103041.
  1822. var currCoords = { x: evt.clientX, y: evt.clientY };
  1823. var prevCoords = PresentationMode.prevCoords;
  1824. PresentationMode.prevCoords = currCoords;
  1825. if (currCoords.x === prevCoords.x && currCoords.y === prevCoords.y) {
  1826. return;
  1827. }
  1828. PresentationMode.showControls();
  1829. },
  1830. mouseDown: function presentationModeMouseDown(evt) {
  1831. var self = PresentationMode;
  1832. if (self.contextMenuOpen) {
  1833. self.contextMenuOpen = false;
  1834. evt.preventDefault();
  1835. return;
  1836. }
  1837. if (evt.button === 0) {
  1838. // Enable clicking of links in presentation mode. Please note:
  1839. // Only links pointing to destinations in the current PDF document work.
  1840. var isInternalLink = (evt.target.href &&
  1841. evt.target.classList.contains('internalLink'));
  1842. if (!isInternalLink) {
  1843. // Unless an internal link was clicked, advance one page.
  1844. evt.preventDefault();
  1845. PDFViewerApplication.page += (evt.shiftKey ? -1 : 1);
  1846. }
  1847. }
  1848. },
  1849. contextMenu: function presentationModeContextMenu(evt) {
  1850. PresentationMode.contextMenuOpen = true;
  1851. }
  1852. };
  1853. (function presentationModeClosure() {
  1854. function presentationModeChange(e) {
  1855. if (PresentationMode.isFullscreen) {
  1856. PresentationMode.enter();
  1857. } else {
  1858. PresentationMode.exit();
  1859. }
  1860. }
  1861. window.addEventListener('fullscreenchange', presentationModeChange, false);
  1862. window.addEventListener('mozfullscreenchange', presentationModeChange, false);
  1863. window.addEventListener('webkitfullscreenchange', presentationModeChange,
  1864. false);
  1865. window.addEventListener('MSFullscreenChange', presentationModeChange, false);
  1866. })();
  1867. /* Copyright 2013 Rob Wu <gwnRob@gmail.com>
  1868. * https://github.com/Rob--W/grab-to-pan.js
  1869. *
  1870. * Licensed under the Apache License, Version 2.0 (the "License");
  1871. * you may not use this file except in compliance with the License.
  1872. * You may obtain a copy of the License at
  1873. *
  1874. * http://www.apache.org/licenses/LICENSE-2.0
  1875. *
  1876. * Unless required by applicable law or agreed to in writing, software
  1877. * distributed under the License is distributed on an "AS IS" BASIS,
  1878. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  1879. * See the License for the specific language governing permissions and
  1880. * limitations under the License.
  1881. */
  1882. 'use strict';
  1883. var GrabToPan = (function GrabToPanClosure() {
  1884. /**
  1885. * Construct a GrabToPan instance for a given HTML element.
  1886. * @param options.element {Element}
  1887. * @param options.ignoreTarget {function} optional. See `ignoreTarget(node)`
  1888. * @param options.onActiveChanged {function(boolean)} optional. Called
  1889. * when grab-to-pan is (de)activated. The first argument is a boolean that
  1890. * shows whether grab-to-pan is activated.
  1891. */
  1892. function GrabToPan(options) {
  1893. this.element = options.element;
  1894. this.document = options.element.ownerDocument;
  1895. if (typeof options.ignoreTarget === 'function') {
  1896. this.ignoreTarget = options.ignoreTarget;
  1897. }
  1898. this.onActiveChanged = options.onActiveChanged;
  1899. // Bind the contexts to ensure that `this` always points to
  1900. // the GrabToPan instance.
  1901. this.activate = this.activate.bind(this);
  1902. this.deactivate = this.deactivate.bind(this);
  1903. this.toggle = this.toggle.bind(this);
  1904. this._onmousedown = this._onmousedown.bind(this);
  1905. this._onmousemove = this._onmousemove.bind(this);
  1906. this._endPan = this._endPan.bind(this);
  1907. // This overlay will be inserted in the document when the mouse moves during
  1908. // a grab operation, to ensure that the cursor has the desired appearance.
  1909. var overlay = this.overlay = document.createElement('div');
  1910. overlay.className = 'grab-to-pan-grabbing';
  1911. }
  1912. GrabToPan.prototype = {
  1913. /**
  1914. * Class name of element which can be grabbed
  1915. */
  1916. CSS_CLASS_GRAB: 'grab-to-pan-grab',
  1917. /**
  1918. * Bind a mousedown event to the element to enable grab-detection.
  1919. */
  1920. activate: function GrabToPan_activate() {
  1921. if (!this.active) {
  1922. this.active = true;
  1923. this.element.addEventListener('mousedown', this._onmousedown, true);
  1924. this.element.classList.add(this.CSS_CLASS_GRAB);
  1925. if (this.onActiveChanged) {
  1926. this.onActiveChanged(true);
  1927. }
  1928. }
  1929. },
  1930. /**
  1931. * Removes all events. Any pending pan session is immediately stopped.
  1932. */
  1933. deactivate: function GrabToPan_deactivate() {
  1934. if (this.active) {
  1935. this.active = false;
  1936. this.element.removeEventListener('mousedown', this._onmousedown, true);
  1937. this._endPan();
  1938. this.element.classList.remove(this.CSS_CLASS_GRAB);
  1939. if (this.onActiveChanged) {
  1940. this.onActiveChanged(false);
  1941. }
  1942. }
  1943. },
  1944. toggle: function GrabToPan_toggle() {
  1945. if (this.active) {
  1946. this.deactivate();
  1947. } else {
  1948. this.activate();
  1949. }
  1950. },
  1951. /**
  1952. * Whether to not pan if the target element is clicked.
  1953. * Override this method to change the default behaviour.
  1954. *
  1955. * @param node {Element} The target of the event
  1956. * @return {boolean} Whether to not react to the click event.
  1957. */
  1958. ignoreTarget: function GrabToPan_ignoreTarget(node) {
  1959. // Use matchesSelector to check whether the clicked element
  1960. // is (a child of) an input element / link
  1961. return node[matchesSelector](
  1962. 'a[href], a[href] *, input, textarea, button, button *, select, option'
  1963. );
  1964. },
  1965. /**
  1966. * @private
  1967. */
  1968. _onmousedown: function GrabToPan__onmousedown(event) {
  1969. if (event.button !== 0 || this.ignoreTarget(event.target)) {
  1970. return;
  1971. }
  1972. if (event.originalTarget) {
  1973. try {
  1974. /* jshint expr:true */
  1975. event.originalTarget.tagName;
  1976. } catch (e) {
  1977. // Mozilla-specific: element is a scrollbar (XUL element)
  1978. return;
  1979. }
  1980. }
  1981. this.scrollLeftStart = this.element.scrollLeft;
  1982. this.scrollTopStart = this.element.scrollTop;
  1983. this.clientXStart = event.clientX;
  1984. this.clientYStart = event.clientY;
  1985. this.document.addEventListener('mousemove', this._onmousemove, true);
  1986. this.document.addEventListener('mouseup', this._endPan, true);
  1987. // When a scroll event occurs before a mousemove, assume that the user
  1988. // dragged a scrollbar (necessary for Opera Presto, Safari and IE)
  1989. // (not needed for Chrome/Firefox)
  1990. this.element.addEventListener('scroll', this._endPan, true);
  1991. event.preventDefault();
  1992. event.stopPropagation();
  1993. this.document.documentElement.classList.add(this.CSS_CLASS_GRABBING);
  1994. var focusedElement = document.activeElement;
  1995. if (focusedElement && !focusedElement.contains(event.target)) {
  1996. focusedElement.blur();
  1997. }
  1998. },
  1999. /**
  2000. * @private
  2001. */
  2002. _onmousemove: function GrabToPan__onmousemove(event) {
  2003. this.element.removeEventListener('scroll', this._endPan, true);
  2004. if (isLeftMouseReleased(event)) {
  2005. this._endPan();
  2006. return;
  2007. }
  2008. var xDiff = event.clientX - this.clientXStart;
  2009. var yDiff = event.clientY - this.clientYStart;
  2010. this.element.scrollTop = this.scrollTopStart - yDiff;
  2011. this.element.scrollLeft = this.scrollLeftStart - xDiff;
  2012. if (!this.overlay.parentNode) {
  2013. document.body.appendChild(this.overlay);
  2014. }
  2015. },
  2016. /**
  2017. * @private
  2018. */
  2019. _endPan: function GrabToPan__endPan() {
  2020. this.element.removeEventListener('scroll', this._endPan, true);
  2021. this.document.removeEventListener('mousemove', this._onmousemove, true);
  2022. this.document.removeEventListener('mouseup', this._endPan, true);
  2023. if (this.overlay.parentNode) {
  2024. this.overlay.parentNode.removeChild(this.overlay);
  2025. }
  2026. }
  2027. };
  2028. // Get the correct (vendor-prefixed) name of the matches method.
  2029. var matchesSelector;
  2030. ['webkitM', 'mozM', 'msM', 'oM', 'm'].some(function(prefix) {
  2031. var name = prefix + 'atches';
  2032. if (name in document.documentElement) {
  2033. matchesSelector = name;
  2034. }
  2035. name += 'Selector';
  2036. if (name in document.documentElement) {
  2037. matchesSelector = name;
  2038. }
  2039. return matchesSelector; // If found, then truthy, and [].some() ends.
  2040. });
  2041. // Browser sniffing because it's impossible to feature-detect
  2042. // whether event.which for onmousemove is reliable
  2043. var isNotIEorIsIE10plus = !document.documentMode || document.documentMode > 9;
  2044. var chrome = window.chrome;
  2045. var isChrome15OrOpera15plus = chrome && (chrome.webstore || chrome.app);
  2046. // ^ Chrome 15+ ^ Opera 15+
  2047. var isSafari6plus = /Apple/.test(navigator.vendor) &&
  2048. /Version\/([6-9]\d*|[1-5]\d+)/.test(navigator.userAgent);
  2049. /**
  2050. * Whether the left mouse is not pressed.
  2051. * @param event {MouseEvent}
  2052. * @return {boolean} True if the left mouse button is not pressed.
  2053. * False if unsure or if the left mouse button is pressed.
  2054. */
  2055. function isLeftMouseReleased(event) {
  2056. if ('buttons' in event && isNotIEorIsIE10plus) {
  2057. // http://www.w3.org/TR/DOM-Level-3-Events/#events-MouseEvent-buttons
  2058. // Firefox 15+
  2059. // Internet Explorer 10+
  2060. return !(event.buttons | 1);
  2061. }
  2062. if (isChrome15OrOpera15plus || isSafari6plus) {
  2063. // Chrome 14+
  2064. // Opera 15+
  2065. // Safari 6.0+
  2066. return event.which === 0;
  2067. }
  2068. }
  2069. return GrabToPan;
  2070. })();
  2071. var HandTool = {
  2072. initialize: function handToolInitialize(options) {
  2073. var toggleHandTool = options.toggleHandTool;
  2074. this.handTool = new GrabToPan({
  2075. element: options.container,
  2076. onActiveChanged: function(isActive) {
  2077. if (!toggleHandTool) {
  2078. return;
  2079. }
  2080. if (isActive) {
  2081. toggleHandTool.title =
  2082. mozL10n.get('hand_tool_disable.title', null, 'Disable hand tool');
  2083. toggleHandTool.firstElementChild.textContent =
  2084. mozL10n.get('hand_tool_disable_label', null, 'Disable hand tool');
  2085. } else {
  2086. toggleHandTool.title =
  2087. mozL10n.get('hand_tool_enable.title', null, 'Enable hand tool');
  2088. toggleHandTool.firstElementChild.textContent =
  2089. mozL10n.get('hand_tool_enable_label', null, 'Enable hand tool');
  2090. }
  2091. }
  2092. });
  2093. if (toggleHandTool) {
  2094. toggleHandTool.addEventListener('click', this.toggle.bind(this), false);
  2095. window.addEventListener('localized', function (evt) {
  2096. Preferences.get('enableHandToolOnLoad').then(function resolved(value) {
  2097. if (value) {
  2098. this.handTool.activate();
  2099. }
  2100. }.bind(this), function rejected(reason) {});
  2101. }.bind(this));
  2102. }
  2103. },
  2104. toggle: function handToolToggle() {
  2105. this.handTool.toggle();
  2106. SecondaryToolbar.close();
  2107. },
  2108. enterPresentationMode: function handToolEnterPresentationMode() {
  2109. if (this.handTool.active) {
  2110. this.wasActive = true;
  2111. this.handTool.deactivate();
  2112. }
  2113. },
  2114. exitPresentationMode: function handToolExitPresentationMode() {
  2115. if (this.wasActive) {
  2116. this.wasActive = null;
  2117. this.handTool.activate();
  2118. }
  2119. }
  2120. };
  2121. var OverlayManager = {
  2122. overlays: {},
  2123. active: null,
  2124. /**
  2125. * @param {string} name The name of the overlay that is registered. This must
  2126. * be equal to the ID of the overlay's DOM element.
  2127. * @param {function} callerCloseMethod (optional) The method that, if present,
  2128. * will call OverlayManager.close from the Object
  2129. * registering the overlay. Access to this method is
  2130. * necessary in order to run cleanup code when e.g.
  2131. * the overlay is force closed. The default is null.
  2132. * @param {boolean} canForceClose (optional) Indicates if opening the overlay
  2133. * will close an active overlay. The default is false.
  2134. * @returns {Promise} A promise that is resolved when the overlay has been
  2135. * registered.
  2136. */
  2137. register: function overlayManagerRegister(name,
  2138. callerCloseMethod, canForceClose) {
  2139. return new Promise(function (resolve) {
  2140. var element, container;
  2141. if (!name || !(element = document.getElementById(name)) ||
  2142. !(container = element.parentNode)) {
  2143. throw new Error('Not enough parameters.');
  2144. } else if (this.overlays[name]) {
  2145. throw new Error('The overlay is already registered.');
  2146. }
  2147. this.overlays[name] = { element: element,
  2148. container: container,
  2149. callerCloseMethod: (callerCloseMethod || null),
  2150. canForceClose: (canForceClose || false) };
  2151. resolve();
  2152. }.bind(this));
  2153. },
  2154. /**
  2155. * @param {string} name The name of the overlay that is unregistered.
  2156. * @returns {Promise} A promise that is resolved when the overlay has been
  2157. * unregistered.
  2158. */
  2159. unregister: function overlayManagerUnregister(name) {
  2160. return new Promise(function (resolve) {
  2161. if (!this.overlays[name]) {
  2162. throw new Error('The overlay does not exist.');
  2163. } else if (this.active === name) {
  2164. throw new Error('The overlay cannot be removed while it is active.');
  2165. }
  2166. delete this.overlays[name];
  2167. resolve();
  2168. }.bind(this));
  2169. },
  2170. /**
  2171. * @param {string} name The name of the overlay that should be opened.
  2172. * @returns {Promise} A promise that is resolved when the overlay has been
  2173. * opened.
  2174. */
  2175. open: function overlayManagerOpen(name) {
  2176. return new Promise(function (resolve) {
  2177. if (!this.overlays[name]) {
  2178. throw new Error('The overlay does not exist.');
  2179. } else if (this.active) {
  2180. if (this.overlays[name].canForceClose) {
  2181. this._closeThroughCaller();
  2182. } else if (this.active === name) {
  2183. throw new Error('The overlay is already active.');
  2184. } else {
  2185. throw new Error('Another overlay is currently active.');
  2186. }
  2187. }
  2188. this.active = name;
  2189. this.overlays[this.active].element.classList.remove('hidden');
  2190. this.overlays[this.active].container.classList.remove('hidden');
  2191. window.addEventListener('keydown', this._keyDown);
  2192. resolve();
  2193. }.bind(this));
  2194. },
  2195. /**
  2196. * @param {string} name The name of the overlay that should be closed.
  2197. * @returns {Promise} A promise that is resolved when the overlay has been
  2198. * closed.
  2199. */
  2200. close: function overlayManagerClose(name) {
  2201. return new Promise(function (resolve) {
  2202. if (!this.overlays[name]) {
  2203. throw new Error('The overlay does not exist.');
  2204. } else if (!this.active) {
  2205. throw new Error('The overlay is currently not active.');
  2206. } else if (this.active !== name) {
  2207. throw new Error('Another overlay is currently active.');
  2208. }
  2209. this.overlays[this.active].container.classList.add('hidden');
  2210. this.overlays[this.active].element.classList.add('hidden');
  2211. this.active = null;
  2212. window.removeEventListener('keydown', this._keyDown);
  2213. resolve();
  2214. }.bind(this));
  2215. },
  2216. /**
  2217. * @private
  2218. */
  2219. _keyDown: function overlayManager_keyDown(evt) {
  2220. var self = OverlayManager;
  2221. if (self.active && evt.keyCode === 27) { // Esc key.
  2222. self._closeThroughCaller();
  2223. evt.preventDefault();
  2224. }
  2225. },
  2226. /**
  2227. * @private
  2228. */
  2229. _closeThroughCaller: function overlayManager_closeThroughCaller() {
  2230. if (this.overlays[this.active].callerCloseMethod) {
  2231. this.overlays[this.active].callerCloseMethod();
  2232. }
  2233. if (this.active) {
  2234. this.close(this.active);
  2235. }
  2236. }
  2237. };
  2238. var PasswordPrompt = {
  2239. overlayName: null,
  2240. updatePassword: null,
  2241. reason: null,
  2242. passwordField: null,
  2243. passwordText: null,
  2244. passwordSubmit: null,
  2245. passwordCancel: null,
  2246. initialize: function secondaryToolbarInitialize(options) {
  2247. this.overlayName = options.overlayName;
  2248. this.passwordField = options.passwordField;
  2249. this.passwordText = options.passwordText;
  2250. this.passwordSubmit = options.passwordSubmit;
  2251. this.passwordCancel = options.passwordCancel;
  2252. // Attach the event listeners.
  2253. this.passwordSubmit.addEventListener('click',
  2254. this.verifyPassword.bind(this));
  2255. this.passwordCancel.addEventListener('click', this.close.bind(this));
  2256. this.passwordField.addEventListener('keydown', function (e) {
  2257. if (e.keyCode === 13) { // Enter key
  2258. this.verifyPassword();
  2259. }
  2260. }.bind(this));
  2261. OverlayManager.register(this.overlayName, this.close.bind(this), true);
  2262. },
  2263. open: function passwordPromptOpen() {
  2264. OverlayManager.open(this.overlayName).then(function () {
  2265. this.passwordField.focus();
  2266. var promptString = mozL10n.get('password_label', null,
  2267. 'Enter the password to open this PDF file.');
  2268. if (this.reason === PDFJS.PasswordResponses.INCORRECT_PASSWORD) {
  2269. promptString = mozL10n.get('password_invalid', null,
  2270. 'Invalid password. Please try again.');
  2271. }
  2272. this.passwordText.textContent = promptString;
  2273. }.bind(this));
  2274. },
  2275. close: function passwordPromptClose() {
  2276. OverlayManager.close(this.overlayName).then(function () {
  2277. this.passwordField.value = '';
  2278. }.bind(this));
  2279. },
  2280. verifyPassword: function passwordPromptVerifyPassword() {
  2281. var password = this.passwordField.value;
  2282. if (password && password.length > 0) {
  2283. this.close();
  2284. return this.updatePassword(password);
  2285. }
  2286. }
  2287. };
  2288. var DocumentProperties = {
  2289. overlayName: null,
  2290. rawFileSize: 0,
  2291. // Document property fields (in the viewer).
  2292. fileNameField: null,
  2293. fileSizeField: null,
  2294. titleField: null,
  2295. authorField: null,
  2296. subjectField: null,
  2297. keywordsField: null,
  2298. creationDateField: null,
  2299. modificationDateField: null,
  2300. creatorField: null,
  2301. producerField: null,
  2302. versionField: null,
  2303. pageCountField: null,
  2304. url: null,
  2305. pdfDocument: null,
  2306. initialize: function documentPropertiesInitialize(options) {
  2307. this.overlayName = options.overlayName;
  2308. // Set the document property fields.
  2309. this.fileNameField = options.fileNameField;
  2310. this.fileSizeField = options.fileSizeField;
  2311. this.titleField = options.titleField;
  2312. this.authorField = options.authorField;
  2313. this.subjectField = options.subjectField;
  2314. this.keywordsField = options.keywordsField;
  2315. this.creationDateField = options.creationDateField;
  2316. this.modificationDateField = options.modificationDateField;
  2317. this.creatorField = options.creatorField;
  2318. this.producerField = options.producerField;
  2319. this.versionField = options.versionField;
  2320. this.pageCountField = options.pageCountField;
  2321. // Bind the event listener for the Close button.
  2322. if (options.closeButton) {
  2323. options.closeButton.addEventListener('click', this.close.bind(this));
  2324. }
  2325. this.dataAvailablePromise = new Promise(function (resolve) {
  2326. this.resolveDataAvailable = resolve;
  2327. }.bind(this));
  2328. OverlayManager.register(this.overlayName, this.close.bind(this));
  2329. },
  2330. getProperties: function documentPropertiesGetProperties() {
  2331. if (!OverlayManager.active) {
  2332. // If the dialog was closed before dataAvailablePromise was resolved,
  2333. // don't bother updating the properties.
  2334. return;
  2335. }
  2336. // Get the file size (if it hasn't already been set).
  2337. this.pdfDocument.getDownloadInfo().then(function(data) {
  2338. if (data.length === this.rawFileSize) {
  2339. return;
  2340. }
  2341. this.setFileSize(data.length);
  2342. this.updateUI(this.fileSizeField, this.parseFileSize());
  2343. }.bind(this));
  2344. // Get the document properties.
  2345. this.pdfDocument.getMetadata().then(function(data) {
  2346. var fields = [
  2347. { field: this.fileNameField,
  2348. content: getPDFFileNameFromURL(this.url) },
  2349. { field: this.fileSizeField, content: this.parseFileSize() },
  2350. { field: this.titleField, content: data.info.Title },
  2351. { field: this.authorField, content: data.info.Author },
  2352. { field: this.subjectField, content: data.info.Subject },
  2353. { field: this.keywordsField, content: data.info.Keywords },
  2354. { field: this.creationDateField,
  2355. content: this.parseDate(data.info.CreationDate) },
  2356. { field: this.modificationDateField,
  2357. content: this.parseDate(data.info.ModDate) },
  2358. { field: this.creatorField, content: data.info.Creator },
  2359. { field: this.producerField, content: data.info.Producer },
  2360. { field: this.versionField, content: data.info.PDFFormatVersion },
  2361. { field: this.pageCountField, content: this.pdfDocument.numPages }
  2362. ];
  2363. // Show the properties in the dialog.
  2364. for (var item in fields) {
  2365. var element = fields[item];
  2366. this.updateUI(element.field, element.content);
  2367. }
  2368. }.bind(this));
  2369. },
  2370. updateUI: function documentPropertiesUpdateUI(field, content) {
  2371. if (field && content !== undefined && content !== '') {
  2372. field.textContent = content;
  2373. }
  2374. },
  2375. setFileSize: function documentPropertiesSetFileSize(fileSize) {
  2376. if (fileSize > 0) {
  2377. this.rawFileSize = fileSize;
  2378. }
  2379. },
  2380. parseFileSize: function documentPropertiesParseFileSize() {
  2381. var fileSize = this.rawFileSize, kb = fileSize / 1024;
  2382. if (!kb) {
  2383. return;
  2384. } else if (kb < 1024) {
  2385. return mozL10n.get('document_properties_kb', {
  2386. size_kb: (+kb.toPrecision(3)).toLocaleString(),
  2387. size_b: fileSize.toLocaleString()
  2388. }, '{{size_kb}} KB ({{size_b}} bytes)');
  2389. } else {
  2390. return mozL10n.get('document_properties_mb', {
  2391. size_mb: (+(kb / 1024).toPrecision(3)).toLocaleString(),
  2392. size_b: fileSize.toLocaleString()
  2393. }, '{{size_mb}} MB ({{size_b}} bytes)');
  2394. }
  2395. },
  2396. open: function documentPropertiesOpen() {
  2397. Promise.all([OverlayManager.open(this.overlayName),
  2398. this.dataAvailablePromise]).then(function () {
  2399. this.getProperties();
  2400. }.bind(this));
  2401. },
  2402. close: function documentPropertiesClose() {
  2403. OverlayManager.close(this.overlayName);
  2404. },
  2405. parseDate: function documentPropertiesParseDate(inputDate) {
  2406. // This is implemented according to the PDF specification (see
  2407. // http://www.gnupdf.org/Date for an overview), but note that
  2408. // Adobe Reader doesn't handle changing the date to universal time
  2409. // and doesn't use the user's time zone (they're effectively ignoring
  2410. // the HH' and mm' parts of the date string).
  2411. var dateToParse = inputDate;
  2412. if (dateToParse === undefined) {
  2413. return '';
  2414. }
  2415. // Remove the D: prefix if it is available.
  2416. if (dateToParse.substring(0,2) === 'D:') {
  2417. dateToParse = dateToParse.substring(2);
  2418. }
  2419. // Get all elements from the PDF date string.
  2420. // JavaScript's Date object expects the month to be between
  2421. // 0 and 11 instead of 1 and 12, so we're correcting for this.
  2422. var year = parseInt(dateToParse.substring(0,4), 10);
  2423. var month = parseInt(dateToParse.substring(4,6), 10) - 1;
  2424. var day = parseInt(dateToParse.substring(6,8), 10);
  2425. var hours = parseInt(dateToParse.substring(8,10), 10);
  2426. var minutes = parseInt(dateToParse.substring(10,12), 10);
  2427. var seconds = parseInt(dateToParse.substring(12,14), 10);
  2428. var utRel = dateToParse.substring(14,15);
  2429. var offsetHours = parseInt(dateToParse.substring(15,17), 10);
  2430. var offsetMinutes = parseInt(dateToParse.substring(18,20), 10);
  2431. // As per spec, utRel = 'Z' means equal to universal time.
  2432. // The other cases ('-' and '+') have to be handled here.
  2433. if (utRel === '-') {
  2434. hours += offsetHours;
  2435. minutes += offsetMinutes;
  2436. } else if (utRel === '+') {
  2437. hours -= offsetHours;
  2438. minutes -= offsetMinutes;
  2439. }
  2440. // Return the new date format from the user's locale.
  2441. var date = new Date(Date.UTC(year, month, day, hours, minutes, seconds));
  2442. var dateString = date.toLocaleDateString();
  2443. var timeString = date.toLocaleTimeString();
  2444. return mozL10n.get('document_properties_date_string',
  2445. {date: dateString, time: timeString},
  2446. '{{date}}, {{time}}');
  2447. }
  2448. };
  2449. var PresentationModeState = {
  2450. UNKNOWN: 0,
  2451. NORMAL: 1,
  2452. CHANGING: 2,
  2453. FULLSCREEN: 3,
  2454. };
  2455. var IGNORE_CURRENT_POSITION_ON_ZOOM = false;
  2456. var CLEANUP_TIMEOUT = 30000;
  2457. var RenderingStates = {
  2458. INITIAL: 0,
  2459. RUNNING: 1,
  2460. PAUSED: 2,
  2461. FINISHED: 3
  2462. };
  2463. /**
  2464. * Controls rendering of the views for pages and thumbnails.
  2465. * @class
  2466. */
  2467. var PDFRenderingQueue = (function PDFRenderingQueueClosure() {
  2468. /**
  2469. * @constructs
  2470. */
  2471. function PDFRenderingQueue() {
  2472. this.pdfViewer = null;
  2473. this.pdfThumbnailViewer = null;
  2474. this.onIdle = null;
  2475. this.highestPriorityPage = null;
  2476. this.idleTimeout = null;
  2477. this.printing = false;
  2478. this.isThumbnailViewEnabled = false;
  2479. }
  2480. PDFRenderingQueue.prototype = /** @lends PDFRenderingQueue.prototype */ {
  2481. /**
  2482. * @param {PDFViewer} pdfViewer
  2483. */
  2484. setViewer: function PDFRenderingQueue_setViewer(pdfViewer) {
  2485. this.pdfViewer = pdfViewer;
  2486. },
  2487. /**
  2488. * @param {PDFThumbnailViewer} pdfThumbnailViewer
  2489. */
  2490. setThumbnailViewer:
  2491. function PDFRenderingQueue_setThumbnailViewer(pdfThumbnailViewer) {
  2492. this.pdfThumbnailViewer = pdfThumbnailViewer;
  2493. },
  2494. /**
  2495. * @param {IRenderableView} view
  2496. * @returns {boolean}
  2497. */
  2498. isHighestPriority: function PDFRenderingQueue_isHighestPriority(view) {
  2499. return this.highestPriorityPage === view.renderingId;
  2500. },
  2501. renderHighestPriority: function
  2502. PDFRenderingQueue_renderHighestPriority(currentlyVisiblePages) {
  2503. if (this.idleTimeout) {
  2504. clearTimeout(this.idleTimeout);
  2505. this.idleTimeout = null;
  2506. }
  2507. // Pages have a higher priority than thumbnails, so check them first.
  2508. if (this.pdfViewer.forceRendering(currentlyVisiblePages)) {
  2509. return;
  2510. }
  2511. // No pages needed rendering so check thumbnails.
  2512. if (this.pdfThumbnailViewer && this.isThumbnailViewEnabled) {
  2513. if (this.pdfThumbnailViewer.forceRendering()) {
  2514. return;
  2515. }
  2516. }
  2517. if (this.printing) {
  2518. // If printing is currently ongoing do not reschedule cleanup.
  2519. return;
  2520. }
  2521. if (this.onIdle) {
  2522. this.idleTimeout = setTimeout(this.onIdle.bind(this), CLEANUP_TIMEOUT);
  2523. }
  2524. },
  2525. getHighestPriority: function
  2526. PDFRenderingQueue_getHighestPriority(visible, views, scrolledDown) {
  2527. // The state has changed figure out which page has the highest priority to
  2528. // render next (if any).
  2529. // Priority:
  2530. // 1 visible pages
  2531. // 2 if last scrolled down page after the visible pages
  2532. // 2 if last scrolled up page before the visible pages
  2533. var visibleViews = visible.views;
  2534. var numVisible = visibleViews.length;
  2535. if (numVisible === 0) {
  2536. return false;
  2537. }
  2538. for (var i = 0; i < numVisible; ++i) {
  2539. var view = visibleViews[i].view;
  2540. if (!this.isViewFinished(view)) {
  2541. return view;
  2542. }
  2543. }
  2544. // All the visible views have rendered, try to render next/previous pages.
  2545. if (scrolledDown) {
  2546. var nextPageIndex = visible.last.id;
  2547. // ID's start at 1 so no need to add 1.
  2548. if (views[nextPageIndex] &&
  2549. !this.isViewFinished(views[nextPageIndex])) {
  2550. return views[nextPageIndex];
  2551. }
  2552. } else {
  2553. var previousPageIndex = visible.first.id - 2;
  2554. if (views[previousPageIndex] &&
  2555. !this.isViewFinished(views[previousPageIndex])) {
  2556. return views[previousPageIndex];
  2557. }
  2558. }
  2559. // Everything that needs to be rendered has been.
  2560. return null;
  2561. },
  2562. /**
  2563. * @param {IRenderableView} view
  2564. * @returns {boolean}
  2565. */
  2566. isViewFinished: function PDFRenderingQueue_isViewFinished(view) {
  2567. return view.renderingState === RenderingStates.FINISHED;
  2568. },
  2569. /**
  2570. * Render a page or thumbnail view. This calls the appropriate function
  2571. * based on the views state. If the view is already rendered it will return
  2572. * false.
  2573. * @param {IRenderableView} view
  2574. */
  2575. renderView: function PDFRenderingQueue_renderView(view) {
  2576. var state = view.renderingState;
  2577. switch (state) {
  2578. case RenderingStates.FINISHED:
  2579. return false;
  2580. case RenderingStates.PAUSED:
  2581. this.highestPriorityPage = view.renderingId;
  2582. view.resume();
  2583. break;
  2584. case RenderingStates.RUNNING:
  2585. this.highestPriorityPage = view.renderingId;
  2586. break;
  2587. case RenderingStates.INITIAL:
  2588. this.highestPriorityPage = view.renderingId;
  2589. view.draw(this.renderHighestPriority.bind(this));
  2590. break;
  2591. }
  2592. return true;
  2593. },
  2594. };
  2595. return PDFRenderingQueue;
  2596. })();
  2597. /**
  2598. * @constructor
  2599. * @param {HTMLDivElement} container - The viewer element.
  2600. * @param {number} id - The page unique ID (normally its number).
  2601. * @param {number} scale - The page scale display.
  2602. * @param {PageViewport} defaultViewport - The page viewport.
  2603. * @param {IPDFLinkService} linkService - The navigation/linking service.
  2604. * @param {PDFRenderingQueue} renderingQueue - The rendering queue object.
  2605. * @param {Cache} cache - The page cache.
  2606. * @param {PDFPageSource} pageSource
  2607. * @param {PDFViewer} viewer
  2608. *
  2609. * @implements {IRenderableView}
  2610. */
  2611. var PageView = function pageView(container, id, scale, defaultViewport,
  2612. linkService, renderingQueue, cache,
  2613. pageSource, viewer) {
  2614. this.id = id;
  2615. this.renderingId = 'page' + id;
  2616. this.rotation = 0;
  2617. this.scale = scale || 1.0;
  2618. this.viewport = defaultViewport;
  2619. this.pdfPageRotate = defaultViewport.rotation;
  2620. this.hasRestrictedScaling = false;
  2621. this.linkService = linkService;
  2622. this.renderingQueue = renderingQueue;
  2623. this.cache = cache;
  2624. this.pageSource = pageSource;
  2625. this.viewer = viewer;
  2626. this.renderingState = RenderingStates.INITIAL;
  2627. this.resume = null;
  2628. this.textLayer = null;
  2629. this.zoomLayer = null;
  2630. this.annotationLayer = null;
  2631. var anchor = document.createElement('a');
  2632. anchor.name = '' + this.id;
  2633. var div = this.el = document.createElement('div');
  2634. div.id = 'pageContainer' + this.id;
  2635. div.className = 'page';
  2636. div.style.width = Math.floor(this.viewport.width) + 'px';
  2637. div.style.height = Math.floor(this.viewport.height) + 'px';
  2638. container.appendChild(anchor);
  2639. container.appendChild(div);
  2640. this.setPdfPage = function pageViewSetPdfPage(pdfPage) {
  2641. this.pdfPage = pdfPage;
  2642. this.pdfPageRotate = pdfPage.rotate;
  2643. var totalRotation = (this.rotation + this.pdfPageRotate) % 360;
  2644. this.viewport = pdfPage.getViewport(this.scale * CSS_UNITS, totalRotation);
  2645. this.stats = pdfPage.stats;
  2646. this.reset();
  2647. };
  2648. this.destroy = function pageViewDestroy() {
  2649. this.zoomLayer = null;
  2650. this.reset();
  2651. if (this.pdfPage) {
  2652. this.pdfPage.destroy();
  2653. }
  2654. };
  2655. this.reset = function pageViewReset(keepAnnotations) {
  2656. if (this.renderTask) {
  2657. this.renderTask.cancel();
  2658. }
  2659. this.resume = null;
  2660. this.renderingState = RenderingStates.INITIAL;
  2661. div.style.width = Math.floor(this.viewport.width) + 'px';
  2662. div.style.height = Math.floor(this.viewport.height) + 'px';
  2663. var childNodes = div.childNodes;
  2664. for (var i = div.childNodes.length - 1; i >= 0; i--) {
  2665. var node = childNodes[i];
  2666. if ((this.zoomLayer && this.zoomLayer === node) ||
  2667. (keepAnnotations && this.annotationLayer === node)) {
  2668. continue;
  2669. }
  2670. div.removeChild(node);
  2671. }
  2672. div.removeAttribute('data-loaded');
  2673. if (keepAnnotations) {
  2674. if (this.annotationLayer) {
  2675. // Hide annotationLayer until all elements are resized
  2676. // so they are not displayed on the already-resized page
  2677. this.annotationLayer.setAttribute('hidden', 'true');
  2678. }
  2679. } else {
  2680. this.annotationLayer = null;
  2681. }
  2682. if (this.canvas) {
  2683. // Zeroing the width and height causes Firefox to release graphics
  2684. // resources immediately, which can greatly reduce memory consumption.
  2685. this.canvas.width = 0;
  2686. this.canvas.height = 0;
  2687. delete this.canvas;
  2688. }
  2689. this.loadingIconDiv = document.createElement('div');
  2690. this.loadingIconDiv.className = 'loadingIcon';
  2691. div.appendChild(this.loadingIconDiv);
  2692. };
  2693. this.update = function pageViewUpdate(scale, rotation) {
  2694. this.scale = scale || this.scale;
  2695. if (typeof rotation !== 'undefined') {
  2696. this.rotation = rotation;
  2697. }
  2698. var totalRotation = (this.rotation + this.pdfPageRotate) % 360;
  2699. this.viewport = this.viewport.clone({
  2700. scale: this.scale * CSS_UNITS,
  2701. rotation: totalRotation
  2702. });
  2703. var isScalingRestricted = false;
  2704. if (this.canvas && PDFJS.maxCanvasPixels > 0) {
  2705. var ctx = this.canvas.getContext('2d');
  2706. var outputScale = getOutputScale(ctx);
  2707. var pixelsInViewport = this.viewport.width * this.viewport.height;
  2708. var maxScale = Math.sqrt(PDFJS.maxCanvasPixels / pixelsInViewport);
  2709. if (((Math.floor(this.viewport.width) * outputScale.sx) | 0) *
  2710. ((Math.floor(this.viewport.height) * outputScale.sy) | 0) >
  2711. PDFJS.maxCanvasPixels) {
  2712. isScalingRestricted = true;
  2713. }
  2714. }
  2715. if (this.canvas &&
  2716. (PDFJS.useOnlyCssZoom ||
  2717. (this.hasRestrictedScaling && isScalingRestricted))) {
  2718. this.cssTransform(this.canvas, true);
  2719. return;
  2720. } else if (this.canvas && !this.zoomLayer) {
  2721. this.zoomLayer = this.canvas.parentNode;
  2722. this.zoomLayer.style.position = 'absolute';
  2723. }
  2724. if (this.zoomLayer) {
  2725. this.cssTransform(this.zoomLayer.firstChild);
  2726. }
  2727. this.reset(true);
  2728. };
  2729. this.cssTransform = function pageCssTransform(canvas, redrawAnnotations) {
  2730. // Scale canvas, canvas wrapper, and page container.
  2731. var width = this.viewport.width;
  2732. var height = this.viewport.height;
  2733. canvas.style.width = canvas.parentNode.style.width = div.style.width =
  2734. Math.floor(width) + 'px';
  2735. canvas.style.height = canvas.parentNode.style.height = div.style.height =
  2736. Math.floor(height) + 'px';
  2737. // The canvas may have been originally rotated, so rotate relative to that.
  2738. var relativeRotation = this.viewport.rotation - canvas._viewport.rotation;
  2739. var absRotation = Math.abs(relativeRotation);
  2740. var scaleX = 1, scaleY = 1;
  2741. if (absRotation === 90 || absRotation === 270) {
  2742. // Scale x and y because of the rotation.
  2743. scaleX = height / width;
  2744. scaleY = width / height;
  2745. }
  2746. var cssTransform = 'rotate(' + relativeRotation + 'deg) ' +
  2747. 'scale(' + scaleX + ',' + scaleY + ')';
  2748. CustomStyle.setProp('transform', canvas, cssTransform);
  2749. if (this.textLayer) {
  2750. // Rotating the text layer is more complicated since the divs inside the
  2751. // the text layer are rotated.
  2752. // TODO: This could probably be simplified by drawing the text layer in
  2753. // one orientation then rotating overall.
  2754. var textLayerViewport = this.textLayer.viewport;
  2755. var textRelativeRotation = this.viewport.rotation -
  2756. textLayerViewport.rotation;
  2757. var textAbsRotation = Math.abs(textRelativeRotation);
  2758. var scale = width / textLayerViewport.width;
  2759. if (textAbsRotation === 90 || textAbsRotation === 270) {
  2760. scale = width / textLayerViewport.height;
  2761. }
  2762. var textLayerDiv = this.textLayer.textLayerDiv;
  2763. var transX, transY;
  2764. switch (textAbsRotation) {
  2765. case 0:
  2766. transX = transY = 0;
  2767. break;
  2768. case 90:
  2769. transX = 0;
  2770. transY = '-' + textLayerDiv.style.height;
  2771. break;
  2772. case 180:
  2773. transX = '-' + textLayerDiv.style.width;
  2774. transY = '-' + textLayerDiv.style.height;
  2775. break;
  2776. case 270:
  2777. transX = '-' + textLayerDiv.style.width;
  2778. transY = 0;
  2779. break;
  2780. default:
  2781. console.error('Bad rotation value.');
  2782. break;
  2783. }
  2784. CustomStyle.setProp('transform', textLayerDiv,
  2785. 'rotate(' + textAbsRotation + 'deg) ' +
  2786. 'scale(' + scale + ', ' + scale + ') ' +
  2787. 'translate(' + transX + ', ' + transY + ')');
  2788. CustomStyle.setProp('transformOrigin', textLayerDiv, '0% 0%');
  2789. }
  2790. if (redrawAnnotations && this.annotationLayer) {
  2791. setupAnnotations(div, this.pdfPage, this.viewport);
  2792. }
  2793. };
  2794. Object.defineProperty(this, 'width', {
  2795. get: function PageView_getWidth() {
  2796. return this.viewport.width;
  2797. },
  2798. enumerable: true
  2799. });
  2800. Object.defineProperty(this, 'height', {
  2801. get: function PageView_getHeight() {
  2802. return this.viewport.height;
  2803. },
  2804. enumerable: true
  2805. });
  2806. var self = this;
  2807. function setupAnnotations(pageDiv, pdfPage, viewport) {
  2808. function bindLink(link, dest) {
  2809. link.href = linkService.getDestinationHash(dest);
  2810. link.onclick = function pageViewSetupLinksOnclick() {
  2811. if (dest) {
  2812. linkService.navigateTo(dest);
  2813. }
  2814. return false;
  2815. };
  2816. if (dest) {
  2817. link.className = 'internalLink';
  2818. }
  2819. }
  2820. function bindNamedAction(link, action) {
  2821. link.href = linkService.getAnchorUrl('');
  2822. link.onclick = function pageViewSetupNamedActionOnClick() {
  2823. linkService.executeNamedAction(action);
  2824. return false;
  2825. };
  2826. link.className = 'internalLink';
  2827. }
  2828. pdfPage.getAnnotations().then(function(annotationsData) {
  2829. viewport = viewport.clone({ dontFlip: true });
  2830. var transform = viewport.transform;
  2831. var transformStr = 'matrix(' + transform.join(',') + ')';
  2832. var data, element, i, ii;
  2833. if (self.annotationLayer) {
  2834. // If an annotationLayer already exists, refresh its children's
  2835. // transformation matrices
  2836. for (i = 0, ii = annotationsData.length; i < ii; i++) {
  2837. data = annotationsData[i];
  2838. element = self.annotationLayer.querySelector(
  2839. '[data-annotation-id="' + data.id + '"]');
  2840. if (element) {
  2841. CustomStyle.setProp('transform', element, transformStr);
  2842. }
  2843. }
  2844. // See this.reset()
  2845. self.annotationLayer.removeAttribute('hidden');
  2846. } else {
  2847. for (i = 0, ii = annotationsData.length; i < ii; i++) {
  2848. data = annotationsData[i];
  2849. if (!data || !data.hasHtml) {
  2850. continue;
  2851. }
  2852. element = PDFJS.AnnotationUtils.getHtmlElement(data,
  2853. pdfPage.commonObjs);
  2854. element.setAttribute('data-annotation-id', data.id);
  2855. mozL10n.translate(element);
  2856. var rect = data.rect;
  2857. var view = pdfPage.view;
  2858. rect = PDFJS.Util.normalizeRect([
  2859. rect[0],
  2860. view[3] - rect[1] + view[1],
  2861. rect[2],
  2862. view[3] - rect[3] + view[1]
  2863. ]);
  2864. element.style.left = rect[0] + 'px';
  2865. element.style.top = rect[1] + 'px';
  2866. element.style.position = 'absolute';
  2867. CustomStyle.setProp('transform', element, transformStr);
  2868. var transformOriginStr = -rect[0] + 'px ' + -rect[1] + 'px';
  2869. CustomStyle.setProp('transformOrigin', element, transformOriginStr);
  2870. if (data.subtype === 'Link' && !data.url) {
  2871. var link = element.getElementsByTagName('a')[0];
  2872. if (link) {
  2873. if (data.action) {
  2874. bindNamedAction(link, data.action);
  2875. } else {
  2876. bindLink(link, ('dest' in data) ? data.dest : null);
  2877. }
  2878. }
  2879. }
  2880. if (!self.annotationLayer) {
  2881. var annotationLayerDiv = document.createElement('div');
  2882. annotationLayerDiv.className = 'annotationLayer';
  2883. pageDiv.appendChild(annotationLayerDiv);
  2884. self.annotationLayer = annotationLayerDiv;
  2885. }
  2886. self.annotationLayer.appendChild(element);
  2887. }
  2888. }
  2889. });
  2890. }
  2891. this.getPagePoint = function pageViewGetPagePoint(x, y) {
  2892. return this.viewport.convertToPdfPoint(x, y);
  2893. };
  2894. this.draw = function pageviewDraw(callback) {
  2895. var pdfPage = this.pdfPage;
  2896. if (this.pagePdfPromise) {
  2897. return;
  2898. }
  2899. if (!pdfPage) {
  2900. var promise = this.pageSource.getPage();
  2901. promise.then(function(pdfPage) {
  2902. delete this.pagePdfPromise;
  2903. this.setPdfPage(pdfPage);
  2904. this.draw(callback);
  2905. }.bind(this));
  2906. this.pagePdfPromise = promise;
  2907. return;
  2908. }
  2909. if (this.renderingState !== RenderingStates.INITIAL) {
  2910. console.error('Must be in new state before drawing');
  2911. }
  2912. this.renderingState = RenderingStates.RUNNING;
  2913. var viewport = this.viewport;
  2914. // Wrap the canvas so if it has a css transform for highdpi the overflow
  2915. // will be hidden in FF.
  2916. var canvasWrapper = document.createElement('div');
  2917. canvasWrapper.style.width = div.style.width;
  2918. canvasWrapper.style.height = div.style.height;
  2919. canvasWrapper.classList.add('canvasWrapper');
  2920. var canvas = document.createElement('canvas');
  2921. canvas.id = 'page' + this.id;
  2922. canvasWrapper.appendChild(canvas);
  2923. if (this.annotationLayer) {
  2924. // annotationLayer needs to stay on top
  2925. div.insertBefore(canvasWrapper, this.annotationLayer);
  2926. } else {
  2927. div.appendChild(canvasWrapper);
  2928. }
  2929. this.canvas = canvas;
  2930. var ctx = canvas.getContext('2d');
  2931. var outputScale = getOutputScale(ctx);
  2932. if (PDFJS.useOnlyCssZoom) {
  2933. var actualSizeViewport = viewport.clone({ scale: CSS_UNITS });
  2934. // Use a scale that will make the canvas be the original intended size
  2935. // of the page.
  2936. outputScale.sx *= actualSizeViewport.width / viewport.width;
  2937. outputScale.sy *= actualSizeViewport.height / viewport.height;
  2938. outputScale.scaled = true;
  2939. }
  2940. if (PDFJS.maxCanvasPixels > 0) {
  2941. var pixelsInViewport = viewport.width * viewport.height;
  2942. var maxScale = Math.sqrt(PDFJS.maxCanvasPixels / pixelsInViewport);
  2943. if (outputScale.sx > maxScale || outputScale.sy > maxScale) {
  2944. outputScale.sx = maxScale;
  2945. outputScale.sy = maxScale;
  2946. outputScale.scaled = true;
  2947. this.hasRestrictedScaling = true;
  2948. } else {
  2949. this.hasRestrictedScaling = false;
  2950. }
  2951. }
  2952. canvas.width = (Math.floor(viewport.width) * outputScale.sx) | 0;
  2953. canvas.height = (Math.floor(viewport.height) * outputScale.sy) | 0;
  2954. canvas.style.width = Math.floor(viewport.width) + 'px';
  2955. canvas.style.height = Math.floor(viewport.height) + 'px';
  2956. // Add the viewport so it's known what it was originally drawn with.
  2957. canvas._viewport = viewport;
  2958. var textLayerDiv = null;
  2959. var textLayer = null;
  2960. if (!PDFJS.disableTextLayer) {
  2961. textLayerDiv = document.createElement('div');
  2962. textLayerDiv.className = 'textLayer';
  2963. textLayerDiv.style.width = canvas.style.width;
  2964. textLayerDiv.style.height = canvas.style.height;
  2965. if (this.annotationLayer) {
  2966. // annotationLayer needs to stay on top
  2967. div.insertBefore(textLayerDiv, this.annotationLayer);
  2968. } else {
  2969. div.appendChild(textLayerDiv);
  2970. }
  2971. textLayer = this.viewer.createTextLayerBuilder(textLayerDiv, this.id - 1,
  2972. this.viewport);
  2973. }
  2974. this.textLayer = textLayer;
  2975. // TODO(mack): use data attributes to store these
  2976. ctx._scaleX = outputScale.sx;
  2977. ctx._scaleY = outputScale.sy;
  2978. if (outputScale.scaled) {
  2979. ctx.scale(outputScale.sx, outputScale.sy);
  2980. }
  2981. // Rendering area
  2982. var self = this;
  2983. function pageViewDrawCallback(error) {
  2984. // The renderTask may have been replaced by a new one, so only remove the
  2985. // reference to the renderTask if it matches the one that is triggering
  2986. // this callback.
  2987. if (renderTask === self.renderTask) {
  2988. self.renderTask = null;
  2989. }
  2990. if (error === 'cancelled') {
  2991. return;
  2992. }
  2993. self.renderingState = RenderingStates.FINISHED;
  2994. if (self.loadingIconDiv) {
  2995. div.removeChild(self.loadingIconDiv);
  2996. delete self.loadingIconDiv;
  2997. }
  2998. if (self.zoomLayer) {
  2999. div.removeChild(self.zoomLayer);
  3000. self.zoomLayer = null;
  3001. }
  3002. self.error = error;
  3003. self.stats = pdfPage.stats;
  3004. self.updateStats();
  3005. if (self.onAfterDraw) {
  3006. self.onAfterDraw();
  3007. }
  3008. var event = document.createEvent('CustomEvent');
  3009. event.initCustomEvent('pagerender', true, true, {
  3010. pageNumber: pdfPage.pageNumber
  3011. });
  3012. div.dispatchEvent(event);
  3013. callback();
  3014. }
  3015. var renderContext = {
  3016. canvasContext: ctx,
  3017. viewport: this.viewport,
  3018. // intent: 'default', // === 'display'
  3019. continueCallback: function pdfViewcContinueCallback(cont) {
  3020. if (!self.renderingQueue.isHighestPriority(self)) {
  3021. self.renderingState = RenderingStates.PAUSED;
  3022. self.resume = function resumeCallback() {
  3023. self.renderingState = RenderingStates.RUNNING;
  3024. cont();
  3025. };
  3026. return;
  3027. }
  3028. cont();
  3029. }
  3030. };
  3031. var renderTask = this.renderTask = this.pdfPage.render(renderContext);
  3032. this.renderTask.promise.then(
  3033. function pdfPageRenderCallback() {
  3034. pageViewDrawCallback(null);
  3035. if (textLayer) {
  3036. self.pdfPage.getTextContent().then(
  3037. function textContentResolved(textContent) {
  3038. textLayer.setTextContent(textContent);
  3039. }
  3040. );
  3041. }
  3042. },
  3043. function pdfPageRenderError(error) {
  3044. pageViewDrawCallback(error);
  3045. }
  3046. );
  3047. setupAnnotations(div, pdfPage, this.viewport);
  3048. div.setAttribute('data-loaded', true);
  3049. // Add the page to the cache at the start of drawing. That way it can be
  3050. // evicted from the cache and destroyed even if we pause its rendering.
  3051. cache.push(this);
  3052. };
  3053. this.beforePrint = function pageViewBeforePrint() {
  3054. var pdfPage = this.pdfPage;
  3055. var viewport = pdfPage.getViewport(1);
  3056. // Use the same hack we use for high dpi displays for printing to get better
  3057. // output until bug 811002 is fixed in FF.
  3058. var PRINT_OUTPUT_SCALE = 2;
  3059. var canvas = document.createElement('canvas');
  3060. canvas.width = Math.floor(viewport.width) * PRINT_OUTPUT_SCALE;
  3061. canvas.height = Math.floor(viewport.height) * PRINT_OUTPUT_SCALE;
  3062. canvas.style.width = (PRINT_OUTPUT_SCALE * viewport.width) + 'pt';
  3063. canvas.style.height = (PRINT_OUTPUT_SCALE * viewport.height) + 'pt';
  3064. var cssScale = 'scale(' + (1 / PRINT_OUTPUT_SCALE) + ', ' +
  3065. (1 / PRINT_OUTPUT_SCALE) + ')';
  3066. CustomStyle.setProp('transform' , canvas, cssScale);
  3067. CustomStyle.setProp('transformOrigin' , canvas, '0% 0%');
  3068. var printContainer = document.getElementById('printContainer');
  3069. var canvasWrapper = document.createElement('div');
  3070. canvasWrapper.style.width = viewport.width + 'pt';
  3071. canvasWrapper.style.height = viewport.height + 'pt';
  3072. canvasWrapper.appendChild(canvas);
  3073. printContainer.appendChild(canvasWrapper);
  3074. canvas.mozPrintCallback = function(obj) {
  3075. var ctx = obj.context;
  3076. ctx.save();
  3077. ctx.fillStyle = 'rgb(255, 255, 255)';
  3078. ctx.fillRect(0, 0, canvas.width, canvas.height);
  3079. ctx.restore();
  3080. ctx.scale(PRINT_OUTPUT_SCALE, PRINT_OUTPUT_SCALE);
  3081. var renderContext = {
  3082. canvasContext: ctx,
  3083. viewport: viewport,
  3084. intent: 'print'
  3085. };
  3086. pdfPage.render(renderContext).promise.then(function() {
  3087. // Tell the printEngine that rendering this canvas/page has finished.
  3088. obj.done();
  3089. }, function(error) {
  3090. console.error(error);
  3091. // Tell the printEngine that rendering this canvas/page has failed.
  3092. // This will make the print proces stop.
  3093. if ('abort' in obj) {
  3094. obj.abort();
  3095. } else {
  3096. obj.done();
  3097. }
  3098. });
  3099. };
  3100. };
  3101. this.updateStats = function pageViewUpdateStats() {
  3102. if (!this.stats) {
  3103. return;
  3104. }
  3105. if (PDFJS.pdfBug && Stats.enabled) {
  3106. var stats = this.stats;
  3107. Stats.add(this.id, stats);
  3108. }
  3109. };
  3110. };
  3111. var FIND_SCROLL_OFFSET_TOP = -50;
  3112. var FIND_SCROLL_OFFSET_LEFT = -400;
  3113. var MAX_TEXT_DIVS_TO_RENDER = 100000;
  3114. var RENDER_DELAY = 200; // ms
  3115. var NonWhitespaceRegexp = /\S/;
  3116. function isAllWhitespace(str) {
  3117. return !NonWhitespaceRegexp.test(str);
  3118. }
  3119. /**
  3120. * @typedef {Object} TextLayerBuilderOptions
  3121. * @property {HTMLDivElement} textLayerDiv - The text layer container.
  3122. * @property {number} pageIndex - The page index.
  3123. * @property {PageViewport} viewport - The viewport of the text layer.
  3124. * @property {ILastScrollSource} lastScrollSource - The object that records when
  3125. * last time scroll happened.
  3126. * @property {boolean} isViewerInPresentationMode
  3127. * @property {PDFFindController} findController
  3128. */
  3129. /**
  3130. * TextLayerBuilder provides text-selection functionality for the PDF.
  3131. * It does this by creating overlay divs over the PDF text. These divs
  3132. * contain text that matches the PDF text they are overlaying. This object
  3133. * also provides a way to highlight text that is being searched for.
  3134. * @class
  3135. */
  3136. var TextLayerBuilder = (function TextLayerBuilderClosure() {
  3137. function TextLayerBuilder(options) {
  3138. this.textLayerDiv = options.textLayerDiv;
  3139. this.layoutDone = false;
  3140. this.divContentDone = false;
  3141. this.pageIdx = options.pageIndex;
  3142. this.matches = [];
  3143. this.lastScrollSource = options.lastScrollSource || null;
  3144. this.viewport = options.viewport;
  3145. this.isViewerInPresentationMode = options.isViewerInPresentationMode;
  3146. this.textDivs = [];
  3147. this.findController = options.findController || null;
  3148. }
  3149. TextLayerBuilder.prototype = {
  3150. renderLayer: function TextLayerBuilder_renderLayer() {
  3151. var textLayerFrag = document.createDocumentFragment();
  3152. var textDivs = this.textDivs;
  3153. var textDivsLength = textDivs.length;
  3154. var canvas = document.createElement('canvas');
  3155. var ctx = canvas.getContext('2d');
  3156. // No point in rendering many divs as it would make the browser
  3157. // unusable even after the divs are rendered.
  3158. if (textDivsLength > MAX_TEXT_DIVS_TO_RENDER) {
  3159. return;
  3160. }
  3161. var lastFontSize;
  3162. var lastFontFamily;
  3163. for (var i = 0; i < textDivsLength; i++) {
  3164. var textDiv = textDivs[i];
  3165. if (textDiv.dataset.isWhitespace !== undefined) {
  3166. continue;
  3167. }
  3168. var fontSize = textDiv.style.fontSize;
  3169. var fontFamily = textDiv.style.fontFamily;
  3170. // Only build font string and set to context if different from last.
  3171. if (fontSize !== lastFontSize || fontFamily !== lastFontFamily) {
  3172. ctx.font = fontSize + ' ' + fontFamily;
  3173. lastFontSize = fontSize;
  3174. lastFontFamily = fontFamily;
  3175. }
  3176. var width = ctx.measureText(textDiv.textContent).width;
  3177. if (width > 0) {
  3178. textLayerFrag.appendChild(textDiv);
  3179. var transform;
  3180. if (textDiv.dataset.canvasWidth !== undefined) {
  3181. // Dataset values come of type string.
  3182. var textScale = textDiv.dataset.canvasWidth / width;
  3183. transform = 'scaleX(' + textScale + ')';
  3184. } else {
  3185. transform = '';
  3186. }
  3187. var rotation = textDiv.dataset.angle;
  3188. if (rotation) {
  3189. transform = 'rotate(' + rotation + 'deg) ' + transform;
  3190. }
  3191. if (transform) {
  3192. CustomStyle.setProp('transform' , textDiv, transform);
  3193. }
  3194. }
  3195. }
  3196. this.textLayerDiv.appendChild(textLayerFrag);
  3197. this.renderingDone = true;
  3198. this.updateMatches();
  3199. },
  3200. setupRenderLayoutTimer:
  3201. function TextLayerBuilder_setupRenderLayoutTimer() {
  3202. // Schedule renderLayout() if the user has been scrolling,
  3203. // otherwise run it right away.
  3204. var self = this;
  3205. var lastScroll = (this.lastScrollSource === null ?
  3206. 0 : this.lastScrollSource.lastScroll);
  3207. if (Date.now() - lastScroll > RENDER_DELAY) { // Render right away
  3208. this.renderLayer();
  3209. } else { // Schedule
  3210. if (this.renderTimer) {
  3211. clearTimeout(this.renderTimer);
  3212. }
  3213. this.renderTimer = setTimeout(function() {
  3214. self.setupRenderLayoutTimer();
  3215. }, RENDER_DELAY);
  3216. }
  3217. },
  3218. appendText: function TextLayerBuilder_appendText(geom, styles) {
  3219. var style = styles[geom.fontName];
  3220. var textDiv = document.createElement('div');
  3221. this.textDivs.push(textDiv);
  3222. if (isAllWhitespace(geom.str)) {
  3223. textDiv.dataset.isWhitespace = true;
  3224. return;
  3225. }
  3226. var tx = PDFJS.Util.transform(this.viewport.transform, geom.transform);
  3227. var angle = Math.atan2(tx[1], tx[0]);
  3228. if (style.vertical) {
  3229. angle += Math.PI / 2;
  3230. }
  3231. var fontHeight = Math.sqrt((tx[2] * tx[2]) + (tx[3] * tx[3]));
  3232. var fontAscent = fontHeight;
  3233. if (style.ascent) {
  3234. fontAscent = style.ascent * fontAscent;
  3235. } else if (style.descent) {
  3236. fontAscent = (1 + style.descent) * fontAscent;
  3237. }
  3238. var left;
  3239. var top;
  3240. if (angle === 0) {
  3241. left = tx[4];
  3242. top = tx[5] - fontAscent;
  3243. } else {
  3244. left = tx[4] + (fontAscent * Math.sin(angle));
  3245. top = tx[5] - (fontAscent * Math.cos(angle));
  3246. }
  3247. textDiv.style.left = left + 'px';
  3248. textDiv.style.top = top + 'px';
  3249. textDiv.style.fontSize = fontHeight + 'px';
  3250. textDiv.style.fontFamily = style.fontFamily;
  3251. textDiv.textContent = geom.str;
  3252. // |fontName| is only used by the Font Inspector. This test will succeed
  3253. // when e.g. the Font Inspector is off but the Stepper is on, but it's
  3254. // not worth the effort to do a more accurate test.
  3255. if (PDFJS.pdfBug) {
  3256. textDiv.dataset.fontName = geom.fontName;
  3257. }
  3258. // Storing into dataset will convert number into string.
  3259. if (angle !== 0) {
  3260. textDiv.dataset.angle = angle * (180 / Math.PI);
  3261. }
  3262. // We don't bother scaling single-char text divs, because it has very
  3263. // little effect on text highlighting. This makes scrolling on docs with
  3264. // lots of such divs a lot faster.
  3265. if (textDiv.textContent.length > 1) {
  3266. if (style.vertical) {
  3267. textDiv.dataset.canvasWidth = geom.height * this.viewport.scale;
  3268. } else {
  3269. textDiv.dataset.canvasWidth = geom.width * this.viewport.scale;
  3270. }
  3271. }
  3272. },
  3273. setTextContent: function TextLayerBuilder_setTextContent(textContent) {
  3274. this.textContent = textContent;
  3275. var textItems = textContent.items;
  3276. for (var i = 0, len = textItems.length; i < len; i++) {
  3277. this.appendText(textItems[i], textContent.styles);
  3278. }
  3279. this.divContentDone = true;
  3280. this.setupRenderLayoutTimer();
  3281. },
  3282. convertMatches: function TextLayerBuilder_convertMatches(matches) {
  3283. var i = 0;
  3284. var iIndex = 0;
  3285. var bidiTexts = this.textContent.items;
  3286. var end = bidiTexts.length - 1;
  3287. var queryLen = (this.findController === null ?
  3288. 0 : this.findController.state.query.length);
  3289. var ret = [];
  3290. for (var m = 0, len = matches.length; m < len; m++) {
  3291. // Calculate the start position.
  3292. var matchIdx = matches[m];
  3293. // Loop over the divIdxs.
  3294. while (i !== end && matchIdx >= (iIndex + bidiTexts[i].str.length)) {
  3295. iIndex += bidiTexts[i].str.length;
  3296. i++;
  3297. }
  3298. if (i === bidiTexts.length) {
  3299. console.error('Could not find a matching mapping');
  3300. }
  3301. var match = {
  3302. begin: {
  3303. divIdx: i,
  3304. offset: matchIdx - iIndex
  3305. }
  3306. };
  3307. // Calculate the end position.
  3308. matchIdx += queryLen;
  3309. // Somewhat the same array as above, but use > instead of >= to get
  3310. // the end position right.
  3311. while (i !== end && matchIdx > (iIndex + bidiTexts[i].str.length)) {
  3312. iIndex += bidiTexts[i].str.length;
  3313. i++;
  3314. }
  3315. match.end = {
  3316. divIdx: i,
  3317. offset: matchIdx - iIndex
  3318. };
  3319. ret.push(match);
  3320. }
  3321. return ret;
  3322. },
  3323. renderMatches: function TextLayerBuilder_renderMatches(matches) {
  3324. // Early exit if there is nothing to render.
  3325. if (matches.length === 0) {
  3326. return;
  3327. }
  3328. var bidiTexts = this.textContent.items;
  3329. var textDivs = this.textDivs;
  3330. var prevEnd = null;
  3331. var isSelectedPage = (this.findController === null ?
  3332. false : (this.pageIdx === this.findController.selected.pageIdx));
  3333. var selectedMatchIdx = (this.findController === null ?
  3334. -1 : this.findController.selected.matchIdx);
  3335. var highlightAll = (this.findController === null ?
  3336. false : this.findController.state.highlightAll);
  3337. var infinity = {
  3338. divIdx: -1,
  3339. offset: undefined
  3340. };
  3341. function beginText(begin, className) {
  3342. var divIdx = begin.divIdx;
  3343. textDivs[divIdx].textContent = '';
  3344. appendTextToDiv(divIdx, 0, begin.offset, className);
  3345. }
  3346. function appendTextToDiv(divIdx, fromOffset, toOffset, className) {
  3347. var div = textDivs[divIdx];
  3348. var content = bidiTexts[divIdx].str.substring(fromOffset, toOffset);
  3349. var node = document.createTextNode(content);
  3350. if (className) {
  3351. var span = document.createElement('span');
  3352. span.className = className;
  3353. span.appendChild(node);
  3354. div.appendChild(span);
  3355. return;
  3356. }
  3357. div.appendChild(node);
  3358. }
  3359. var i0 = selectedMatchIdx, i1 = i0 + 1;
  3360. if (highlightAll) {
  3361. i0 = 0;
  3362. i1 = matches.length;
  3363. } else if (!isSelectedPage) {
  3364. // Not highlighting all and this isn't the selected page, so do nothing.
  3365. return;
  3366. }
  3367. for (var i = i0; i < i1; i++) {
  3368. var match = matches[i];
  3369. var begin = match.begin;
  3370. var end = match.end;
  3371. var isSelected = (isSelectedPage && i === selectedMatchIdx);
  3372. var highlightSuffix = (isSelected ? ' selected' : '');
  3373. if (isSelected && !this.isViewerInPresentationMode) {
  3374. scrollIntoView(textDivs[begin.divIdx],
  3375. { top: FIND_SCROLL_OFFSET_TOP,
  3376. left: FIND_SCROLL_OFFSET_LEFT });
  3377. }
  3378. // Match inside new div.
  3379. if (!prevEnd || begin.divIdx !== prevEnd.divIdx) {
  3380. // If there was a previous div, then add the text at the end.
  3381. if (prevEnd !== null) {
  3382. appendTextToDiv(prevEnd.divIdx, prevEnd.offset, infinity.offset);
  3383. }
  3384. // Clear the divs and set the content until the starting point.
  3385. beginText(begin);
  3386. } else {
  3387. appendTextToDiv(prevEnd.divIdx, prevEnd.offset, begin.offset);
  3388. }
  3389. if (begin.divIdx === end.divIdx) {
  3390. appendTextToDiv(begin.divIdx, begin.offset, end.offset,
  3391. 'highlight' + highlightSuffix);
  3392. } else {
  3393. appendTextToDiv(begin.divIdx, begin.offset, infinity.offset,
  3394. 'highlight begin' + highlightSuffix);
  3395. for (var n0 = begin.divIdx + 1, n1 = end.divIdx; n0 < n1; n0++) {
  3396. textDivs[n0].className = 'highlight middle' + highlightSuffix;
  3397. }
  3398. beginText(end, 'highlight end' + highlightSuffix);
  3399. }
  3400. prevEnd = end;
  3401. }
  3402. if (prevEnd) {
  3403. appendTextToDiv(prevEnd.divIdx, prevEnd.offset, infinity.offset);
  3404. }
  3405. },
  3406. updateMatches: function TextLayerBuilder_updateMatches() {
  3407. // Only show matches when all rendering is done.
  3408. if (!this.renderingDone) {
  3409. return;
  3410. }
  3411. // Clear all matches.
  3412. var matches = this.matches;
  3413. var textDivs = this.textDivs;
  3414. var bidiTexts = this.textContent.items;
  3415. var clearedUntilDivIdx = -1;
  3416. // Clear all current matches.
  3417. for (var i = 0, len = matches.length; i < len; i++) {
  3418. var match = matches[i];
  3419. var begin = Math.max(clearedUntilDivIdx, match.begin.divIdx);
  3420. for (var n = begin, end = match.end.divIdx; n <= end; n++) {
  3421. var div = textDivs[n];
  3422. div.textContent = bidiTexts[n].str;
  3423. div.className = '';
  3424. }
  3425. clearedUntilDivIdx = match.end.divIdx + 1;
  3426. }
  3427. if (this.findController === null || !this.findController.active) {
  3428. return;
  3429. }
  3430. // Convert the matches on the page controller into the match format
  3431. // used for the textLayer.
  3432. this.matches = this.convertMatches(this.findController === null ?
  3433. [] : (this.findController.pageMatches[this.pageIdx] || []));
  3434. this.renderMatches(this.matches);
  3435. }
  3436. };
  3437. return TextLayerBuilder;
  3438. })();
  3439. /**
  3440. * @typedef {Object} PDFViewerOptions
  3441. * @property {HTMLDivElement} container - The container for the viewer element.
  3442. * @property {HTMLDivElement} viewer - (optional) The viewer element.
  3443. * @property {IPDFLinkService} linkService - The navigation/linking service.
  3444. * @property {PDFRenderingQueue} renderingQueue - (optional) The rendering
  3445. * queue object.
  3446. */
  3447. /**
  3448. * Simple viewer control to display PDF content/pages.
  3449. * @class
  3450. * @implements {ILastScrollSource}
  3451. * @implements {IRenderableView}
  3452. */
  3453. var PDFViewer = (function pdfViewer() {
  3454. /**
  3455. * @constructs PDFViewer
  3456. * @param {PDFViewerOptions} options
  3457. */
  3458. function PDFViewer(options) {
  3459. this.container = options.container;
  3460. this.viewer = options.viewer || options.container.firstElementChild;
  3461. this.linkService = options.linkService || new SimpleLinkService(this);
  3462. this.defaultRenderingQueue = !options.renderingQueue;
  3463. if (this.defaultRenderingQueue) {
  3464. // Custom rendering queue is not specified, using default one
  3465. this.renderingQueue = new PDFRenderingQueue();
  3466. this.renderingQueue.setViewer(this);
  3467. } else {
  3468. this.renderingQueue = options.renderingQueue;
  3469. }
  3470. this.scroll = watchScroll(this.container, this._scrollUpdate.bind(this));
  3471. this.lastScroll = 0;
  3472. this.updateInProgress = false;
  3473. this.presentationModeState = PresentationModeState.UNKNOWN;
  3474. this._resetView();
  3475. }
  3476. PDFViewer.prototype = /** @lends PDFViewer.prototype */{
  3477. get pagesCount() {
  3478. return this.pages.length;
  3479. },
  3480. getPageView: function (index) {
  3481. return this.pages[index];
  3482. },
  3483. get currentPageNumber() {
  3484. return this._currentPageNumber;
  3485. },
  3486. set currentPageNumber(val) {
  3487. if (!this.pdfDocument) {
  3488. this._currentPageNumber = val;
  3489. return;
  3490. }
  3491. var event = document.createEvent('UIEvents');
  3492. event.initUIEvent('pagechange', true, true, window, 0);
  3493. event.updateInProgress = this.updateInProgress;
  3494. if (!(0 < val && val <= this.pagesCount)) {
  3495. event.pageNumber = this._currentPageNumber;
  3496. event.previousPageNumber = val;
  3497. this.container.dispatchEvent(event);
  3498. return;
  3499. }
  3500. this.pages[val - 1].updateStats();
  3501. event.previousPageNumber = this._currentPageNumber;
  3502. this._currentPageNumber = val;
  3503. event.pageNumber = val;
  3504. this.container.dispatchEvent(event);
  3505. },
  3506. /**
  3507. * @returns {number}
  3508. */
  3509. get currentScale() {
  3510. return this._currentScale;
  3511. },
  3512. /**
  3513. * @param {number} val - Scale of the pages in percents.
  3514. */
  3515. set currentScale(val) {
  3516. if (isNaN(val)) {
  3517. throw new Error('Invalid numeric scale');
  3518. }
  3519. if (!this.pdfDocument) {
  3520. this._currentScale = val;
  3521. this._currentScaleValue = val.toString();
  3522. return;
  3523. }
  3524. this._setScale(val, false);
  3525. },
  3526. /**
  3527. * @returns {string}
  3528. */
  3529. get currentScaleValue() {
  3530. return this._currentScaleValue;
  3531. },
  3532. /**
  3533. * @param val - The scale of the pages (in percent or predefined value).
  3534. */
  3535. set currentScaleValue(val) {
  3536. if (!this.pdfDocument) {
  3537. this._currentScale = isNaN(val) ? UNKNOWN_SCALE : val;
  3538. this._currentScaleValue = val;
  3539. return;
  3540. }
  3541. this._setScale(val, false);
  3542. },
  3543. /**
  3544. * @returns {number}
  3545. */
  3546. get pagesRotation() {
  3547. return this._pagesRotation;
  3548. },
  3549. /**
  3550. * @param {number} rotation - The rotation of the pages (0, 90, 180, 270).
  3551. */
  3552. set pagesRotation(rotation) {
  3553. this._pagesRotation = rotation;
  3554. for (var i = 0, l = this.pages.length; i < l; i++) {
  3555. var page = this.pages[i];
  3556. page.update(page.scale, rotation);
  3557. }
  3558. this._setScale(this._currentScaleValue, true);
  3559. },
  3560. /**
  3561. * @param pdfDocument {PDFDocument}
  3562. */
  3563. setDocument: function (pdfDocument) {
  3564. if (this.pdfDocument) {
  3565. this._resetView();
  3566. }
  3567. this.pdfDocument = pdfDocument;
  3568. if (!pdfDocument) {
  3569. return;
  3570. }
  3571. var pagesCount = pdfDocument.numPages;
  3572. var pagesRefMap = this.pagesRefMap = {};
  3573. var self = this;
  3574. var resolvePagesPromise;
  3575. var pagesPromise = new Promise(function (resolve) {
  3576. resolvePagesPromise = resolve;
  3577. });
  3578. this.pagesPromise = pagesPromise;
  3579. pagesPromise.then(function () {
  3580. var event = document.createEvent('CustomEvent');
  3581. event.initCustomEvent('pagesloaded', true, true, {
  3582. pagesCount: pagesCount
  3583. });
  3584. self.container.dispatchEvent(event);
  3585. });
  3586. var isOnePageRenderedResolved = false;
  3587. var resolveOnePageRendered = null;
  3588. var onePageRendered = new Promise(function (resolve) {
  3589. resolveOnePageRendered = resolve;
  3590. });
  3591. this.onePageRendered = onePageRendered;
  3592. var bindOnAfterDraw = function (pageView) {
  3593. // when page is painted, using the image as thumbnail base
  3594. pageView.onAfterDraw = function pdfViewLoadOnAfterDraw() {
  3595. if (!isOnePageRenderedResolved) {
  3596. isOnePageRenderedResolved = true;
  3597. resolveOnePageRendered();
  3598. }
  3599. var event = document.createEvent('CustomEvent');
  3600. event.initCustomEvent('pagerendered', true, true, {
  3601. pageNumber: pageView.id
  3602. });
  3603. self.container.dispatchEvent(event);
  3604. };
  3605. };
  3606. var firstPagePromise = pdfDocument.getPage(1);
  3607. this.firstPagePromise = firstPagePromise;
  3608. // Fetch a single page so we can get a viewport that will be the default
  3609. // viewport for all pages
  3610. return firstPagePromise.then(function(pdfPage) {
  3611. var scale = this._currentScale || 1.0;
  3612. var viewport = pdfPage.getViewport(scale * CSS_UNITS);
  3613. for (var pageNum = 1; pageNum <= pagesCount; ++pageNum) {
  3614. var pageSource = new PDFPageSource(pdfDocument, pageNum);
  3615. var pageView = new PageView(this.viewer, pageNum, scale,
  3616. viewport.clone(), this.linkService,
  3617. this.renderingQueue, this.cache,
  3618. pageSource, this);
  3619. bindOnAfterDraw(pageView);
  3620. this.pages.push(pageView);
  3621. }
  3622. // Fetch all the pages since the viewport is needed before printing
  3623. // starts to create the correct size canvas. Wait until one page is
  3624. // rendered so we don't tie up too many resources early on.
  3625. onePageRendered.then(function () {
  3626. if (!PDFJS.disableAutoFetch) {
  3627. var getPagesLeft = pagesCount;
  3628. for (var pageNum = 1; pageNum <= pagesCount; ++pageNum) {
  3629. pdfDocument.getPage(pageNum).then(function (pageNum, pdfPage) {
  3630. var pageView = self.pages[pageNum - 1];
  3631. if (!pageView.pdfPage) {
  3632. pageView.setPdfPage(pdfPage);
  3633. }
  3634. var refStr = pdfPage.ref.num + ' ' + pdfPage.ref.gen + ' R';
  3635. pagesRefMap[refStr] = pageNum;
  3636. getPagesLeft--;
  3637. if (!getPagesLeft) {
  3638. resolvePagesPromise();
  3639. }
  3640. }.bind(null, pageNum));
  3641. }
  3642. } else {
  3643. // XXX: Printing is semi-broken with auto fetch disabled.
  3644. resolvePagesPromise();
  3645. }
  3646. });
  3647. var event = document.createEvent('CustomEvent');
  3648. event.initCustomEvent('pagesinit', true, true, null);
  3649. self.container.dispatchEvent(event);
  3650. if (this.defaultRenderingQueue) {
  3651. this.update();
  3652. }
  3653. }.bind(this));
  3654. },
  3655. _resetView: function () {
  3656. this.cache = new Cache(DEFAULT_CACHE_SIZE);
  3657. this.pages = [];
  3658. this._currentPageNumber = 1;
  3659. this._currentScale = UNKNOWN_SCALE;
  3660. this._currentScaleValue = null;
  3661. this.location = null;
  3662. this._pagesRotation = 0;
  3663. var container = this.viewer;
  3664. while (container.hasChildNodes()) {
  3665. container.removeChild(container.lastChild);
  3666. }
  3667. },
  3668. _scrollUpdate: function () {
  3669. this.lastScroll = Date.now();
  3670. if (this.pagesCount === 0) {
  3671. return;
  3672. }
  3673. this.update();
  3674. },
  3675. _setScaleUpdatePages: function pdfViewer_setScaleUpdatePages(
  3676. newScale, newValue, noScroll, preset) {
  3677. this._currentScaleValue = newValue;
  3678. if (newScale === this._currentScale) {
  3679. return;
  3680. }
  3681. for (var i = 0, ii = this.pages.length; i < ii; i++) {
  3682. this.pages[i].update(newScale);
  3683. }
  3684. this._currentScale = newScale;
  3685. if (!noScroll) {
  3686. var page = this._currentPageNumber, dest;
  3687. var inPresentationMode =
  3688. this.presentationModeState === PresentationModeState.CHANGING ||
  3689. this.presentationModeState === PresentationModeState.FULLSCREEN;
  3690. if (this.location && !inPresentationMode &&
  3691. !IGNORE_CURRENT_POSITION_ON_ZOOM) {
  3692. page = this.location.pageNumber;
  3693. dest = [null, { name: 'XYZ' }, this.location.left,
  3694. this.location.top, null];
  3695. }
  3696. this.scrollPageIntoView(page, dest);
  3697. }
  3698. var event = document.createEvent('UIEvents');
  3699. event.initUIEvent('scalechange', true, true, window, 0);
  3700. event.scale = newScale;
  3701. if (preset) {
  3702. event.presetValue = newValue;
  3703. }
  3704. this.container.dispatchEvent(event);
  3705. },
  3706. _setScale: function pdfViewer_setScale(value, noScroll) {
  3707. if (value === 'custom') {
  3708. return;
  3709. }
  3710. var scale = parseFloat(value);
  3711. if (scale > 0) {
  3712. this._setScaleUpdatePages(scale, value, noScroll, false);
  3713. } else {
  3714. var currentPage = this.pages[this._currentPageNumber - 1];
  3715. if (!currentPage) {
  3716. return;
  3717. }
  3718. var inPresentationMode =
  3719. this.presentationModeState === PresentationModeState.FULLSCREEN;
  3720. var hPadding = inPresentationMode ? 0 : SCROLLBAR_PADDING;
  3721. var vPadding = inPresentationMode ? 0 : VERTICAL_PADDING;
  3722. var pageWidthScale = (this.container.clientWidth - hPadding) /
  3723. currentPage.width * currentPage.scale;
  3724. var pageHeightScale = (this.container.clientHeight - vPadding) /
  3725. currentPage.height * currentPage.scale;
  3726. switch (value) {
  3727. case 'page-actual':
  3728. scale = 1;
  3729. break;
  3730. case 'page-width':
  3731. scale = pageWidthScale;
  3732. break;
  3733. case 'page-height':
  3734. scale = pageHeightScale;
  3735. break;
  3736. case 'page-fit':
  3737. scale = Math.min(pageWidthScale, pageHeightScale);
  3738. break;
  3739. case 'auto':
  3740. var isLandscape = (currentPage.width > currentPage.height);
  3741. // For pages in landscape mode, fit the page height to the viewer
  3742. // *unless* the page would thus become too wide to fit horizontally.
  3743. var horizontalScale = isLandscape ?
  3744. Math.min(pageHeightScale, pageWidthScale) : pageWidthScale;
  3745. scale = Math.min(MAX_AUTO_SCALE, horizontalScale);
  3746. break;
  3747. default:
  3748. console.error('pdfViewSetScale: \'' + value +
  3749. '\' is an unknown zoom value.');
  3750. return;
  3751. }
  3752. this._setScaleUpdatePages(scale, value, noScroll, true);
  3753. }
  3754. },
  3755. /**
  3756. * Scrolls page into view.
  3757. * @param {number} pageNumber
  3758. * @param {Array} dest - (optional) original PDF destination array:
  3759. * <page-ref> </XYZ|FitXXX> <args..>
  3760. */
  3761. scrollPageIntoView: function PDFViewer_scrollPageIntoView(pageNumber,
  3762. dest) {
  3763. var pageView = this.pages[pageNumber - 1];
  3764. var pageViewDiv = pageView.el;
  3765. if (this.presentationModeState ===
  3766. PresentationModeState.FULLSCREEN) {
  3767. if (this.linkService.page !== pageView.id) {
  3768. // Avoid breaking getVisiblePages in presentation mode.
  3769. this.linkService.page = pageView.id;
  3770. return;
  3771. }
  3772. dest = null;
  3773. // Fixes the case when PDF has different page sizes.
  3774. this._setScale(this.currentScaleValue, true);
  3775. }
  3776. if (!dest) {
  3777. scrollIntoView(pageViewDiv);
  3778. return;
  3779. }
  3780. var x = 0, y = 0;
  3781. var width = 0, height = 0, widthScale, heightScale;
  3782. var changeOrientation = (pageView.rotation % 180 === 0 ? false : true);
  3783. var pageWidth = (changeOrientation ? pageView.height : pageView.width) /
  3784. pageView.scale / CSS_UNITS;
  3785. var pageHeight = (changeOrientation ? pageView.width : pageView.height) /
  3786. pageView.scale / CSS_UNITS;
  3787. var scale = 0;
  3788. switch (dest[1].name) {
  3789. case 'XYZ':
  3790. x = dest[2];
  3791. y = dest[3];
  3792. scale = dest[4];
  3793. // If x and/or y coordinates are not supplied, default to
  3794. // _top_ left of the page (not the obvious bottom left,
  3795. // since aligning the bottom of the intended page with the
  3796. // top of the window is rarely helpful).
  3797. x = x !== null ? x : 0;
  3798. y = y !== null ? y : pageHeight;
  3799. break;
  3800. case 'Fit':
  3801. case 'FitB':
  3802. scale = 'page-fit';
  3803. break;
  3804. case 'FitH':
  3805. case 'FitBH':
  3806. y = dest[2];
  3807. scale = 'page-width';
  3808. break;
  3809. case 'FitV':
  3810. case 'FitBV':
  3811. x = dest[2];
  3812. width = pageWidth;
  3813. height = pageHeight;
  3814. scale = 'page-height';
  3815. break;
  3816. case 'FitR':
  3817. x = dest[2];
  3818. y = dest[3];
  3819. width = dest[4] - x;
  3820. height = dest[5] - y;
  3821. var viewerContainer = this.container;
  3822. widthScale = (viewerContainer.clientWidth - SCROLLBAR_PADDING) /
  3823. width / CSS_UNITS;
  3824. heightScale = (viewerContainer.clientHeight - SCROLLBAR_PADDING) /
  3825. height / CSS_UNITS;
  3826. scale = Math.min(Math.abs(widthScale), Math.abs(heightScale));
  3827. break;
  3828. default:
  3829. return;
  3830. }
  3831. if (scale && scale !== this.currentScale) {
  3832. this.currentScaleValue = scale;
  3833. } else if (this.currentScale === UNKNOWN_SCALE) {
  3834. this.currentScaleValue = DEFAULT_SCALE;
  3835. }
  3836. if (scale === 'page-fit' && !dest[4]) {
  3837. scrollIntoView(pageViewDiv);
  3838. return;
  3839. }
  3840. var boundingRect = [
  3841. pageView.viewport.convertToViewportPoint(x, y),
  3842. pageView.viewport.convertToViewportPoint(x + width, y + height)
  3843. ];
  3844. var left = Math.min(boundingRect[0][0], boundingRect[1][0]);
  3845. var top = Math.min(boundingRect[0][1], boundingRect[1][1]);
  3846. scrollIntoView(pageViewDiv, { left: left, top: top });
  3847. },
  3848. _updateLocation: function (firstPage) {
  3849. var currentScale = this._currentScale;
  3850. var currentScaleValue = this._currentScaleValue;
  3851. var normalizedScaleValue =
  3852. parseFloat(currentScaleValue) === currentScale ?
  3853. Math.round(currentScale * 10000) / 100 : currentScaleValue;
  3854. var pageNumber = firstPage.id;
  3855. var pdfOpenParams = '#page=' + pageNumber;
  3856. pdfOpenParams += '&zoom=' + normalizedScaleValue;
  3857. var currentPageView = this.pages[pageNumber - 1];
  3858. var container = this.container;
  3859. var topLeft = currentPageView.getPagePoint(
  3860. (container.scrollLeft - firstPage.x),
  3861. (container.scrollTop - firstPage.y));
  3862. var intLeft = Math.round(topLeft[0]);
  3863. var intTop = Math.round(topLeft[1]);
  3864. pdfOpenParams += ',' + intLeft + ',' + intTop;
  3865. this.location = {
  3866. pageNumber: pageNumber,
  3867. scale: normalizedScaleValue,
  3868. top: intTop,
  3869. left: intLeft,
  3870. pdfOpenParams: pdfOpenParams
  3871. };
  3872. },
  3873. update: function () {
  3874. var visible = this._getVisiblePages();
  3875. var visiblePages = visible.views;
  3876. if (visiblePages.length === 0) {
  3877. return;
  3878. }
  3879. this.updateInProgress = true;
  3880. var suggestedCacheSize = Math.max(DEFAULT_CACHE_SIZE,
  3881. 2 * visiblePages.length + 1);
  3882. this.cache.resize(suggestedCacheSize);
  3883. this.renderingQueue.renderHighestPriority(visible);
  3884. var currentId = this.currentPageNumber;
  3885. var firstPage = visible.first;
  3886. for (var i = 0, ii = visiblePages.length, stillFullyVisible = false;
  3887. i < ii; ++i) {
  3888. var page = visiblePages[i];
  3889. if (page.percent < 100) {
  3890. break;
  3891. }
  3892. if (page.id === currentId) {
  3893. stillFullyVisible = true;
  3894. break;
  3895. }
  3896. }
  3897. if (!stillFullyVisible) {
  3898. currentId = visiblePages[0].id;
  3899. }
  3900. if (this.presentationModeState !== PresentationModeState.FULLSCREEN) {
  3901. this.currentPageNumber = currentId;
  3902. }
  3903. this._updateLocation(firstPage);
  3904. this.updateInProgress = false;
  3905. var event = document.createEvent('UIEvents');
  3906. event.initUIEvent('updateviewarea', true, true, window, 0);
  3907. this.container.dispatchEvent(event);
  3908. },
  3909. containsElement: function (element) {
  3910. return this.container.contains(element);
  3911. },
  3912. focus: function () {
  3913. this.container.focus();
  3914. },
  3915. blur: function () {
  3916. this.container.blur();
  3917. },
  3918. get isHorizontalScrollbarEnabled() {
  3919. return (this.presentationModeState === PresentationModeState.FULLSCREEN ?
  3920. false : (this.container.scrollWidth > this.container.clientWidth));
  3921. },
  3922. _getVisiblePages: function () {
  3923. if (this.presentationModeState !== PresentationModeState.FULLSCREEN) {
  3924. return getVisibleElements(this.container, this.pages, true);
  3925. } else {
  3926. // The algorithm in getVisibleElements doesn't work in all browsers and
  3927. // configurations when presentation mode is active.
  3928. var visible = [];
  3929. var currentPage = this.pages[this._currentPageNumber - 1];
  3930. visible.push({ id: currentPage.id, view: currentPage });
  3931. return { first: currentPage, last: currentPage, views: visible };
  3932. }
  3933. },
  3934. cleanup: function () {
  3935. for (var i = 0, ii = this.pages.length; i < ii; i++) {
  3936. if (this.pages[i] &&
  3937. this.pages[i].renderingState !== RenderingStates.FINISHED) {
  3938. this.pages[i].reset();
  3939. }
  3940. }
  3941. },
  3942. forceRendering: function (currentlyVisiblePages) {
  3943. var visiblePages = currentlyVisiblePages || this._getVisiblePages();
  3944. var pageView = this.renderingQueue.getHighestPriority(visiblePages,
  3945. this.pages,
  3946. this.scroll.down);
  3947. if (pageView) {
  3948. this.renderingQueue.renderView(pageView);
  3949. return true;
  3950. }
  3951. return false;
  3952. },
  3953. getPageTextContent: function (pageIndex) {
  3954. return this.pdfDocument.getPage(pageIndex + 1).then(function (page) {
  3955. return page.getTextContent();
  3956. });
  3957. },
  3958. /**
  3959. * @param textLayerDiv {HTMLDivElement}
  3960. * @param pageIndex {number}
  3961. * @param viewport {PageViewport}
  3962. * @returns {TextLayerBuilder}
  3963. */
  3964. createTextLayerBuilder: function (textLayerDiv, pageIndex, viewport) {
  3965. var isViewerInPresentationMode =
  3966. this.presentationModeState === PresentationModeState.FULLSCREEN;
  3967. return new TextLayerBuilder({
  3968. textLayerDiv: textLayerDiv,
  3969. pageIndex: pageIndex,
  3970. viewport: viewport,
  3971. lastScrollSource: this,
  3972. isViewerInPresentationMode: isViewerInPresentationMode,
  3973. findController: this.findController
  3974. });
  3975. },
  3976. setFindController: function (findController) {
  3977. this.findController = findController;
  3978. },
  3979. };
  3980. return PDFViewer;
  3981. })();
  3982. var SimpleLinkService = (function SimpleLinkServiceClosure() {
  3983. function SimpleLinkService(pdfViewer) {
  3984. this.pdfViewer = pdfViewer;
  3985. }
  3986. SimpleLinkService.prototype = {
  3987. /**
  3988. * @returns {number}
  3989. */
  3990. get page() {
  3991. return this.pdfViewer.currentPageNumber;
  3992. },
  3993. /**
  3994. * @param {number} value
  3995. */
  3996. set page(value) {
  3997. this.pdfViewer.currentPageNumber = value;
  3998. },
  3999. /**
  4000. * @param dest - The PDF destination object.
  4001. */
  4002. navigateTo: function (dest) {},
  4003. /**
  4004. * @param dest - The PDF destination object.
  4005. * @returns {string} The hyperlink to the PDF object.
  4006. */
  4007. getDestinationHash: function (dest) {
  4008. return '#';
  4009. },
  4010. /**
  4011. * @param hash - The PDF parameters/hash.
  4012. * @returns {string} The hyperlink to the PDF object.
  4013. */
  4014. getAnchorUrl: function (hash) {
  4015. return '#';
  4016. },
  4017. /**
  4018. * @param {string} hash
  4019. */
  4020. setHash: function (hash) {},
  4021. /**
  4022. * @param {string} action
  4023. */
  4024. executeNamedAction: function (action) {},
  4025. };
  4026. return SimpleLinkService;
  4027. })();
  4028. /**
  4029. * PDFPage object source.
  4030. * @class
  4031. */
  4032. var PDFPageSource = (function PDFPageSourceClosure() {
  4033. /**
  4034. * @constructs
  4035. * @param {PDFDocument} pdfDocument
  4036. * @param {number} pageNumber
  4037. * @constructor
  4038. */
  4039. function PDFPageSource(pdfDocument, pageNumber) {
  4040. this.pdfDocument = pdfDocument;
  4041. this.pageNumber = pageNumber;
  4042. }
  4043. PDFPageSource.prototype = /** @lends PDFPageSource.prototype */ {
  4044. /**
  4045. * @returns {Promise<PDFPage>}
  4046. */
  4047. getPage: function () {
  4048. return this.pdfDocument.getPage(this.pageNumber);
  4049. }
  4050. };
  4051. return PDFPageSource;
  4052. })();
  4053. var PDFViewerApplication = {
  4054. initialBookmark: document.location.hash.substring(1),
  4055. initialized: false,
  4056. fellback: false,
  4057. pdfDocument: null,
  4058. sidebarOpen: false,
  4059. printing: false,
  4060. /** @type {PDFViewer} */
  4061. pdfViewer: null,
  4062. /** @type {PDFThumbnailViewer} */
  4063. pdfThumbnailViewer: null,
  4064. /** @type {PDFRenderingQueue} */
  4065. pdfRenderingQueue: null,
  4066. pageRotation: 0,
  4067. updateScaleControls: true,
  4068. isInitialViewSet: false,
  4069. animationStartedPromise: null,
  4070. mouseScrollTimeStamp: 0,
  4071. mouseScrollDelta: 0,
  4072. preferenceSidebarViewOnLoad: SidebarView.NONE,
  4073. preferencePdfBugEnabled: false,
  4074. isViewerEmbedded: (window.parent !== window),
  4075. url: '',
  4076. // called once when the document is loaded
  4077. initialize: function pdfViewInitialize() {
  4078. var pdfRenderingQueue = new PDFRenderingQueue();
  4079. pdfRenderingQueue.onIdle = this.cleanup.bind(this);
  4080. this.pdfRenderingQueue = pdfRenderingQueue;
  4081. var container = document.getElementById('viewerContainer');
  4082. var viewer = document.getElementById('viewer');
  4083. this.pdfViewer = new PDFViewer({
  4084. container: container,
  4085. viewer: viewer,
  4086. renderingQueue: pdfRenderingQueue,
  4087. linkService: this
  4088. });
  4089. pdfRenderingQueue.setViewer(this.pdfViewer);
  4090. var thumbnailContainer = document.getElementById('thumbnailView');
  4091. this.pdfThumbnailViewer = new PDFThumbnailViewer({
  4092. container: thumbnailContainer,
  4093. renderingQueue: pdfRenderingQueue,
  4094. linkService: this
  4095. });
  4096. pdfRenderingQueue.setThumbnailViewer(this.pdfThumbnailViewer);
  4097. Preferences.initialize();
  4098. this.findController = new PDFFindController({
  4099. pdfViewer: this.pdfViewer,
  4100. integratedFind: this.supportsIntegratedFind
  4101. });
  4102. this.pdfViewer.setFindController(this.findController);
  4103. this.findBar = new PDFFindBar({
  4104. bar: document.getElementById('findbar'),
  4105. toggleButton: document.getElementById('viewFind'),
  4106. findField: document.getElementById('findInput'),
  4107. highlightAllCheckbox: document.getElementById('findHighlightAll'),
  4108. caseSensitiveCheckbox: document.getElementById('findMatchCase'),
  4109. findMsg: document.getElementById('findMsg'),
  4110. findStatusIcon: document.getElementById('findStatusIcon'),
  4111. findPreviousButton: document.getElementById('findPrevious'),
  4112. findNextButton: document.getElementById('findNext'),
  4113. findController: this.findController
  4114. });
  4115. this.findController.setFindBar(this.findBar);
  4116. HandTool.initialize({
  4117. container: container,
  4118. toggleHandTool: document.getElementById('toggleHandTool')
  4119. });
  4120. SecondaryToolbar.initialize({
  4121. toolbar: document.getElementById('secondaryToolbar'),
  4122. presentationMode: PresentationMode,
  4123. toggleButton: document.getElementById('secondaryToolbarToggle'),
  4124. presentationModeButton:
  4125. document.getElementById('secondaryPresentationMode'),
  4126. openFile: document.getElementById('secondaryOpenFile'),
  4127. print: document.getElementById('secondaryPrint'),
  4128. download: document.getElementById('secondaryDownload'),
  4129. viewBookmark: document.getElementById('secondaryViewBookmark'),
  4130. firstPage: document.getElementById('firstPage'),
  4131. lastPage: document.getElementById('lastPage'),
  4132. pageRotateCw: document.getElementById('pageRotateCw'),
  4133. pageRotateCcw: document.getElementById('pageRotateCcw'),
  4134. documentProperties: DocumentProperties,
  4135. documentPropertiesButton: document.getElementById('documentProperties')
  4136. });
  4137. PresentationMode.initialize({
  4138. container: container,
  4139. secondaryToolbar: SecondaryToolbar,
  4140. firstPage: document.getElementById('contextFirstPage'),
  4141. lastPage: document.getElementById('contextLastPage'),
  4142. pageRotateCw: document.getElementById('contextPageRotateCw'),
  4143. pageRotateCcw: document.getElementById('contextPageRotateCcw')
  4144. });
  4145. PasswordPrompt.initialize({
  4146. overlayName: 'passwordOverlay',
  4147. passwordField: document.getElementById('password'),
  4148. passwordText: document.getElementById('passwordText'),
  4149. passwordSubmit: document.getElementById('passwordSubmit'),
  4150. passwordCancel: document.getElementById('passwordCancel')
  4151. });
  4152. DocumentProperties.initialize({
  4153. overlayName: 'documentPropertiesOverlay',
  4154. closeButton: document.getElementById('documentPropertiesClose'),
  4155. fileNameField: document.getElementById('fileNameField'),
  4156. fileSizeField: document.getElementById('fileSizeField'),
  4157. titleField: document.getElementById('titleField'),
  4158. authorField: document.getElementById('authorField'),
  4159. subjectField: document.getElementById('subjectField'),
  4160. keywordsField: document.getElementById('keywordsField'),
  4161. creationDateField: document.getElementById('creationDateField'),
  4162. modificationDateField: document.getElementById('modificationDateField'),
  4163. creatorField: document.getElementById('creatorField'),
  4164. producerField: document.getElementById('producerField'),
  4165. versionField: document.getElementById('versionField'),
  4166. pageCountField: document.getElementById('pageCountField')
  4167. });
  4168. var self = this;
  4169. var initializedPromise = Promise.all([
  4170. Preferences.get('enableWebGL').then(function resolved(value) {
  4171. PDFJS.disableWebGL = !value;
  4172. }),
  4173. Preferences.get('sidebarViewOnLoad').then(function resolved(value) {
  4174. self.preferenceSidebarViewOnLoad = value;
  4175. }),
  4176. Preferences.get('pdfBugEnabled').then(function resolved(value) {
  4177. self.preferencePdfBugEnabled = value;
  4178. }),
  4179. Preferences.get('disableTextLayer').then(function resolved(value) {
  4180. if (PDFJS.disableTextLayer === true) {
  4181. return;
  4182. }
  4183. PDFJS.disableTextLayer = value;
  4184. }),
  4185. Preferences.get('disableRange').then(function resolved(value) {
  4186. if (PDFJS.disableRange === true) {
  4187. return;
  4188. }
  4189. PDFJS.disableRange = value;
  4190. }),
  4191. Preferences.get('disableAutoFetch').then(function resolved(value) {
  4192. PDFJS.disableAutoFetch = value;
  4193. }),
  4194. Preferences.get('disableFontFace').then(function resolved(value) {
  4195. if (PDFJS.disableFontFace === true) {
  4196. return;
  4197. }
  4198. PDFJS.disableFontFace = value;
  4199. }),
  4200. Preferences.get('useOnlyCssZoom').then(function resolved(value) {
  4201. PDFJS.useOnlyCssZoom = value;
  4202. })
  4203. // TODO move more preferences and other async stuff here
  4204. ]).catch(function (reason) { });
  4205. return initializedPromise.then(function () {
  4206. PDFViewerApplication.initialized = true;
  4207. });
  4208. },
  4209. zoomIn: function pdfViewZoomIn(ticks) {
  4210. var newScale = this.pdfViewer.currentScale;
  4211. do {
  4212. newScale = (newScale * DEFAULT_SCALE_DELTA).toFixed(2);
  4213. newScale = Math.ceil(newScale * 10) / 10;
  4214. newScale = Math.min(MAX_SCALE, newScale);
  4215. } while (--ticks && newScale < MAX_SCALE);
  4216. this.setScale(newScale, true);
  4217. },
  4218. zoomOut: function pdfViewZoomOut(ticks) {
  4219. var newScale = this.pdfViewer.currentScale;
  4220. do {
  4221. newScale = (newScale / DEFAULT_SCALE_DELTA).toFixed(2);
  4222. newScale = Math.floor(newScale * 10) / 10;
  4223. newScale = Math.max(MIN_SCALE, newScale);
  4224. } while (--ticks && newScale > MIN_SCALE);
  4225. this.setScale(newScale, true);
  4226. },
  4227. get currentScaleValue() {
  4228. return this.pdfViewer.currentScaleValue;
  4229. },
  4230. get pagesCount() {
  4231. return this.pdfDocument.numPages;
  4232. },
  4233. set page(val) {
  4234. this.pdfViewer.currentPageNumber = val;
  4235. },
  4236. get page() {
  4237. return this.pdfViewer.currentPageNumber;
  4238. },
  4239. get supportsPrinting() {
  4240. var canvas = document.createElement('canvas');
  4241. var value = 'mozPrintCallback' in canvas;
  4242. // shadow
  4243. Object.defineProperty(this, 'supportsPrinting', { value: value,
  4244. enumerable: true,
  4245. configurable: true,
  4246. writable: false });
  4247. return value;
  4248. },
  4249. get supportsFullscreen() {
  4250. var doc = document.documentElement;
  4251. var support = doc.requestFullscreen || doc.mozRequestFullScreen ||
  4252. doc.webkitRequestFullScreen || doc.msRequestFullscreen;
  4253. if (document.fullscreenEnabled === false ||
  4254. document.mozFullScreenEnabled === false ||
  4255. document.webkitFullscreenEnabled === false ||
  4256. document.msFullscreenEnabled === false) {
  4257. support = false;
  4258. }
  4259. Object.defineProperty(this, 'supportsFullscreen', { value: support,
  4260. enumerable: true,
  4261. configurable: true,
  4262. writable: false });
  4263. return support;
  4264. },
  4265. get supportsIntegratedFind() {
  4266. var support = false;
  4267. Object.defineProperty(this, 'supportsIntegratedFind', { value: support,
  4268. enumerable: true,
  4269. configurable: true,
  4270. writable: false });
  4271. return support;
  4272. },
  4273. get supportsDocumentFonts() {
  4274. var support = true;
  4275. Object.defineProperty(this, 'supportsDocumentFonts', { value: support,
  4276. enumerable: true,
  4277. configurable: true,
  4278. writable: false });
  4279. return support;
  4280. },
  4281. get supportsDocumentColors() {
  4282. var support = true;
  4283. Object.defineProperty(this, 'supportsDocumentColors', { value: support,
  4284. enumerable: true,
  4285. configurable: true,
  4286. writable: false });
  4287. return support;
  4288. },
  4289. get loadingBar() {
  4290. var bar = new ProgressBar('#loadingBar', {});
  4291. Object.defineProperty(this, 'loadingBar', { value: bar,
  4292. enumerable: true,
  4293. configurable: true,
  4294. writable: false });
  4295. return bar;
  4296. },
  4297. setTitleUsingUrl: function pdfViewSetTitleUsingUrl(url) {
  4298. this.url = url;
  4299. try {
  4300. this.setTitle(decodeURIComponent(getFileName(url)) || url);
  4301. } catch (e) {
  4302. // decodeURIComponent may throw URIError,
  4303. // fall back to using the unprocessed url in that case
  4304. this.setTitle(url);
  4305. }
  4306. },
  4307. setTitle: function pdfViewSetTitle(title) {
  4308. document.title = title;
  4309. },
  4310. close: function pdfViewClose() {
  4311. var errorWrapper = document.getElementById('errorWrapper');
  4312. errorWrapper.setAttribute('hidden', 'true');
  4313. if (!this.pdfDocument) {
  4314. return;
  4315. }
  4316. this.pdfDocument.destroy();
  4317. this.pdfDocument = null;
  4318. this.pdfThumbnailViewer.setDocument(null);
  4319. this.pdfViewer.setDocument(null);
  4320. if (typeof PDFBug !== 'undefined') {
  4321. PDFBug.cleanup();
  4322. }
  4323. },
  4324. // TODO(mack): This function signature should really be pdfViewOpen(url, args)
  4325. open: function pdfViewOpen(file, scale, password,
  4326. pdfDataRangeTransport, args) {
  4327. if (this.pdfDocument) {
  4328. // Reload the preferences if a document was previously opened.
  4329. Preferences.reload();
  4330. }
  4331. this.close();
  4332. var parameters = {password: password};
  4333. if (typeof file === 'string') { // URL
  4334. this.setTitleUsingUrl(file);
  4335. parameters.url = file;
  4336. } else if (file && 'byteLength' in file) { // ArrayBuffer
  4337. parameters.data = file;
  4338. } else if (file.url && file.originalUrl) {
  4339. this.setTitleUsingUrl(file.originalUrl);
  4340. parameters.url = file.url;
  4341. }
  4342. if (args) {
  4343. for (var prop in args) {
  4344. parameters[prop] = args[prop];
  4345. }
  4346. }
  4347. var self = this;
  4348. self.loading = true;
  4349. self.downloadComplete = false;
  4350. var passwordNeeded = function passwordNeeded(updatePassword, reason) {
  4351. PasswordPrompt.updatePassword = updatePassword;
  4352. PasswordPrompt.reason = reason;
  4353. PasswordPrompt.open();
  4354. };
  4355. function getDocumentProgress(progressData) {
  4356. self.progress(progressData.loaded / progressData.total);
  4357. }
  4358. PDFJS.getDocument(parameters, pdfDataRangeTransport, passwordNeeded,
  4359. getDocumentProgress).then(
  4360. function getDocumentCallback(pdfDocument) {
  4361. self.load(pdfDocument, scale);
  4362. self.loading = false;
  4363. },
  4364. function getDocumentError(exception) {
  4365. var message = exception && exception.message;
  4366. var loadingErrorMessage = mozL10n.get('loading_error', null,
  4367. 'An error occurred while loading the PDF.');
  4368. if (exception instanceof PDFJS.InvalidPDFException) {
  4369. // change error message also for other builds
  4370. loadingErrorMessage = mozL10n.get('invalid_file_error', null,
  4371. 'Invalid or corrupted PDF file.');
  4372. } else if (exception instanceof PDFJS.MissingPDFException) {
  4373. // special message for missing PDF's
  4374. loadingErrorMessage = mozL10n.get('missing_file_error', null,
  4375. 'Missing PDF file.');
  4376. } else if (exception instanceof PDFJS.UnexpectedResponseException) {
  4377. loadingErrorMessage = mozL10n.get('unexpected_response_error', null,
  4378. 'Unexpected server response.');
  4379. }
  4380. var moreInfo = {
  4381. message: message
  4382. };
  4383. self.error(loadingErrorMessage, moreInfo);
  4384. self.loading = false;
  4385. }
  4386. );
  4387. if (args && args.length) {
  4388. DocumentProperties.setFileSize(args.length);
  4389. }
  4390. },
  4391. download: function pdfViewDownload() {
  4392. function downloadByUrl() {
  4393. downloadManager.downloadUrl(url, filename);
  4394. }
  4395. var url = this.url.split('#')[0];
  4396. var filename = getPDFFileNameFromURL(url);
  4397. var downloadManager = new DownloadManager();
  4398. downloadManager.onerror = function (err) {
  4399. // This error won't really be helpful because it's likely the
  4400. // fallback won't work either (or is already open).
  4401. PDFViewerApplication.error('PDF failed to download.');
  4402. };
  4403. if (!this.pdfDocument) { // the PDF is not ready yet
  4404. downloadByUrl();
  4405. return;
  4406. }
  4407. if (!this.downloadComplete) { // the PDF is still downloading
  4408. downloadByUrl();
  4409. return;
  4410. }
  4411. this.pdfDocument.getData().then(
  4412. function getDataSuccess(data) {
  4413. var blob = PDFJS.createBlob(data, 'application/pdf');
  4414. downloadManager.download(blob, url, filename);
  4415. },
  4416. downloadByUrl // Error occurred try downloading with just the url.
  4417. ).then(null, downloadByUrl);
  4418. },
  4419. fallback: function pdfViewFallback(featureId) {
  4420. return;
  4421. },
  4422. navigateTo: function pdfViewNavigateTo(dest) {
  4423. var destString = '';
  4424. var self = this;
  4425. var goToDestination = function(destRef) {
  4426. self.pendingRefStr = null;
  4427. // dest array looks like that: <page-ref> </XYZ|FitXXX> <args..>
  4428. var pageNumber = destRef instanceof Object ?
  4429. self.pagesRefMap[destRef.num + ' ' + destRef.gen + ' R'] :
  4430. (destRef + 1);
  4431. if (pageNumber) {
  4432. if (pageNumber > self.pagesCount) {
  4433. pageNumber = self.pagesCount;
  4434. }
  4435. self.pdfViewer.scrollPageIntoView(pageNumber, dest);
  4436. // Update the browsing history.
  4437. PDFHistory.push({ dest: dest, hash: destString, page: pageNumber });
  4438. } else {
  4439. self.pdfDocument.getPageIndex(destRef).then(function (pageIndex) {
  4440. var pageNum = pageIndex + 1;
  4441. self.pagesRefMap[destRef.num + ' ' + destRef.gen + ' R'] = pageNum;
  4442. goToDestination(destRef);
  4443. });
  4444. }
  4445. };
  4446. var destinationPromise;
  4447. if (typeof dest === 'string') {
  4448. destString = dest;
  4449. destinationPromise = this.pdfDocument.getDestination(dest);
  4450. } else {
  4451. destinationPromise = Promise.resolve(dest);
  4452. }
  4453. destinationPromise.then(function(destination) {
  4454. dest = destination;
  4455. if (!(destination instanceof Array)) {
  4456. return; // invalid destination
  4457. }
  4458. goToDestination(destination[0]);
  4459. });
  4460. },
  4461. executeNamedAction: function pdfViewExecuteNamedAction(action) {
  4462. // See PDF reference, table 8.45 - Named action
  4463. switch (action) {
  4464. case 'GoToPage':
  4465. document.getElementById('pageNumber').focus();
  4466. break;
  4467. case 'GoBack':
  4468. PDFHistory.back();
  4469. break;
  4470. case 'GoForward':
  4471. PDFHistory.forward();
  4472. break;
  4473. case 'Find':
  4474. if (!this.supportsIntegratedFind) {
  4475. this.findBar.toggle();
  4476. }
  4477. break;
  4478. case 'NextPage':
  4479. this.page++;
  4480. break;
  4481. case 'PrevPage':
  4482. this.page--;
  4483. break;
  4484. case 'LastPage':
  4485. this.page = this.pagesCount;
  4486. break;
  4487. case 'FirstPage':
  4488. this.page = 1;
  4489. break;
  4490. default:
  4491. break; // No action according to spec
  4492. }
  4493. },
  4494. getDestinationHash: function pdfViewGetDestinationHash(dest) {
  4495. if (typeof dest === 'string') {
  4496. return this.getAnchorUrl('#' + escape(dest));
  4497. }
  4498. if (dest instanceof Array) {
  4499. var destRef = dest[0]; // see navigateTo method for dest format
  4500. var pageNumber = destRef instanceof Object ?
  4501. this.pagesRefMap[destRef.num + ' ' + destRef.gen + ' R'] :
  4502. (destRef + 1);
  4503. if (pageNumber) {
  4504. var pdfOpenParams = this.getAnchorUrl('#page=' + pageNumber);
  4505. var destKind = dest[1];
  4506. if (typeof destKind === 'object' && 'name' in destKind &&
  4507. destKind.name === 'XYZ') {
  4508. var scale = (dest[4] || this.currentScaleValue);
  4509. var scaleNumber = parseFloat(scale);
  4510. if (scaleNumber) {
  4511. scale = scaleNumber * 100;
  4512. }
  4513. pdfOpenParams += '&zoom=' + scale;
  4514. if (dest[2] || dest[3]) {
  4515. pdfOpenParams += ',' + (dest[2] || 0) + ',' + (dest[3] || 0);
  4516. }
  4517. }
  4518. return pdfOpenParams;
  4519. }
  4520. }
  4521. return '';
  4522. },
  4523. /**
  4524. * Prefix the full url on anchor links to make sure that links are resolved
  4525. * relative to the current URL instead of the one defined in <base href>.
  4526. * @param {String} anchor The anchor hash, including the #.
  4527. */
  4528. getAnchorUrl: function getAnchorUrl(anchor) {
  4529. return anchor;
  4530. },
  4531. /**
  4532. * Show the error box.
  4533. * @param {String} message A message that is human readable.
  4534. * @param {Object} moreInfo (optional) Further information about the error
  4535. * that is more technical. Should have a 'message'
  4536. * and optionally a 'stack' property.
  4537. */
  4538. error: function pdfViewError(message, moreInfo) {
  4539. var moreInfoText = mozL10n.get('error_version_info',
  4540. {version: PDFJS.version || '?', build: PDFJS.build || '?'},
  4541. 'PDF.js v{{version}} (build: {{build}})') + '\n';
  4542. if (moreInfo) {
  4543. moreInfoText +=
  4544. mozL10n.get('error_message', {message: moreInfo.message},
  4545. 'Message: {{message}}');
  4546. if (moreInfo.stack) {
  4547. moreInfoText += '\n' +
  4548. mozL10n.get('error_stack', {stack: moreInfo.stack},
  4549. 'Stack: {{stack}}');
  4550. } else {
  4551. if (moreInfo.filename) {
  4552. moreInfoText += '\n' +
  4553. mozL10n.get('error_file', {file: moreInfo.filename},
  4554. 'File: {{file}}');
  4555. }
  4556. if (moreInfo.lineNumber) {
  4557. moreInfoText += '\n' +
  4558. mozL10n.get('error_line', {line: moreInfo.lineNumber},
  4559. 'Line: {{line}}');
  4560. }
  4561. }
  4562. }
  4563. var errorWrapper = document.getElementById('errorWrapper');
  4564. errorWrapper.removeAttribute('hidden');
  4565. var errorMessage = document.getElementById('errorMessage');
  4566. errorMessage.textContent = message;
  4567. var closeButton = document.getElementById('errorClose');
  4568. closeButton.onclick = function() {
  4569. errorWrapper.setAttribute('hidden', 'true');
  4570. };
  4571. var errorMoreInfo = document.getElementById('errorMoreInfo');
  4572. var moreInfoButton = document.getElementById('errorShowMore');
  4573. var lessInfoButton = document.getElementById('errorShowLess');
  4574. moreInfoButton.onclick = function() {
  4575. errorMoreInfo.removeAttribute('hidden');
  4576. moreInfoButton.setAttribute('hidden', 'true');
  4577. lessInfoButton.removeAttribute('hidden');
  4578. errorMoreInfo.style.height = errorMoreInfo.scrollHeight + 'px';
  4579. };
  4580. lessInfoButton.onclick = function() {
  4581. errorMoreInfo.setAttribute('hidden', 'true');
  4582. moreInfoButton.removeAttribute('hidden');
  4583. lessInfoButton.setAttribute('hidden', 'true');
  4584. };
  4585. moreInfoButton.oncontextmenu = noContextMenuHandler;
  4586. lessInfoButton.oncontextmenu = noContextMenuHandler;
  4587. closeButton.oncontextmenu = noContextMenuHandler;
  4588. moreInfoButton.removeAttribute('hidden');
  4589. lessInfoButton.setAttribute('hidden', 'true');
  4590. errorMoreInfo.value = moreInfoText;
  4591. },
  4592. progress: function pdfViewProgress(level) {
  4593. var percent = Math.round(level * 100);
  4594. // When we transition from full request to range requests, it's possible
  4595. // that we discard some of the loaded data. This can cause the loading
  4596. // bar to move backwards. So prevent this by only updating the bar if it
  4597. // increases.
  4598. if (percent > this.loadingBar.percent || isNaN(percent)) {
  4599. this.loadingBar.percent = percent;
  4600. // When disableAutoFetch is enabled, it's not uncommon for the entire file
  4601. // to never be fetched (depends on e.g. the file structure). In this case
  4602. // the loading bar will not be completely filled, nor will it be hidden.
  4603. // To prevent displaying a partially filled loading bar permanently, we
  4604. // hide it when no data has been loaded during a certain amount of time.
  4605. if (PDFJS.disableAutoFetch && percent) {
  4606. if (this.disableAutoFetchLoadingBarTimeout) {
  4607. clearTimeout(this.disableAutoFetchLoadingBarTimeout);
  4608. this.disableAutoFetchLoadingBarTimeout = null;
  4609. }
  4610. this.loadingBar.show();
  4611. this.disableAutoFetchLoadingBarTimeout = setTimeout(function () {
  4612. this.loadingBar.hide();
  4613. this.disableAutoFetchLoadingBarTimeout = null;
  4614. }.bind(this), DISABLE_AUTO_FETCH_LOADING_BAR_TIMEOUT);
  4615. }
  4616. }
  4617. },
  4618. load: function pdfViewLoad(pdfDocument, scale) {
  4619. var self = this;
  4620. scale = scale || UNKNOWN_SCALE;
  4621. this.findController.reset();
  4622. this.pdfDocument = pdfDocument;
  4623. DocumentProperties.url = this.url;
  4624. DocumentProperties.pdfDocument = pdfDocument;
  4625. DocumentProperties.resolveDataAvailable();
  4626. var downloadedPromise = pdfDocument.getDownloadInfo().then(function() {
  4627. self.downloadComplete = true;
  4628. self.loadingBar.hide();
  4629. });
  4630. var pagesCount = pdfDocument.numPages;
  4631. document.getElementById('numPages').textContent =
  4632. mozL10n.get('page_of', {pageCount: pagesCount}, 'of {{pageCount}}');
  4633. document.getElementById('pageNumber').max = pagesCount;
  4634. var id = this.documentFingerprint = pdfDocument.fingerprint;
  4635. var store = this.store = new ViewHistory(id);
  4636. var pdfViewer = this.pdfViewer;
  4637. pdfViewer.currentScale = scale;
  4638. pdfViewer.setDocument(pdfDocument);
  4639. var firstPagePromise = pdfViewer.firstPagePromise;
  4640. var pagesPromise = pdfViewer.pagesPromise;
  4641. var onePageRendered = pdfViewer.onePageRendered;
  4642. this.pageRotation = 0;
  4643. this.isInitialViewSet = false;
  4644. this.pagesRefMap = pdfViewer.pagesRefMap;
  4645. this.pdfThumbnailViewer.setDocument(pdfDocument);
  4646. firstPagePromise.then(function(pdfPage) {
  4647. downloadedPromise.then(function () {
  4648. var event = document.createEvent('CustomEvent');
  4649. event.initCustomEvent('documentload', true, true, {});
  4650. window.dispatchEvent(event);
  4651. });
  4652. self.loadingBar.setWidth(document.getElementById('viewer'));
  4653. self.findController.resolveFirstPage();
  4654. if (!PDFJS.disableHistory && !self.isViewerEmbedded) {
  4655. // The browsing history is only enabled when the viewer is standalone,
  4656. // i.e. not when it is embedded in a web page.
  4657. PDFHistory.initialize(self.documentFingerprint, self);
  4658. }
  4659. });
  4660. // Fetch the necessary preference values.
  4661. var showPreviousViewOnLoad;
  4662. var showPreviousViewOnLoadPromise =
  4663. Preferences.get('showPreviousViewOnLoad').then(function (prefValue) {
  4664. showPreviousViewOnLoad = prefValue;
  4665. });
  4666. var defaultZoomValue;
  4667. var defaultZoomValuePromise =
  4668. Preferences.get('defaultZoomValue').then(function (prefValue) {
  4669. defaultZoomValue = prefValue;
  4670. });
  4671. var storePromise = store.initializedPromise;
  4672. Promise.all([firstPagePromise, storePromise, showPreviousViewOnLoadPromise,
  4673. defaultZoomValuePromise]).then(function resolved() {
  4674. var storedHash = null;
  4675. if (showPreviousViewOnLoad && store.get('exists', false)) {
  4676. var pageNum = store.get('page', '1');
  4677. var zoom = defaultZoomValue ||
  4678. store.get('zoom', self.pdfViewer.currentScale);
  4679. var left = store.get('scrollLeft', '0');
  4680. var top = store.get('scrollTop', '0');
  4681. storedHash = 'page=' + pageNum + '&zoom=' + zoom + ',' +
  4682. left + ',' + top;
  4683. } else if (defaultZoomValue) {
  4684. storedHash = 'page=1&zoom=' + defaultZoomValue;
  4685. }
  4686. self.setInitialView(storedHash, scale);
  4687. // Make all navigation keys work on document load,
  4688. // unless the viewer is embedded in a web page.
  4689. if (!self.isViewerEmbedded) {
  4690. self.pdfViewer.focus();
  4691. }
  4692. }, function rejected(reason) {
  4693. console.error(reason);
  4694. firstPagePromise.then(function () {
  4695. self.setInitialView(null, scale);
  4696. });
  4697. });
  4698. pagesPromise.then(function() {
  4699. if (self.supportsPrinting) {
  4700. pdfDocument.getJavaScript().then(function(javaScript) {
  4701. if (javaScript.length) {
  4702. console.warn('Warning: JavaScript is not supported');
  4703. self.fallback(PDFJS.UNSUPPORTED_FEATURES.javaScript);
  4704. }
  4705. // Hack to support auto printing.
  4706. var regex = /\bprint\s*\(/g;
  4707. for (var i = 0, ii = javaScript.length; i < ii; i++) {
  4708. var js = javaScript[i];
  4709. if (js && regex.test(js)) {
  4710. setTimeout(function() {
  4711. window.print();
  4712. });
  4713. return;
  4714. }
  4715. }
  4716. });
  4717. }
  4718. });
  4719. // outline depends on pagesRefMap
  4720. var promises = [pagesPromise, this.animationStartedPromise];
  4721. Promise.all(promises).then(function() {
  4722. pdfDocument.getOutline().then(function(outline) {
  4723. var outlineView = document.getElementById('outlineView');
  4724. self.outline = new DocumentOutlineView({
  4725. outline: outline,
  4726. outlineView: outlineView,
  4727. linkService: self
  4728. });
  4729. document.getElementById('viewOutline').disabled = !outline;
  4730. if (!outline && !outlineView.classList.contains('hidden')) {
  4731. self.switchSidebarView('thumbs');
  4732. }
  4733. if (outline &&
  4734. self.preferenceSidebarViewOnLoad === SidebarView.OUTLINE) {
  4735. self.switchSidebarView('outline', true);
  4736. }
  4737. });
  4738. pdfDocument.getAttachments().then(function(attachments) {
  4739. var attachmentsView = document.getElementById('attachmentsView');
  4740. self.attachments = new DocumentAttachmentsView({
  4741. attachments: attachments,
  4742. attachmentsView: attachmentsView
  4743. });
  4744. document.getElementById('viewAttachments').disabled = !attachments;
  4745. if (!attachments && !attachmentsView.classList.contains('hidden')) {
  4746. self.switchSidebarView('thumbs');
  4747. }
  4748. if (attachments &&
  4749. self.preferenceSidebarViewOnLoad === SidebarView.ATTACHMENTS) {
  4750. self.switchSidebarView('attachments', true);
  4751. }
  4752. });
  4753. });
  4754. if (self.preferenceSidebarViewOnLoad === SidebarView.THUMBS) {
  4755. Promise.all([firstPagePromise, onePageRendered]).then(function () {
  4756. self.switchSidebarView('thumbs', true);
  4757. });
  4758. }
  4759. pdfDocument.getMetadata().then(function(data) {
  4760. var info = data.info, metadata = data.metadata;
  4761. self.documentInfo = info;
  4762. self.metadata = metadata;
  4763. // Provides some basic debug information
  4764. console.log('PDF ' + pdfDocument.fingerprint + ' [' +
  4765. info.PDFFormatVersion + ' ' + (info.Producer || '-').trim() +
  4766. ' / ' + (info.Creator || '-').trim() + ']' +
  4767. ' (PDF.js: ' + (PDFJS.version || '-') +
  4768. (!PDFJS.disableWebGL ? ' [WebGL]' : '') + ')');
  4769. var pdfTitle;
  4770. if (metadata && metadata.has('dc:title')) {
  4771. var title = metadata.get('dc:title');
  4772. // Ghostscript sometimes return 'Untitled', sets the title to 'Untitled'
  4773. if (title !== 'Untitled') {
  4774. pdfTitle = title;
  4775. }
  4776. }
  4777. if (!pdfTitle && info && info['Title']) {
  4778. pdfTitle = info['Title'];
  4779. }
  4780. if (pdfTitle) {
  4781. self.setTitle(pdfTitle + ' - ' + document.title);
  4782. }
  4783. if (info.IsAcroFormPresent) {
  4784. console.warn('Warning: AcroForm/XFA is not supported');
  4785. self.fallback(PDFJS.UNSUPPORTED_FEATURES.forms);
  4786. }
  4787. });
  4788. },
  4789. setInitialView: function pdfViewSetInitialView(storedHash, scale) {
  4790. this.isInitialViewSet = true;
  4791. // When opening a new file (when one is already loaded in the viewer):
  4792. // Reset 'currentPageNumber', since otherwise the page's scale will be wrong
  4793. // if 'currentPageNumber' is larger than the number of pages in the file.
  4794. document.getElementById('pageNumber').value =
  4795. this.pdfViewer.currentPageNumber = 1;
  4796. if (PDFHistory.initialDestination) {
  4797. this.navigateTo(PDFHistory.initialDestination);
  4798. PDFHistory.initialDestination = null;
  4799. } else if (this.initialBookmark) {
  4800. this.setHash(this.initialBookmark);
  4801. PDFHistory.push({ hash: this.initialBookmark }, !!this.initialBookmark);
  4802. this.initialBookmark = null;
  4803. } else if (storedHash) {
  4804. this.setHash(storedHash);
  4805. } else if (scale) {
  4806. this.setScale(scale, true);
  4807. this.page = 1;
  4808. }
  4809. if (this.pdfViewer.currentScale === UNKNOWN_SCALE) {
  4810. // Scale was not initialized: invalid bookmark or scale was not specified.
  4811. // Setting the default one.
  4812. this.setScale(DEFAULT_SCALE, true);
  4813. }
  4814. },
  4815. cleanup: function pdfViewCleanup() {
  4816. this.pdfViewer.cleanup();
  4817. this.pdfThumbnailViewer.cleanup();
  4818. this.pdfDocument.cleanup();
  4819. },
  4820. forceRendering: function pdfViewForceRendering() {
  4821. this.pdfRenderingQueue.printing = this.printing;
  4822. this.pdfRenderingQueue.isThumbnailViewEnabled = this.sidebarOpen;
  4823. this.pdfRenderingQueue.renderHighestPriority();
  4824. },
  4825. setHash: function pdfViewSetHash(hash) {
  4826. if (!this.isInitialViewSet) {
  4827. this.initialBookmark = hash;
  4828. return;
  4829. }
  4830. var validFitZoomValues = ['Fit','FitB','FitH','FitBH',
  4831. 'FitV','FitBV','FitR'];
  4832. if (!hash) {
  4833. return;
  4834. }
  4835. if (hash.indexOf('=') >= 0) {
  4836. var params = this.parseQueryString(hash);
  4837. // borrowing syntax from "Parameters for Opening PDF Files"
  4838. if ('nameddest' in params) {
  4839. PDFHistory.updateNextHashParam(params.nameddest);
  4840. this.navigateTo(params.nameddest);
  4841. return;
  4842. }
  4843. var pageNumber, dest;
  4844. if ('page' in params) {
  4845. pageNumber = (params.page | 0) || 1;
  4846. }
  4847. if ('zoom' in params) {
  4848. var zoomArgs = params.zoom.split(','); // scale,left,top
  4849. // building destination array
  4850. // If the zoom value, it has to get divided by 100. If it is a string,
  4851. // it should stay as it is.
  4852. var zoomArg = zoomArgs[0];
  4853. var zoomArgNumber = parseFloat(zoomArg);
  4854. var destName = 'XYZ';
  4855. if (zoomArgNumber) {
  4856. zoomArg = zoomArgNumber / 100;
  4857. } else if (validFitZoomValues.indexOf(zoomArg) >= 0) {
  4858. destName = zoomArg;
  4859. }
  4860. dest = [null, { name: destName },
  4861. zoomArgs.length > 1 ? (zoomArgs[1] | 0) : null,
  4862. zoomArgs.length > 2 ? (zoomArgs[2] | 0) : null,
  4863. zoomArg];
  4864. }
  4865. if (dest) {
  4866. this.pdfViewer.scrollPageIntoView(pageNumber || this.page, dest);
  4867. } else if (pageNumber) {
  4868. this.page = pageNumber; // simple page
  4869. }
  4870. if ('pagemode' in params) {
  4871. if (params.pagemode === 'thumbs' || params.pagemode === 'bookmarks' ||
  4872. params.pagemode === 'attachments') {
  4873. this.switchSidebarView((params.pagemode === 'bookmarks' ?
  4874. 'outline' : params.pagemode), true);
  4875. } else if (params.pagemode === 'none' && this.sidebarOpen) {
  4876. document.getElementById('sidebarToggle').click();
  4877. }
  4878. }
  4879. } else if (/^\d+$/.test(hash)) { // page number
  4880. this.page = hash;
  4881. } else { // named destination
  4882. PDFHistory.updateNextHashParam(unescape(hash));
  4883. this.navigateTo(unescape(hash));
  4884. }
  4885. },
  4886. switchSidebarView: function pdfViewSwitchSidebarView(view, openSidebar) {
  4887. if (openSidebar && !this.sidebarOpen) {
  4888. document.getElementById('sidebarToggle').click();
  4889. }
  4890. var thumbsView = document.getElementById('thumbnailView');
  4891. var outlineView = document.getElementById('outlineView');
  4892. var attachmentsView = document.getElementById('attachmentsView');
  4893. var thumbsButton = document.getElementById('viewThumbnail');
  4894. var outlineButton = document.getElementById('viewOutline');
  4895. var attachmentsButton = document.getElementById('viewAttachments');
  4896. switch (view) {
  4897. case 'thumbs':
  4898. var wasAnotherViewVisible = thumbsView.classList.contains('hidden');
  4899. thumbsButton.classList.add('toggled');
  4900. outlineButton.classList.remove('toggled');
  4901. attachmentsButton.classList.remove('toggled');
  4902. thumbsView.classList.remove('hidden');
  4903. outlineView.classList.add('hidden');
  4904. attachmentsView.classList.add('hidden');
  4905. this.forceRendering();
  4906. if (wasAnotherViewVisible) {
  4907. this.pdfThumbnailViewer.ensureThumbnailVisible(this.page);
  4908. }
  4909. break;
  4910. case 'outline':
  4911. thumbsButton.classList.remove('toggled');
  4912. outlineButton.classList.add('toggled');
  4913. attachmentsButton.classList.remove('toggled');
  4914. thumbsView.classList.add('hidden');
  4915. outlineView.classList.remove('hidden');
  4916. attachmentsView.classList.add('hidden');
  4917. if (outlineButton.getAttribute('disabled')) {
  4918. return;
  4919. }
  4920. break;
  4921. case 'attachments':
  4922. thumbsButton.classList.remove('toggled');
  4923. outlineButton.classList.remove('toggled');
  4924. attachmentsButton.classList.add('toggled');
  4925. thumbsView.classList.add('hidden');
  4926. outlineView.classList.add('hidden');
  4927. attachmentsView.classList.remove('hidden');
  4928. if (attachmentsButton.getAttribute('disabled')) {
  4929. return;
  4930. }
  4931. break;
  4932. }
  4933. },
  4934. // Helper function to parse query string (e.g. ?param1=value&parm2=...).
  4935. parseQueryString: function pdfViewParseQueryString(query) {
  4936. var parts = query.split('&');
  4937. var params = {};
  4938. for (var i = 0, ii = parts.length; i < ii; ++i) {
  4939. var param = parts[i].split('=');
  4940. var key = param[0].toLowerCase();
  4941. var value = param.length > 1 ? param[1] : null;
  4942. params[decodeURIComponent(key)] = decodeURIComponent(value);
  4943. }
  4944. return params;
  4945. },
  4946. beforePrint: function pdfViewSetupBeforePrint() {
  4947. if (!this.supportsPrinting) {
  4948. var printMessage = mozL10n.get('printing_not_supported', null,
  4949. 'Warning: Printing is not fully supported by this browser.');
  4950. this.error(printMessage);
  4951. return;
  4952. }
  4953. var alertNotReady = false;
  4954. var i, ii;
  4955. if (!this.pagesCount) {
  4956. alertNotReady = true;
  4957. } else {
  4958. for (i = 0, ii = this.pagesCount; i < ii; ++i) {
  4959. if (!this.pdfViewer.getPageView(i).pdfPage) {
  4960. alertNotReady = true;
  4961. break;
  4962. }
  4963. }
  4964. }
  4965. if (alertNotReady) {
  4966. var notReadyMessage = mozL10n.get('printing_not_ready', null,
  4967. 'Warning: The PDF is not fully loaded for printing.');
  4968. window.alert(notReadyMessage);
  4969. return;
  4970. }
  4971. this.printing = true;
  4972. this.forceRendering();
  4973. var body = document.querySelector('body');
  4974. body.setAttribute('data-mozPrintCallback', true);
  4975. for (i = 0, ii = this.pagesCount; i < ii; ++i) {
  4976. this.pdfViewer.getPageView(i).beforePrint();
  4977. }
  4978. },
  4979. afterPrint: function pdfViewSetupAfterPrint() {
  4980. var div = document.getElementById('printContainer');
  4981. while (div.hasChildNodes()) {
  4982. div.removeChild(div.lastChild);
  4983. }
  4984. this.printing = false;
  4985. this.forceRendering();
  4986. },
  4987. setScale: function (value, resetAutoSettings) {
  4988. this.updateScaleControls = !!resetAutoSettings;
  4989. this.pdfViewer.currentScaleValue = value;
  4990. this.updateScaleControls = true;
  4991. },
  4992. rotatePages: function pdfViewRotatePages(delta) {
  4993. var pageNumber = this.page;
  4994. this.pageRotation = (this.pageRotation + 360 + delta) % 360;
  4995. this.pdfViewer.pagesRotation = this.pageRotation;
  4996. this.pdfThumbnailViewer.pagesRotation = this.pageRotation;
  4997. this.forceRendering();
  4998. this.pdfViewer.scrollPageIntoView(pageNumber);
  4999. },
  5000. /**
  5001. * This function flips the page in presentation mode if the user scrolls up
  5002. * or down with large enough motion and prevents page flipping too often.
  5003. *
  5004. * @this {PDFView}
  5005. * @param {number} mouseScrollDelta The delta value from the mouse event.
  5006. */
  5007. mouseScroll: function pdfViewMouseScroll(mouseScrollDelta) {
  5008. var MOUSE_SCROLL_COOLDOWN_TIME = 50;
  5009. var currentTime = (new Date()).getTime();
  5010. var storedTime = this.mouseScrollTimeStamp;
  5011. // In case one page has already been flipped there is a cooldown time
  5012. // which has to expire before next page can be scrolled on to.
  5013. if (currentTime > storedTime &&
  5014. currentTime - storedTime < MOUSE_SCROLL_COOLDOWN_TIME) {
  5015. return;
  5016. }
  5017. // In case the user decides to scroll to the opposite direction than before
  5018. // clear the accumulated delta.
  5019. if ((this.mouseScrollDelta > 0 && mouseScrollDelta < 0) ||
  5020. (this.mouseScrollDelta < 0 && mouseScrollDelta > 0)) {
  5021. this.clearMouseScrollState();
  5022. }
  5023. this.mouseScrollDelta += mouseScrollDelta;
  5024. var PAGE_FLIP_THRESHOLD = 120;
  5025. if (Math.abs(this.mouseScrollDelta) >= PAGE_FLIP_THRESHOLD) {
  5026. var PageFlipDirection = {
  5027. UP: -1,
  5028. DOWN: 1
  5029. };
  5030. // In presentation mode scroll one page at a time.
  5031. var pageFlipDirection = (this.mouseScrollDelta > 0) ?
  5032. PageFlipDirection.UP :
  5033. PageFlipDirection.DOWN;
  5034. this.clearMouseScrollState();
  5035. var currentPage = this.page;
  5036. // In case we are already on the first or the last page there is no need
  5037. // to do anything.
  5038. if ((currentPage === 1 && pageFlipDirection === PageFlipDirection.UP) ||
  5039. (currentPage === this.pagesCount &&
  5040. pageFlipDirection === PageFlipDirection.DOWN)) {
  5041. return;
  5042. }
  5043. this.page += pageFlipDirection;
  5044. this.mouseScrollTimeStamp = currentTime;
  5045. }
  5046. },
  5047. /**
  5048. * This function clears the member attributes used with mouse scrolling in
  5049. * presentation mode.
  5050. *
  5051. * @this {PDFView}
  5052. */
  5053. clearMouseScrollState: function pdfViewClearMouseScrollState() {
  5054. this.mouseScrollTimeStamp = 0;
  5055. this.mouseScrollDelta = 0;
  5056. }
  5057. };
  5058. window.PDFView = PDFViewerApplication; // obsolete name, using it as an alias
  5059. var THUMBNAIL_SCROLL_MARGIN = -19;
  5060. /**
  5061. * @constructor
  5062. * @param container
  5063. * @param id
  5064. * @param defaultViewport
  5065. * @param linkService
  5066. * @param renderingQueue
  5067. * @param pageSource
  5068. *
  5069. * @implements {IRenderableView}
  5070. */
  5071. var ThumbnailView = function thumbnailView(container, id, defaultViewport,
  5072. linkService, renderingQueue,
  5073. pageSource) {
  5074. var anchor = document.createElement('a');
  5075. anchor.href = linkService.getAnchorUrl('#page=' + id);
  5076. anchor.title = mozL10n.get('thumb_page_title', {page: id}, 'Page {{page}}');
  5077. anchor.onclick = function stopNavigation() {
  5078. linkService.page = id;
  5079. return false;
  5080. };
  5081. this.pdfPage = undefined;
  5082. this.viewport = defaultViewport;
  5083. this.pdfPageRotate = defaultViewport.rotation;
  5084. this.rotation = 0;
  5085. this.pageWidth = this.viewport.width;
  5086. this.pageHeight = this.viewport.height;
  5087. this.pageRatio = this.pageWidth / this.pageHeight;
  5088. this.id = id;
  5089. this.renderingId = 'thumbnail' + id;
  5090. this.canvasWidth = 98;
  5091. this.canvasHeight = this.canvasWidth / this.pageWidth * this.pageHeight;
  5092. this.scale = (this.canvasWidth / this.pageWidth);
  5093. var div = this.el = document.createElement('div');
  5094. div.id = 'thumbnailContainer' + id;
  5095. div.className = 'thumbnail';
  5096. if (id === 1) {
  5097. // Highlight the thumbnail of the first page when no page number is
  5098. // specified (or exists in cache) when the document is loaded.
  5099. div.classList.add('selected');
  5100. }
  5101. var ring = document.createElement('div');
  5102. ring.className = 'thumbnailSelectionRing';
  5103. ring.style.width = this.canvasWidth + 'px';
  5104. ring.style.height = this.canvasHeight + 'px';
  5105. div.appendChild(ring);
  5106. anchor.appendChild(div);
  5107. container.appendChild(anchor);
  5108. this.hasImage = false;
  5109. this.renderingState = RenderingStates.INITIAL;
  5110. this.renderingQueue = renderingQueue;
  5111. this.pageSource = pageSource;
  5112. this.setPdfPage = function thumbnailViewSetPdfPage(pdfPage) {
  5113. this.pdfPage = pdfPage;
  5114. this.pdfPageRotate = pdfPage.rotate;
  5115. var totalRotation = (this.rotation + this.pdfPageRotate) % 360;
  5116. this.viewport = pdfPage.getViewport(1, totalRotation);
  5117. this.update();
  5118. };
  5119. this.update = function thumbnailViewUpdate(rotation) {
  5120. if (rotation !== undefined) {
  5121. this.rotation = rotation;
  5122. }
  5123. var totalRotation = (this.rotation + this.pdfPageRotate) % 360;
  5124. this.viewport = this.viewport.clone({
  5125. scale: 1,
  5126. rotation: totalRotation
  5127. });
  5128. this.pageWidth = this.viewport.width;
  5129. this.pageHeight = this.viewport.height;
  5130. this.pageRatio = this.pageWidth / this.pageHeight;
  5131. this.canvasHeight = this.canvasWidth / this.pageWidth * this.pageHeight;
  5132. this.scale = (this.canvasWidth / this.pageWidth);
  5133. div.removeAttribute('data-loaded');
  5134. ring.textContent = '';
  5135. ring.style.width = this.canvasWidth + 'px';
  5136. ring.style.height = this.canvasHeight + 'px';
  5137. this.hasImage = false;
  5138. this.renderingState = RenderingStates.INITIAL;
  5139. this.resume = null;
  5140. };
  5141. this.getPageDrawContext = function thumbnailViewGetPageDrawContext() {
  5142. var canvas = document.createElement('canvas');
  5143. canvas.id = 'thumbnail' + id;
  5144. canvas.width = this.canvasWidth;
  5145. canvas.height = this.canvasHeight;
  5146. canvas.className = 'thumbnailImage';
  5147. canvas.setAttribute('aria-label', mozL10n.get('thumb_page_canvas',
  5148. {page: id}, 'Thumbnail of Page {{page}}'));
  5149. div.setAttribute('data-loaded', true);
  5150. ring.appendChild(canvas);
  5151. var ctx = canvas.getContext('2d');
  5152. ctx.save();
  5153. ctx.fillStyle = 'rgb(255, 255, 255)';
  5154. ctx.fillRect(0, 0, this.canvasWidth, this.canvasHeight);
  5155. ctx.restore();
  5156. return ctx;
  5157. };
  5158. this.drawingRequired = function thumbnailViewDrawingRequired() {
  5159. return !this.hasImage;
  5160. };
  5161. this.draw = function thumbnailViewDraw(callback) {
  5162. if (!this.pdfPage) {
  5163. var promise = this.pageSource.getPage(this.id);
  5164. promise.then(function(pdfPage) {
  5165. this.setPdfPage(pdfPage);
  5166. this.draw(callback);
  5167. }.bind(this));
  5168. return;
  5169. }
  5170. if (this.renderingState !== RenderingStates.INITIAL) {
  5171. console.error('Must be in new state before drawing');
  5172. }
  5173. this.renderingState = RenderingStates.RUNNING;
  5174. if (this.hasImage) {
  5175. callback();
  5176. return;
  5177. }
  5178. var self = this;
  5179. var ctx = this.getPageDrawContext();
  5180. var drawViewport = this.viewport.clone({ scale: this.scale });
  5181. var renderContext = {
  5182. canvasContext: ctx,
  5183. viewport: drawViewport,
  5184. continueCallback: function(cont) {
  5185. if (!self.renderingQueue.isHighestPriority(self)) {
  5186. self.renderingState = RenderingStates.PAUSED;
  5187. self.resume = function() {
  5188. self.renderingState = RenderingStates.RUNNING;
  5189. cont();
  5190. };
  5191. return;
  5192. }
  5193. cont();
  5194. }
  5195. };
  5196. this.pdfPage.render(renderContext).promise.then(
  5197. function pdfPageRenderCallback() {
  5198. self.renderingState = RenderingStates.FINISHED;
  5199. callback();
  5200. },
  5201. function pdfPageRenderError(error) {
  5202. self.renderingState = RenderingStates.FINISHED;
  5203. callback();
  5204. }
  5205. );
  5206. this.hasImage = true;
  5207. };
  5208. function getTempCanvas(width, height) {
  5209. var tempCanvas = ThumbnailView.tempImageCache;
  5210. if (!tempCanvas) {
  5211. tempCanvas = document.createElement('canvas');
  5212. ThumbnailView.tempImageCache = tempCanvas;
  5213. }
  5214. tempCanvas.width = width;
  5215. tempCanvas.height = height;
  5216. return tempCanvas;
  5217. }
  5218. this.setImage = function thumbnailViewSetImage(img) {
  5219. if (!this.pdfPage) {
  5220. var promise = this.pageSource.getPage();
  5221. promise.then(function(pdfPage) {
  5222. this.setPdfPage(pdfPage);
  5223. this.setImage(img);
  5224. }.bind(this));
  5225. return;
  5226. }
  5227. if (this.hasImage || !img) {
  5228. return;
  5229. }
  5230. this.renderingState = RenderingStates.FINISHED;
  5231. var ctx = this.getPageDrawContext();
  5232. var reducedImage = img;
  5233. var reducedWidth = img.width;
  5234. var reducedHeight = img.height;
  5235. // drawImage does an awful job of rescaling the image, doing it gradually
  5236. var MAX_SCALE_FACTOR = 2.0;
  5237. if (Math.max(img.width / ctx.canvas.width,
  5238. img.height / ctx.canvas.height) > MAX_SCALE_FACTOR) {
  5239. reducedWidth >>= 1;
  5240. reducedHeight >>= 1;
  5241. reducedImage = getTempCanvas(reducedWidth, reducedHeight);
  5242. var reducedImageCtx = reducedImage.getContext('2d');
  5243. reducedImageCtx.drawImage(img, 0, 0, img.width, img.height,
  5244. 0, 0, reducedWidth, reducedHeight);
  5245. while (Math.max(reducedWidth / ctx.canvas.width,
  5246. reducedHeight / ctx.canvas.height) > MAX_SCALE_FACTOR) {
  5247. reducedImageCtx.drawImage(reducedImage,
  5248. 0, 0, reducedWidth, reducedHeight,
  5249. 0, 0, reducedWidth >> 1, reducedHeight >> 1);
  5250. reducedWidth >>= 1;
  5251. reducedHeight >>= 1;
  5252. }
  5253. }
  5254. ctx.drawImage(reducedImage, 0, 0, reducedWidth, reducedHeight,
  5255. 0, 0, ctx.canvas.width, ctx.canvas.height);
  5256. this.hasImage = true;
  5257. };
  5258. };
  5259. ThumbnailView.tempImageCache = null;
  5260. /**
  5261. * @typedef {Object} PDFThumbnailViewerOptions
  5262. * @property {HTMLDivElement} container - The container for the thumbs elements.
  5263. * @property {IPDFLinkService} linkService - The navigation/linking service.
  5264. * @property {PDFRenderingQueue} renderingQueue - The rendering queue object.
  5265. */
  5266. /**
  5267. * Simple viewer control to display thumbs for pages.
  5268. * @class
  5269. */
  5270. var PDFThumbnailViewer = (function pdfThumbnailViewer() {
  5271. /**
  5272. * @constructs
  5273. * @param {PDFThumbnailViewerOptions} options
  5274. */
  5275. function PDFThumbnailViewer(options) {
  5276. this.container = options.container;
  5277. this.renderingQueue = options.renderingQueue;
  5278. this.linkService = options.linkService;
  5279. this.scroll = watchScroll(this.container, this._scrollUpdated.bind(this));
  5280. this._resetView();
  5281. }
  5282. PDFThumbnailViewer.prototype = {
  5283. _scrollUpdated: function PDFThumbnailViewer_scrollUpdated() {
  5284. this.renderingQueue.renderHighestPriority();
  5285. },
  5286. getThumbnail: function PDFThumbnailViewer_getThumbnail(index) {
  5287. return this.thumbnails[index];
  5288. },
  5289. _getVisibleThumbs: function PDFThumbnailViewer_getVisibleThumbs() {
  5290. return getVisibleElements(this.container, this.thumbnails);
  5291. },
  5292. scrollThumbnailIntoView: function (page) {
  5293. var selected = document.querySelector('.thumbnail.selected');
  5294. if (selected) {
  5295. selected.classList.remove('selected');
  5296. }
  5297. var thumbnail = document.getElementById('thumbnailContainer' + page);
  5298. thumbnail.classList.add('selected');
  5299. var visibleThumbs = this._getVisibleThumbs();
  5300. var numVisibleThumbs = visibleThumbs.views.length;
  5301. // If the thumbnail isn't currently visible, scroll it into view.
  5302. if (numVisibleThumbs > 0) {
  5303. var first = visibleThumbs.first.id;
  5304. // Account for only one thumbnail being visible.
  5305. var last = (numVisibleThumbs > 1 ? visibleThumbs.last.id : first);
  5306. if (page <= first || page >= last) {
  5307. scrollIntoView(thumbnail, { top: THUMBNAIL_SCROLL_MARGIN });
  5308. }
  5309. }
  5310. },
  5311. get pagesRotation() {
  5312. return this._pagesRotation;
  5313. },
  5314. set pagesRotation(rotation) {
  5315. this._pagesRotation = rotation;
  5316. for (var i = 0, l = this.thumbnails.length; i < l; i++) {
  5317. var thumb = this.thumbnails[i];
  5318. thumb.update(rotation);
  5319. }
  5320. },
  5321. cleanup: function PDFThumbnailViewer_cleanup() {
  5322. ThumbnailView.tempImageCache = null;
  5323. },
  5324. _resetView: function () {
  5325. this.thumbnails = [];
  5326. this._pagesRotation = 0;
  5327. },
  5328. setDocument: function (pdfDocument) {
  5329. if (this.pdfDocument) {
  5330. // cleanup of the elements and views
  5331. var thumbsView = this.container;
  5332. while (thumbsView.hasChildNodes()) {
  5333. thumbsView.removeChild(thumbsView.lastChild);
  5334. }
  5335. this._resetView();
  5336. }
  5337. this.pdfDocument = pdfDocument;
  5338. if (!pdfDocument) {
  5339. return Promise.resolve();
  5340. }
  5341. return pdfDocument.getPage(1).then(function (firstPage) {
  5342. var pagesCount = pdfDocument.numPages;
  5343. var viewport = firstPage.getViewport(1.0);
  5344. for (var pageNum = 1; pageNum <= pagesCount; ++pageNum) {
  5345. var pageSource = new PDFPageSource(pdfDocument, pageNum);
  5346. var thumbnail = new ThumbnailView(this.container, pageNum,
  5347. viewport.clone(), this.linkService,
  5348. this.renderingQueue, pageSource);
  5349. this.thumbnails.push(thumbnail);
  5350. }
  5351. }.bind(this));
  5352. },
  5353. ensureThumbnailVisible:
  5354. function PDFThumbnailViewer_ensureThumbnailVisible(page) {
  5355. // Ensure that the thumbnail of the current page is visible
  5356. // when switching from another view.
  5357. scrollIntoView(document.getElementById('thumbnailContainer' + page));
  5358. },
  5359. forceRendering: function () {
  5360. var visibleThumbs = this._getVisibleThumbs();
  5361. var thumbView = this.renderingQueue.getHighestPriority(visibleThumbs,
  5362. this.thumbnails,
  5363. this.scroll.down);
  5364. if (thumbView) {
  5365. this.renderingQueue.renderView(thumbView);
  5366. return true;
  5367. }
  5368. return false;
  5369. }
  5370. };
  5371. return PDFThumbnailViewer;
  5372. })();
  5373. var DocumentOutlineView = function documentOutlineView(options) {
  5374. var outline = options.outline;
  5375. var outlineView = options.outlineView;
  5376. while (outlineView.firstChild) {
  5377. outlineView.removeChild(outlineView.firstChild);
  5378. }
  5379. if (!outline) {
  5380. return;
  5381. }
  5382. var linkService = options.linkService;
  5383. function bindItemLink(domObj, item) {
  5384. domObj.href = linkService.getDestinationHash(item.dest);
  5385. domObj.onclick = function documentOutlineViewOnclick(e) {
  5386. linkService.navigateTo(item.dest);
  5387. return false;
  5388. };
  5389. }
  5390. var queue = [{parent: outlineView, items: outline}];
  5391. while (queue.length > 0) {
  5392. var levelData = queue.shift();
  5393. var i, n = levelData.items.length;
  5394. for (i = 0; i < n; i++) {
  5395. var item = levelData.items[i];
  5396. var div = document.createElement('div');
  5397. div.className = 'outlineItem';
  5398. var a = document.createElement('a');
  5399. bindItemLink(a, item);
  5400. a.textContent = item.title;
  5401. div.appendChild(a);
  5402. if (item.items.length > 0) {
  5403. var itemsDiv = document.createElement('div');
  5404. itemsDiv.className = 'outlineItems';
  5405. div.appendChild(itemsDiv);
  5406. queue.push({parent: itemsDiv, items: item.items});
  5407. }
  5408. levelData.parent.appendChild(div);
  5409. }
  5410. }
  5411. };
  5412. var DocumentAttachmentsView = function documentAttachmentsView(options) {
  5413. var attachments = options.attachments;
  5414. var attachmentsView = options.attachmentsView;
  5415. while (attachmentsView.firstChild) {
  5416. attachmentsView.removeChild(attachmentsView.firstChild);
  5417. }
  5418. if (!attachments) {
  5419. return;
  5420. }
  5421. function bindItemLink(domObj, item) {
  5422. domObj.onclick = function documentAttachmentsViewOnclick(e) {
  5423. var downloadManager = new DownloadManager();
  5424. downloadManager.downloadData(item.content, getFileName(item.filename),
  5425. '');
  5426. return false;
  5427. };
  5428. }
  5429. var names = Object.keys(attachments).sort(function(a,b) {
  5430. return a.toLowerCase().localeCompare(b.toLowerCase());
  5431. });
  5432. for (var i = 0, ii = names.length; i < ii; i++) {
  5433. var item = attachments[names[i]];
  5434. var div = document.createElement('div');
  5435. div.className = 'attachmentsItem';
  5436. var button = document.createElement('button');
  5437. bindItemLink(button, item);
  5438. button.textContent = getFileName(item.filename);
  5439. div.appendChild(button);
  5440. attachmentsView.appendChild(div);
  5441. }
  5442. };
  5443. function webViewerLoad(evt) {
  5444. PDFViewerApplication.initialize().then(webViewerInitialized);
  5445. }
  5446. function webViewerInitialized() {
  5447. var queryString = document.location.search.substring(1);
  5448. var params = PDFViewerApplication.parseQueryString(queryString);
  5449. var file = 'file' in params ? params.file : DEFAULT_URL;
  5450. var fileInput = document.createElement('input');
  5451. fileInput.id = 'fileInput';
  5452. fileInput.className = 'fileInput';
  5453. fileInput.setAttribute('type', 'file');
  5454. fileInput.oncontextmenu = noContextMenuHandler;
  5455. document.body.appendChild(fileInput);
  5456. if (!window.File || !window.FileReader || !window.FileList || !window.Blob) {
  5457. document.getElementById('openFile').setAttribute('hidden', 'true');
  5458. document.getElementById('secondaryOpenFile').setAttribute('hidden', 'true');
  5459. } else {
  5460. document.getElementById('fileInput').value = null;
  5461. }
  5462. var locale = PDFJS.locale || navigator.language;
  5463. if (PDFViewerApplication.preferencePdfBugEnabled) {
  5464. // Special debugging flags in the hash section of the URL.
  5465. var hash = document.location.hash.substring(1);
  5466. var hashParams = PDFViewerApplication.parseQueryString(hash);
  5467. if ('disableworker' in hashParams) {
  5468. PDFJS.disableWorker = (hashParams['disableworker'] === 'true');
  5469. }
  5470. if ('disablerange' in hashParams) {
  5471. PDFJS.disableRange = (hashParams['disablerange'] === 'true');
  5472. }
  5473. if ('disablestream' in hashParams) {
  5474. PDFJS.disableStream = (hashParams['disablestream'] === 'true');
  5475. }
  5476. if ('disableautofetch' in hashParams) {
  5477. PDFJS.disableAutoFetch = (hashParams['disableautofetch'] === 'true');
  5478. }
  5479. if ('disablefontface' in hashParams) {
  5480. PDFJS.disableFontFace = (hashParams['disablefontface'] === 'true');
  5481. }
  5482. if ('disablehistory' in hashParams) {
  5483. PDFJS.disableHistory = (hashParams['disablehistory'] === 'true');
  5484. }
  5485. if ('webgl' in hashParams) {
  5486. PDFJS.disableWebGL = (hashParams['webgl'] !== 'true');
  5487. }
  5488. if ('useonlycsszoom' in hashParams) {
  5489. PDFJS.useOnlyCssZoom = (hashParams['useonlycsszoom'] === 'true');
  5490. }
  5491. if ('verbosity' in hashParams) {
  5492. PDFJS.verbosity = hashParams['verbosity'] | 0;
  5493. }
  5494. if ('ignorecurrentpositiononzoom' in hashParams) {
  5495. IGNORE_CURRENT_POSITION_ON_ZOOM =
  5496. (hashParams['ignorecurrentpositiononzoom'] === 'true');
  5497. }
  5498. if ('locale' in hashParams) {
  5499. locale = hashParams['locale'];
  5500. }
  5501. if ('textlayer' in hashParams) {
  5502. switch (hashParams['textlayer']) {
  5503. case 'off':
  5504. PDFJS.disableTextLayer = true;
  5505. break;
  5506. case 'visible':
  5507. case 'shadow':
  5508. case 'hover':
  5509. var viewer = document.getElementById('viewer');
  5510. viewer.classList.add('textLayer-' + hashParams['textlayer']);
  5511. break;
  5512. }
  5513. }
  5514. if ('pdfbug' in hashParams) {
  5515. PDFJS.pdfBug = true;
  5516. var pdfBug = hashParams['pdfbug'];
  5517. var enabled = pdfBug.split(',');
  5518. PDFBug.enable(enabled);
  5519. PDFBug.init();
  5520. }
  5521. }
  5522. mozL10n.setLanguage(locale);
  5523. if (!PDFViewerApplication.supportsPrinting) {
  5524. document.getElementById('print').classList.add('hidden');
  5525. document.getElementById('secondaryPrint').classList.add('hidden');
  5526. }
  5527. if (!PDFViewerApplication.supportsFullscreen) {
  5528. document.getElementById('presentationMode').classList.add('hidden');
  5529. document.getElementById('secondaryPresentationMode').
  5530. classList.add('hidden');
  5531. }
  5532. if (PDFViewerApplication.supportsIntegratedFind) {
  5533. document.getElementById('viewFind').classList.add('hidden');
  5534. }
  5535. // Listen for unsupported features to trigger the fallback UI.
  5536. PDFJS.UnsupportedManager.listen(
  5537. PDFViewerApplication.fallback.bind(PDFViewerApplication));
  5538. // Suppress context menus for some controls
  5539. document.getElementById('scaleSelect').oncontextmenu = noContextMenuHandler;
  5540. var mainContainer = document.getElementById('mainContainer');
  5541. var outerContainer = document.getElementById('outerContainer');
  5542. mainContainer.addEventListener('transitionend', function(e) {
  5543. if (e.target === mainContainer) {
  5544. var event = document.createEvent('UIEvents');
  5545. event.initUIEvent('resize', false, false, window, 0);
  5546. window.dispatchEvent(event);
  5547. outerContainer.classList.remove('sidebarMoving');
  5548. }
  5549. }, true);
  5550. document.getElementById('sidebarToggle').addEventListener('click',
  5551. function() {
  5552. this.classList.toggle('toggled');
  5553. outerContainer.classList.add('sidebarMoving');
  5554. outerContainer.classList.toggle('sidebarOpen');
  5555. PDFViewerApplication.sidebarOpen =
  5556. outerContainer.classList.contains('sidebarOpen');
  5557. PDFViewerApplication.forceRendering();
  5558. });
  5559. document.getElementById('viewThumbnail').addEventListener('click',
  5560. function() {
  5561. PDFViewerApplication.switchSidebarView('thumbs');
  5562. });
  5563. document.getElementById('viewOutline').addEventListener('click',
  5564. function() {
  5565. PDFViewerApplication.switchSidebarView('outline');
  5566. });
  5567. document.getElementById('viewAttachments').addEventListener('click',
  5568. function() {
  5569. PDFViewerApplication.switchSidebarView('attachments');
  5570. });
  5571. document.getElementById('previous').addEventListener('click',
  5572. function() {
  5573. PDFViewerApplication.page--;
  5574. });
  5575. document.getElementById('next').addEventListener('click',
  5576. function() {
  5577. PDFViewerApplication.page++;
  5578. });
  5579. document.getElementById('zoomIn').addEventListener('click',
  5580. function() {
  5581. PDFViewerApplication.zoomIn();
  5582. });
  5583. document.getElementById('zoomOut').addEventListener('click',
  5584. function() {
  5585. PDFViewerApplication.zoomOut();
  5586. });
  5587. document.getElementById('pageNumber').addEventListener('click', function() {
  5588. this.select();
  5589. });
  5590. document.getElementById('pageNumber').addEventListener('change', function() {
  5591. // Handle the user inputting a floating point number.
  5592. PDFViewerApplication.page = (this.value | 0);
  5593. if (this.value !== (this.value | 0).toString()) {
  5594. this.value = PDFViewerApplication.page;
  5595. }
  5596. });
  5597. document.getElementById('scaleSelect').addEventListener('change',
  5598. function() {
  5599. PDFViewerApplication.setScale(this.value, false);
  5600. });
  5601. document.getElementById('presentationMode').addEventListener('click',
  5602. SecondaryToolbar.presentationModeClick.bind(SecondaryToolbar));
  5603. document.getElementById('openFile').addEventListener('click',
  5604. SecondaryToolbar.openFileClick.bind(SecondaryToolbar));
  5605. document.getElementById('print').addEventListener('click',
  5606. SecondaryToolbar.printClick.bind(SecondaryToolbar));
  5607. document.getElementById('download').addEventListener('click',
  5608. SecondaryToolbar.downloadClick.bind(SecondaryToolbar));
  5609. if (file && file.lastIndexOf('file:', 0) === 0) {
  5610. // file:-scheme. Load the contents in the main thread because QtWebKit
  5611. // cannot load file:-URLs in a Web Worker. file:-URLs are usually loaded
  5612. // very quickly, so there is no need to set up progress event listeners.
  5613. PDFViewerApplication.setTitleUsingUrl(file);
  5614. var xhr = new XMLHttpRequest();
  5615. xhr.onload = function() {
  5616. PDFViewerApplication.open(new Uint8Array(xhr.response), 0);
  5617. };
  5618. try {
  5619. xhr.open('GET', file);
  5620. xhr.responseType = 'arraybuffer';
  5621. xhr.send();
  5622. } catch (e) {
  5623. PDFViewerApplication.error(mozL10n.get('loading_error', null,
  5624. 'An error occurred while loading the PDF.'), e);
  5625. }
  5626. return;
  5627. }
  5628. if (file) {
  5629. PDFViewerApplication.open(file, 0);
  5630. }
  5631. }
  5632. document.addEventListener('DOMContentLoaded', webViewerLoad, true);
  5633. document.addEventListener('pagerendered', function (e) {
  5634. var pageIndex = e.detail.pageNumber - 1;
  5635. var pageView = PDFViewerApplication.pdfViewer.getPageView(pageIndex);
  5636. var thumbnailView = PDFViewerApplication.pdfThumbnailViewer.
  5637. getThumbnail(pageIndex);
  5638. thumbnailView.setImage(pageView.canvas);
  5639. if (pageView.error) {
  5640. PDFViewerApplication.error(mozL10n.get('rendering_error', null,
  5641. 'An error occurred while rendering the page.'), pageView.error);
  5642. }
  5643. // If the page is still visible when it has finished rendering,
  5644. // ensure that the page number input loading indicator is hidden.
  5645. if ((pageIndex + 1) === PDFViewerApplication.page) {
  5646. var pageNumberInput = document.getElementById('pageNumber');
  5647. pageNumberInput.classList.remove(PAGE_NUMBER_LOADING_INDICATOR);
  5648. }
  5649. }, true);
  5650. window.addEventListener('presentationmodechanged', function (e) {
  5651. var active = e.detail.active;
  5652. var switchInProgress = e.detail.switchInProgress;
  5653. PDFViewerApplication.pdfViewer.presentationModeState =
  5654. switchInProgress ? PresentationModeState.CHANGING :
  5655. active ? PresentationModeState.FULLSCREEN : PresentationModeState.NORMAL;
  5656. });
  5657. function updateViewarea() {
  5658. if (!PDFViewerApplication.initialized) {
  5659. return;
  5660. }
  5661. PDFViewerApplication.pdfViewer.update();
  5662. }
  5663. window.addEventListener('updateviewarea', function () {
  5664. if (!PDFViewerApplication.initialized) {
  5665. return;
  5666. }
  5667. var location = PDFViewerApplication.pdfViewer.location;
  5668. PDFViewerApplication.store.initializedPromise.then(function() {
  5669. PDFViewerApplication.store.setMultiple({
  5670. 'exists': true,
  5671. 'page': location.pageNumber,
  5672. 'zoom': location.scale,
  5673. 'scrollLeft': location.left,
  5674. 'scrollTop': location.top
  5675. }).catch(function() {
  5676. // unable to write to storage
  5677. });
  5678. });
  5679. var href = PDFViewerApplication.getAnchorUrl(location.pdfOpenParams);
  5680. document.getElementById('viewBookmark').href = href;
  5681. document.getElementById('secondaryViewBookmark').href = href;
  5682. // Update the current bookmark in the browsing history.
  5683. PDFHistory.updateCurrentBookmark(location.pdfOpenParams, location.pageNumber);
  5684. // Show/hide the loading indicator in the page number input element.
  5685. var pageNumberInput = document.getElementById('pageNumber');
  5686. var currentPage =
  5687. PDFViewerApplication.pdfViewer.getPageView(PDFViewerApplication.page - 1);
  5688. if (currentPage.renderingState === RenderingStates.FINISHED) {
  5689. pageNumberInput.classList.remove(PAGE_NUMBER_LOADING_INDICATOR);
  5690. } else {
  5691. pageNumberInput.classList.add(PAGE_NUMBER_LOADING_INDICATOR);
  5692. }
  5693. }, true);
  5694. window.addEventListener('resize', function webViewerResize(evt) {
  5695. if (PDFViewerApplication.initialized &&
  5696. (document.getElementById('pageWidthOption').selected ||
  5697. document.getElementById('pageFitOption').selected ||
  5698. document.getElementById('pageAutoOption').selected)) {
  5699. var selectedScale = document.getElementById('scaleSelect').value;
  5700. PDFViewerApplication.setScale(selectedScale, false);
  5701. }
  5702. updateViewarea();
  5703. // Set the 'max-height' CSS property of the secondary toolbar.
  5704. SecondaryToolbar.setMaxHeight(document.getElementById('viewerContainer'));
  5705. });
  5706. window.addEventListener('hashchange', function webViewerHashchange(evt) {
  5707. if (PDFHistory.isHashChangeUnlocked) {
  5708. PDFViewerApplication.setHash(document.location.hash.substring(1));
  5709. }
  5710. });
  5711. window.addEventListener('change', function webViewerChange(evt) {
  5712. var files = evt.target.files;
  5713. if (!files || files.length === 0) {
  5714. return;
  5715. }
  5716. var file = files[0];
  5717. if (!PDFJS.disableCreateObjectURL &&
  5718. typeof URL !== 'undefined' && URL.createObjectURL) {
  5719. PDFViewerApplication.open(URL.createObjectURL(file), 0);
  5720. } else {
  5721. // Read the local file into a Uint8Array.
  5722. var fileReader = new FileReader();
  5723. fileReader.onload = function webViewerChangeFileReaderOnload(evt) {
  5724. var buffer = evt.target.result;
  5725. var uint8Array = new Uint8Array(buffer);
  5726. PDFViewerApplication.open(uint8Array, 0);
  5727. };
  5728. fileReader.readAsArrayBuffer(file);
  5729. }
  5730. PDFViewerApplication.setTitleUsingUrl(file.name);
  5731. // URL does not reflect proper document location - hiding some icons.
  5732. document.getElementById('viewBookmark').setAttribute('hidden', 'true');
  5733. document.getElementById('secondaryViewBookmark').
  5734. setAttribute('hidden', 'true');
  5735. document.getElementById('download').setAttribute('hidden', 'true');
  5736. document.getElementById('secondaryDownload').setAttribute('hidden', 'true');
  5737. }, true);
  5738. function selectScaleOption(value) {
  5739. var options = document.getElementById('scaleSelect').options;
  5740. var predefinedValueFound = false;
  5741. for (var i = 0; i < options.length; i++) {
  5742. var option = options[i];
  5743. if (option.value !== value) {
  5744. option.selected = false;
  5745. continue;
  5746. }
  5747. option.selected = true;
  5748. predefinedValueFound = true;
  5749. }
  5750. return predefinedValueFound;
  5751. }
  5752. window.addEventListener('localized', function localized(evt) {
  5753. document.getElementsByTagName('html')[0].dir = mozL10n.getDirection();
  5754. PDFViewerApplication.animationStartedPromise.then(function() {
  5755. // Adjust the width of the zoom box to fit the content.
  5756. // Note: If the window is narrow enough that the zoom box is not visible,
  5757. // we temporarily show it to be able to adjust its width.
  5758. var container = document.getElementById('scaleSelectContainer');
  5759. if (container.clientWidth === 0) {
  5760. container.setAttribute('style', 'display: inherit;');
  5761. }
  5762. if (container.clientWidth > 0) {
  5763. var select = document.getElementById('scaleSelect');
  5764. select.setAttribute('style', 'min-width: inherit;');
  5765. var width = select.clientWidth + SCALE_SELECT_CONTAINER_PADDING;
  5766. select.setAttribute('style', 'min-width: ' +
  5767. (width + SCALE_SELECT_PADDING) + 'px;');
  5768. container.setAttribute('style', 'min-width: ' + width + 'px; ' +
  5769. 'max-width: ' + width + 'px;');
  5770. }
  5771. // Set the 'max-height' CSS property of the secondary toolbar.
  5772. SecondaryToolbar.setMaxHeight(document.getElementById('viewerContainer'));
  5773. });
  5774. }, true);
  5775. window.addEventListener('scalechange', function scalechange(evt) {
  5776. document.getElementById('zoomOut').disabled = (evt.scale === MIN_SCALE);
  5777. document.getElementById('zoomIn').disabled = (evt.scale === MAX_SCALE);
  5778. var customScaleOption = document.getElementById('customScaleOption');
  5779. customScaleOption.selected = false;
  5780. if (!PDFViewerApplication.updateScaleControls &&
  5781. (document.getElementById('pageWidthOption').selected ||
  5782. document.getElementById('pageFitOption').selected ||
  5783. document.getElementById('pageAutoOption').selected)) {
  5784. updateViewarea();
  5785. return;
  5786. }
  5787. if (evt.presetValue) {
  5788. selectScaleOption(evt.presetValue);
  5789. updateViewarea();
  5790. return;
  5791. }
  5792. var predefinedValueFound = selectScaleOption('' + evt.scale);
  5793. if (!predefinedValueFound) {
  5794. var customScale = Math.round(evt.scale * 10000) / 100;
  5795. customScaleOption.textContent =
  5796. mozL10n.get('page_scale_percent', { scale: customScale }, '{{scale}}%');
  5797. customScaleOption.selected = true;
  5798. }
  5799. updateViewarea();
  5800. }, true);
  5801. window.addEventListener('pagechange', function pagechange(evt) {
  5802. var page = evt.pageNumber;
  5803. if (evt.previousPageNumber !== page) {
  5804. document.getElementById('pageNumber').value = page;
  5805. PDFViewerApplication.pdfThumbnailViewer.scrollThumbnailIntoView(page);
  5806. }
  5807. var numPages = PDFViewerApplication.pagesCount;
  5808. document.getElementById('previous').disabled = (page <= 1);
  5809. document.getElementById('next').disabled = (page >= numPages);
  5810. document.getElementById('firstPage').disabled = (page <= 1);
  5811. document.getElementById('lastPage').disabled = (page >= numPages);
  5812. // checking if the this.page was called from the updateViewarea function
  5813. if (evt.updateInProgress) {
  5814. return;
  5815. }
  5816. // Avoid scrolling the first page during loading
  5817. if (this.loading && page === 1) {
  5818. return;
  5819. }
  5820. PDFViewerApplication.pdfViewer.scrollPageIntoView(page);
  5821. }, true);
  5822. function handleMouseWheel(evt) {
  5823. var MOUSE_WHEEL_DELTA_FACTOR = 40;
  5824. var ticks = (evt.type === 'DOMMouseScroll') ? -evt.detail :
  5825. evt.wheelDelta / MOUSE_WHEEL_DELTA_FACTOR;
  5826. var direction = (ticks < 0) ? 'zoomOut' : 'zoomIn';
  5827. if (PresentationMode.active) {
  5828. evt.preventDefault();
  5829. PDFViewerApplication.mouseScroll(ticks * MOUSE_WHEEL_DELTA_FACTOR);
  5830. } else if (evt.ctrlKey) { // Only zoom the pages, not the entire viewer
  5831. evt.preventDefault();
  5832. PDFViewerApplication[direction](Math.abs(ticks));
  5833. }
  5834. }
  5835. window.addEventListener('DOMMouseScroll', handleMouseWheel);
  5836. window.addEventListener('mousewheel', handleMouseWheel);
  5837. window.addEventListener('click', function click(evt) {
  5838. if (!PresentationMode.active) {
  5839. if (SecondaryToolbar.opened &&
  5840. PDFViewerApplication.pdfViewer.containsElement(evt.target)) {
  5841. SecondaryToolbar.close();
  5842. }
  5843. } else if (evt.button === 0) {
  5844. // Necessary since preventDefault() in 'mousedown' won't stop
  5845. // the event propagation in all circumstances in presentation mode.
  5846. evt.preventDefault();
  5847. }
  5848. }, false);
  5849. window.addEventListener('keydown', function keydown(evt) {
  5850. if (OverlayManager.active) {
  5851. return;
  5852. }
  5853. var handled = false;
  5854. var cmd = (evt.ctrlKey ? 1 : 0) |
  5855. (evt.altKey ? 2 : 0) |
  5856. (evt.shiftKey ? 4 : 0) |
  5857. (evt.metaKey ? 8 : 0);
  5858. // First, handle the key bindings that are independent whether an input
  5859. // control is selected or not.
  5860. if (cmd === 1 || cmd === 8 || cmd === 5 || cmd === 12) {
  5861. // either CTRL or META key with optional SHIFT.
  5862. var pdfViewer = PDFViewerApplication.pdfViewer;
  5863. var inPresentationMode = pdfViewer &&
  5864. (pdfViewer.presentationModeState === PresentationModeState.CHANGING ||
  5865. pdfViewer.presentationModeState === PresentationModeState.FULLSCREEN);
  5866. switch (evt.keyCode) {
  5867. case 70: // f
  5868. if (!PDFViewerApplication.supportsIntegratedFind) {
  5869. PDFViewerApplication.findBar.open();
  5870. handled = true;
  5871. }
  5872. break;
  5873. case 71: // g
  5874. if (!PDFViewerApplication.supportsIntegratedFind) {
  5875. PDFViewerApplication.findBar.dispatchEvent('again',
  5876. cmd === 5 || cmd === 12);
  5877. handled = true;
  5878. }
  5879. break;
  5880. case 61: // FF/Mac '='
  5881. case 107: // FF '+' and '='
  5882. case 187: // Chrome '+'
  5883. case 171: // FF with German keyboard
  5884. if (!inPresentationMode) {
  5885. PDFViewerApplication.zoomIn();
  5886. }
  5887. handled = true;
  5888. break;
  5889. case 173: // FF/Mac '-'
  5890. case 109: // FF '-'
  5891. case 189: // Chrome '-'
  5892. if (!inPresentationMode) {
  5893. PDFViewerApplication.zoomOut();
  5894. }
  5895. handled = true;
  5896. break;
  5897. case 48: // '0'
  5898. case 96: // '0' on Numpad of Swedish keyboard
  5899. if (!inPresentationMode) {
  5900. // keeping it unhandled (to restore page zoom to 100%)
  5901. setTimeout(function () {
  5902. // ... and resetting the scale after browser adjusts its scale
  5903. PDFViewerApplication.setScale(DEFAULT_SCALE, true);
  5904. });
  5905. handled = false;
  5906. }
  5907. break;
  5908. }
  5909. }
  5910. // CTRL or META without shift
  5911. if (cmd === 1 || cmd === 8) {
  5912. switch (evt.keyCode) {
  5913. case 83: // s
  5914. PDFViewerApplication.download();
  5915. handled = true;
  5916. break;
  5917. }
  5918. }
  5919. // CTRL+ALT or Option+Command
  5920. if (cmd === 3 || cmd === 10) {
  5921. switch (evt.keyCode) {
  5922. case 80: // p
  5923. SecondaryToolbar.presentationModeClick();
  5924. handled = true;
  5925. break;
  5926. case 71: // g
  5927. // focuses input#pageNumber field
  5928. document.getElementById('pageNumber').select();
  5929. handled = true;
  5930. break;
  5931. }
  5932. }
  5933. if (handled) {
  5934. evt.preventDefault();
  5935. return;
  5936. }
  5937. // Some shortcuts should not get handled if a control/input element
  5938. // is selected.
  5939. var curElement = document.activeElement || document.querySelector(':focus');
  5940. var curElementTagName = curElement && curElement.tagName.toUpperCase();
  5941. if (curElementTagName === 'INPUT' ||
  5942. curElementTagName === 'TEXTAREA' ||
  5943. curElementTagName === 'SELECT') {
  5944. // Make sure that the secondary toolbar is closed when Escape is pressed.
  5945. if (evt.keyCode !== 27) { // 'Esc'
  5946. return;
  5947. }
  5948. }
  5949. if (cmd === 0) { // no control key pressed at all.
  5950. switch (evt.keyCode) {
  5951. case 38: // up arrow
  5952. case 33: // pg up
  5953. case 8: // backspace
  5954. if (!PresentationMode.active &&
  5955. PDFViewerApplication.currentScaleValue !== 'page-fit') {
  5956. break;
  5957. }
  5958. /* in presentation mode */
  5959. /* falls through */
  5960. case 37: // left arrow
  5961. // horizontal scrolling using arrow keys
  5962. if (PDFViewerApplication.pdfViewer.isHorizontalScrollbarEnabled) {
  5963. break;
  5964. }
  5965. /* falls through */
  5966. case 75: // 'k'
  5967. case 80: // 'p'
  5968. PDFViewerApplication.page--;
  5969. handled = true;
  5970. break;
  5971. case 27: // esc key
  5972. if (SecondaryToolbar.opened) {
  5973. SecondaryToolbar.close();
  5974. handled = true;
  5975. }
  5976. if (!PDFViewerApplication.supportsIntegratedFind &&
  5977. PDFViewerApplication.findBar.opened) {
  5978. PDFViewerApplication.findBar.close();
  5979. handled = true;
  5980. }
  5981. break;
  5982. case 40: // down arrow
  5983. case 34: // pg down
  5984. case 32: // spacebar
  5985. if (!PresentationMode.active &&
  5986. PDFViewerApplication.currentScaleValue !== 'page-fit') {
  5987. break;
  5988. }
  5989. /* falls through */
  5990. case 39: // right arrow
  5991. // horizontal scrolling using arrow keys
  5992. if (PDFViewerApplication.pdfViewer.isHorizontalScrollbarEnabled) {
  5993. break;
  5994. }
  5995. /* falls through */
  5996. case 74: // 'j'
  5997. case 78: // 'n'
  5998. PDFViewerApplication.page++;
  5999. handled = true;
  6000. break;
  6001. case 36: // home
  6002. if (PresentationMode.active || PDFViewerApplication.page > 1) {
  6003. PDFViewerApplication.page = 1;
  6004. handled = true;
  6005. }
  6006. break;
  6007. case 35: // end
  6008. if (PresentationMode.active || (PDFViewerApplication.pdfDocument &&
  6009. PDFViewerApplication.page < PDFViewerApplication.pagesCount)) {
  6010. PDFViewerApplication.page = PDFViewerApplication.pagesCount;
  6011. handled = true;
  6012. }
  6013. break;
  6014. case 72: // 'h'
  6015. if (!PresentationMode.active) {
  6016. HandTool.toggle();
  6017. }
  6018. break;
  6019. case 82: // 'r'
  6020. PDFViewerApplication.rotatePages(90);
  6021. break;
  6022. }
  6023. }
  6024. if (cmd === 4) { // shift-key
  6025. switch (evt.keyCode) {
  6026. case 32: // spacebar
  6027. if (!PresentationMode.active &&
  6028. PDFViewerApplication.currentScaleValue !== 'page-fit') {
  6029. break;
  6030. }
  6031. PDFViewerApplication.page--;
  6032. handled = true;
  6033. break;
  6034. case 82: // 'r'
  6035. PDFViewerApplication.rotatePages(-90);
  6036. break;
  6037. }
  6038. }
  6039. if (!handled && !PresentationMode.active) {
  6040. // 33=Page Up 34=Page Down 35=End 36=Home
  6041. // 37=Left 38=Up 39=Right 40=Down
  6042. if (evt.keyCode >= 33 && evt.keyCode <= 40 &&
  6043. !PDFViewerApplication.pdfViewer.containsElement(curElement)) {
  6044. // The page container is not focused, but a page navigation key has been
  6045. // pressed. Change the focus to the viewer container to make sure that
  6046. // navigation by keyboard works as expected.
  6047. PDFViewerApplication.pdfViewer.focus();
  6048. }
  6049. // 32=Spacebar
  6050. if (evt.keyCode === 32 && curElementTagName !== 'BUTTON') {
  6051. if (!PDFViewerApplication.pdfViewer.containsElement(curElement)) {
  6052. PDFViewerApplication.pdfViewer.focus();
  6053. }
  6054. }
  6055. }
  6056. if (cmd === 2) { // alt-key
  6057. switch (evt.keyCode) {
  6058. case 37: // left arrow
  6059. if (PresentationMode.active) {
  6060. PDFHistory.back();
  6061. handled = true;
  6062. }
  6063. break;
  6064. case 39: // right arrow
  6065. if (PresentationMode.active) {
  6066. PDFHistory.forward();
  6067. handled = true;
  6068. }
  6069. break;
  6070. }
  6071. }
  6072. if (handled) {
  6073. evt.preventDefault();
  6074. PDFViewerApplication.clearMouseScrollState();
  6075. }
  6076. });
  6077. window.addEventListener('beforeprint', function beforePrint(evt) {
  6078. PDFViewerApplication.beforePrint();
  6079. });
  6080. window.addEventListener('afterprint', function afterPrint(evt) {
  6081. PDFViewerApplication.afterPrint();
  6082. });
  6083. (function animationStartedClosure() {
  6084. // The offsetParent is not set until the pdf.js iframe or object is visible.
  6085. // Waiting for first animation.
  6086. PDFViewerApplication.animationStartedPromise = new Promise(
  6087. function (resolve) {
  6088. window.requestAnimationFrame(resolve);
  6089. });
  6090. })();