You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

7952 lines
254 KiB

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