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.

7516 lines
265 KiB

7 years ago
  1. /* Copyright 2016 Mozilla Foundation
  2. *
  3. * Licensed under the Apache License, Version 2.0 (the "License");
  4. * you may not use this file except in compliance with the License.
  5. * You may obtain a copy of the License at
  6. *
  7. * http://www.apache.org/licenses/LICENSE-2.0
  8. *
  9. * Unless required by applicable law or agreed to in writing, software
  10. * distributed under the License is distributed on an "AS IS" BASIS,
  11. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. * See the License for the specific language governing permissions and
  13. * limitations under the License.
  14. */
  15. 'use strict';
  16. ;
  17. var pdfjsWebLibs;
  18. {
  19. pdfjsWebLibs = { pdfjsWebPDFJS: window.pdfjsDistBuildPdf };
  20. (function () {
  21. (function (root, factory) {
  22. factory(root.pdfjsWebGrabToPan = {});
  23. }(this, function (exports) {
  24. function GrabToPan(options) {
  25. this.element = options.element;
  26. this.document = options.element.ownerDocument;
  27. if (typeof options.ignoreTarget === 'function') {
  28. this.ignoreTarget = options.ignoreTarget;
  29. }
  30. this.onActiveChanged = options.onActiveChanged;
  31. this.activate = this.activate.bind(this);
  32. this.deactivate = this.deactivate.bind(this);
  33. this.toggle = this.toggle.bind(this);
  34. this._onmousedown = this._onmousedown.bind(this);
  35. this._onmousemove = this._onmousemove.bind(this);
  36. this._endPan = this._endPan.bind(this);
  37. var overlay = this.overlay = document.createElement('div');
  38. overlay.className = 'grab-to-pan-grabbing';
  39. }
  40. GrabToPan.prototype = {
  41. CSS_CLASS_GRAB: 'grab-to-pan-grab',
  42. activate: function GrabToPan_activate() {
  43. if (!this.active) {
  44. this.active = true;
  45. this.element.addEventListener('mousedown', this._onmousedown, true);
  46. this.element.classList.add(this.CSS_CLASS_GRAB);
  47. if (this.onActiveChanged) {
  48. this.onActiveChanged(true);
  49. }
  50. }
  51. },
  52. deactivate: function GrabToPan_deactivate() {
  53. if (this.active) {
  54. this.active = false;
  55. this.element.removeEventListener('mousedown', this._onmousedown, true);
  56. this._endPan();
  57. this.element.classList.remove(this.CSS_CLASS_GRAB);
  58. if (this.onActiveChanged) {
  59. this.onActiveChanged(false);
  60. }
  61. }
  62. },
  63. toggle: function GrabToPan_toggle() {
  64. if (this.active) {
  65. this.deactivate();
  66. } else {
  67. this.activate();
  68. }
  69. },
  70. ignoreTarget: function GrabToPan_ignoreTarget(node) {
  71. return node[matchesSelector]('a[href], a[href] *, input, textarea, button, button *, select, option');
  72. },
  73. _onmousedown: function GrabToPan__onmousedown(event) {
  74. if (event.button !== 0 || this.ignoreTarget(event.target)) {
  75. return;
  76. }
  77. if (event.originalTarget) {
  78. try {
  79. event.originalTarget.tagName;
  80. } catch (e) {
  81. return;
  82. }
  83. }
  84. this.scrollLeftStart = this.element.scrollLeft;
  85. this.scrollTopStart = this.element.scrollTop;
  86. this.clientXStart = event.clientX;
  87. this.clientYStart = event.clientY;
  88. this.document.addEventListener('mousemove', this._onmousemove, true);
  89. this.document.addEventListener('mouseup', this._endPan, true);
  90. this.element.addEventListener('scroll', this._endPan, true);
  91. event.preventDefault();
  92. event.stopPropagation();
  93. var focusedElement = document.activeElement;
  94. if (focusedElement && !focusedElement.contains(event.target)) {
  95. focusedElement.blur();
  96. }
  97. },
  98. _onmousemove: function GrabToPan__onmousemove(event) {
  99. this.element.removeEventListener('scroll', this._endPan, true);
  100. if (isLeftMouseReleased(event)) {
  101. this._endPan();
  102. return;
  103. }
  104. var xDiff = event.clientX - this.clientXStart;
  105. var yDiff = event.clientY - this.clientYStart;
  106. var scrollTop = this.scrollTopStart - yDiff;
  107. var scrollLeft = this.scrollLeftStart - xDiff;
  108. if (this.element.scrollTo) {
  109. this.element.scrollTo({
  110. top: scrollTop,
  111. left: scrollLeft,
  112. behavior: 'instant'
  113. });
  114. } else {
  115. this.element.scrollTop = scrollTop;
  116. this.element.scrollLeft = scrollLeft;
  117. }
  118. if (!this.overlay.parentNode) {
  119. document.body.appendChild(this.overlay);
  120. }
  121. },
  122. _endPan: function GrabToPan__endPan() {
  123. this.element.removeEventListener('scroll', this._endPan, true);
  124. this.document.removeEventListener('mousemove', this._onmousemove, true);
  125. this.document.removeEventListener('mouseup', this._endPan, true);
  126. if (this.overlay.parentNode) {
  127. this.overlay.parentNode.removeChild(this.overlay);
  128. }
  129. }
  130. };
  131. var matchesSelector;
  132. [
  133. 'webkitM',
  134. 'mozM',
  135. 'msM',
  136. 'oM',
  137. 'm'
  138. ].some(function (prefix) {
  139. var name = prefix + 'atches';
  140. if (name in document.documentElement) {
  141. matchesSelector = name;
  142. }
  143. name += 'Selector';
  144. if (name in document.documentElement) {
  145. matchesSelector = name;
  146. }
  147. return matchesSelector;
  148. });
  149. var isNotIEorIsIE10plus = !document.documentMode || document.documentMode > 9;
  150. var chrome = window.chrome;
  151. var isChrome15OrOpera15plus = chrome && (chrome.webstore || chrome.app);
  152. var isSafari6plus = /Apple/.test(navigator.vendor) && /Version\/([6-9]\d*|[1-5]\d+)/.test(navigator.userAgent);
  153. function isLeftMouseReleased(event) {
  154. if ('buttons' in event && isNotIEorIsIE10plus) {
  155. return !(event.buttons & 1);
  156. }
  157. if (isChrome15OrOpera15plus || isSafari6plus) {
  158. return event.which === 0;
  159. }
  160. }
  161. exports.GrabToPan = GrabToPan;
  162. }));
  163. (function (root, factory) {
  164. factory(root.pdfjsWebOverlayManager = {});
  165. }(this, function (exports) {
  166. var OverlayManager = {
  167. overlays: {},
  168. active: null,
  169. register: function overlayManagerRegister(name, element, callerCloseMethod, canForceClose) {
  170. return new Promise(function (resolve) {
  171. var container;
  172. if (!name || !element || !(container = element.parentNode)) {
  173. throw new Error('Not enough parameters.');
  174. } else if (this.overlays[name]) {
  175. throw new Error('The overlay is already registered.');
  176. }
  177. this.overlays[name] = {
  178. element: element,
  179. container: container,
  180. callerCloseMethod: callerCloseMethod || null,
  181. canForceClose: canForceClose || false
  182. };
  183. resolve();
  184. }.bind(this));
  185. },
  186. unregister: function overlayManagerUnregister(name) {
  187. return new Promise(function (resolve) {
  188. if (!this.overlays[name]) {
  189. throw new Error('The overlay does not exist.');
  190. } else if (this.active === name) {
  191. throw new Error('The overlay cannot be removed while it is active.');
  192. }
  193. delete this.overlays[name];
  194. resolve();
  195. }.bind(this));
  196. },
  197. open: function overlayManagerOpen(name) {
  198. return new Promise(function (resolve) {
  199. if (!this.overlays[name]) {
  200. throw new Error('The overlay does not exist.');
  201. } else if (this.active) {
  202. if (this.overlays[name].canForceClose) {
  203. this._closeThroughCaller();
  204. } else if (this.active === name) {
  205. throw new Error('The overlay is already active.');
  206. } else {
  207. throw new Error('Another overlay is currently active.');
  208. }
  209. }
  210. this.active = name;
  211. this.overlays[this.active].element.classList.remove('hidden');
  212. this.overlays[this.active].container.classList.remove('hidden');
  213. window.addEventListener('keydown', this._keyDown);
  214. resolve();
  215. }.bind(this));
  216. },
  217. close: function overlayManagerClose(name) {
  218. return new Promise(function (resolve) {
  219. if (!this.overlays[name]) {
  220. throw new Error('The overlay does not exist.');
  221. } else if (!this.active) {
  222. throw new Error('The overlay is currently not active.');
  223. } else if (this.active !== name) {
  224. throw new Error('Another overlay is currently active.');
  225. }
  226. this.overlays[this.active].container.classList.add('hidden');
  227. this.overlays[this.active].element.classList.add('hidden');
  228. this.active = null;
  229. window.removeEventListener('keydown', this._keyDown);
  230. resolve();
  231. }.bind(this));
  232. },
  233. _keyDown: function overlayManager_keyDown(evt) {
  234. var self = OverlayManager;
  235. if (self.active && evt.keyCode === 27) {
  236. self._closeThroughCaller();
  237. evt.preventDefault();
  238. }
  239. },
  240. _closeThroughCaller: function overlayManager_closeThroughCaller() {
  241. if (this.overlays[this.active].callerCloseMethod) {
  242. this.overlays[this.active].callerCloseMethod();
  243. }
  244. if (this.active) {
  245. this.close(this.active);
  246. }
  247. }
  248. };
  249. exports.OverlayManager = OverlayManager;
  250. }));
  251. (function (root, factory) {
  252. factory(root.pdfjsWebPDFRenderingQueue = {});
  253. }(this, function (exports) {
  254. var CLEANUP_TIMEOUT = 30000;
  255. var RenderingStates = {
  256. INITIAL: 0,
  257. RUNNING: 1,
  258. PAUSED: 2,
  259. FINISHED: 3
  260. };
  261. var PDFRenderingQueue = function PDFRenderingQueueClosure() {
  262. function PDFRenderingQueue() {
  263. this.pdfViewer = null;
  264. this.pdfThumbnailViewer = null;
  265. this.onIdle = null;
  266. this.highestPriorityPage = null;
  267. this.idleTimeout = null;
  268. this.printing = false;
  269. this.isThumbnailViewEnabled = false;
  270. }
  271. PDFRenderingQueue.prototype = {
  272. setViewer: function PDFRenderingQueue_setViewer(pdfViewer) {
  273. this.pdfViewer = pdfViewer;
  274. },
  275. setThumbnailViewer: function PDFRenderingQueue_setThumbnailViewer(pdfThumbnailViewer) {
  276. this.pdfThumbnailViewer = pdfThumbnailViewer;
  277. },
  278. isHighestPriority: function PDFRenderingQueue_isHighestPriority(view) {
  279. return this.highestPriorityPage === view.renderingId;
  280. },
  281. renderHighestPriority: function PDFRenderingQueue_renderHighestPriority(currentlyVisiblePages) {
  282. if (this.idleTimeout) {
  283. clearTimeout(this.idleTimeout);
  284. this.idleTimeout = null;
  285. }
  286. if (this.pdfViewer.forceRendering(currentlyVisiblePages)) {
  287. return;
  288. }
  289. if (this.pdfThumbnailViewer && this.isThumbnailViewEnabled) {
  290. if (this.pdfThumbnailViewer.forceRendering()) {
  291. return;
  292. }
  293. }
  294. if (this.printing) {
  295. return;
  296. }
  297. if (this.onIdle) {
  298. this.idleTimeout = setTimeout(this.onIdle.bind(this), CLEANUP_TIMEOUT);
  299. }
  300. },
  301. getHighestPriority: function PDFRenderingQueue_getHighestPriority(visible, views, scrolledDown) {
  302. var visibleViews = visible.views;
  303. var numVisible = visibleViews.length;
  304. if (numVisible === 0) {
  305. return false;
  306. }
  307. for (var i = 0; i < numVisible; ++i) {
  308. var view = visibleViews[i].view;
  309. if (!this.isViewFinished(view)) {
  310. return view;
  311. }
  312. }
  313. if (scrolledDown) {
  314. var nextPageIndex = visible.last.id;
  315. if (views[nextPageIndex] && !this.isViewFinished(views[nextPageIndex])) {
  316. return views[nextPageIndex];
  317. }
  318. } else {
  319. var previousPageIndex = visible.first.id - 2;
  320. if (views[previousPageIndex] && !this.isViewFinished(views[previousPageIndex])) {
  321. return views[previousPageIndex];
  322. }
  323. }
  324. return null;
  325. },
  326. isViewFinished: function PDFRenderingQueue_isViewFinished(view) {
  327. return view.renderingState === RenderingStates.FINISHED;
  328. },
  329. renderView: function PDFRenderingQueue_renderView(view) {
  330. var state = view.renderingState;
  331. switch (state) {
  332. case RenderingStates.FINISHED:
  333. return false;
  334. case RenderingStates.PAUSED:
  335. this.highestPriorityPage = view.renderingId;
  336. view.resume();
  337. break;
  338. case RenderingStates.RUNNING:
  339. this.highestPriorityPage = view.renderingId;
  340. break;
  341. case RenderingStates.INITIAL:
  342. this.highestPriorityPage = view.renderingId;
  343. var continueRendering = function () {
  344. this.renderHighestPriority();
  345. }.bind(this);
  346. view.draw().then(continueRendering, continueRendering);
  347. break;
  348. }
  349. return true;
  350. }
  351. };
  352. return PDFRenderingQueue;
  353. }();
  354. exports.RenderingStates = RenderingStates;
  355. exports.PDFRenderingQueue = PDFRenderingQueue;
  356. }));
  357. (function (root, factory) {
  358. factory(root.pdfjsWebPreferences = {});
  359. }(this, function (exports) {
  360. var defaultPreferences = null;
  361. function getDefaultPreferences() {
  362. if (!defaultPreferences) {
  363. defaultPreferences = Promise.resolve({
  364. "showPreviousViewOnLoad": true,
  365. "defaultZoomValue": "",
  366. "sidebarViewOnLoad": 0,
  367. "enableHandToolOnLoad": false,
  368. "enableWebGL": false,
  369. "pdfBugEnabled": false,
  370. "disableRange": false,
  371. "disableStream": false,
  372. "disableAutoFetch": false,
  373. "disableFontFace": false,
  374. "disableTextLayer": false,
  375. "useOnlyCssZoom": false,
  376. "externalLinkTarget": 0,
  377. "enhanceTextSelection": false,
  378. "renderer": "canvas",
  379. "renderInteractiveForms": false,
  380. "disablePageLabels": false
  381. });
  382. }
  383. return defaultPreferences;
  384. }
  385. function cloneObj(obj) {
  386. var result = {};
  387. for (var i in obj) {
  388. if (Object.prototype.hasOwnProperty.call(obj, i)) {
  389. result[i] = obj[i];
  390. }
  391. }
  392. return result;
  393. }
  394. var Preferences = {
  395. prefs: null,
  396. isInitializedPromiseResolved: false,
  397. initializedPromise: null,
  398. initialize: function preferencesInitialize() {
  399. return this.initializedPromise = getDefaultPreferences().then(function (defaults) {
  400. Object.defineProperty(this, 'defaults', {
  401. value: Object.freeze(defaults),
  402. writable: false,
  403. enumerable: true,
  404. configurable: false
  405. });
  406. this.prefs = cloneObj(defaults);
  407. return this._readFromStorage(defaults);
  408. }.bind(this)).then(function (prefObj) {
  409. this.isInitializedPromiseResolved = true;
  410. if (prefObj) {
  411. this.prefs = prefObj;
  412. }
  413. }.bind(this));
  414. },
  415. _writeToStorage: function preferences_writeToStorage(prefObj) {
  416. return Promise.resolve();
  417. },
  418. _readFromStorage: function preferences_readFromStorage(prefObj) {
  419. return Promise.resolve();
  420. },
  421. reset: function preferencesReset() {
  422. return this.initializedPromise.then(function () {
  423. this.prefs = cloneObj(this.defaults);
  424. return this._writeToStorage(this.defaults);
  425. }.bind(this));
  426. },
  427. reload: function preferencesReload() {
  428. return this.initializedPromise.then(function () {
  429. this._readFromStorage(this.defaults).then(function (prefObj) {
  430. if (prefObj) {
  431. this.prefs = prefObj;
  432. }
  433. }.bind(this));
  434. }.bind(this));
  435. },
  436. set: function preferencesSet(name, value) {
  437. return this.initializedPromise.then(function () {
  438. if (this.defaults[name] === undefined) {
  439. throw new Error('preferencesSet: \'' + name + '\' is undefined.');
  440. } else if (value === undefined) {
  441. throw new Error('preferencesSet: no value is specified.');
  442. }
  443. var valueType = typeof value;
  444. var defaultType = typeof this.defaults[name];
  445. if (valueType !== defaultType) {
  446. if (valueType === 'number' && defaultType === 'string') {
  447. value = value.toString();
  448. } else {
  449. throw new Error('Preferences_set: \'' + value + '\' is a \"' + valueType + '\", expected \"' + defaultType + '\".');
  450. }
  451. } else {
  452. if (valueType === 'number' && (value | 0) !== value) {
  453. throw new Error('Preferences_set: \'' + value + '\' must be an \"integer\".');
  454. }
  455. }
  456. this.prefs[name] = value;
  457. return this._writeToStorage(this.prefs);
  458. }.bind(this));
  459. },
  460. get: function preferencesGet(name) {
  461. return this.initializedPromise.then(function () {
  462. var defaultValue = this.defaults[name];
  463. if (defaultValue === undefined) {
  464. throw new Error('preferencesGet: \'' + name + '\' is undefined.');
  465. } else {
  466. var prefValue = this.prefs[name];
  467. if (prefValue !== undefined) {
  468. return prefValue;
  469. }
  470. }
  471. return defaultValue;
  472. }.bind(this));
  473. }
  474. };
  475. Preferences._writeToStorage = function (prefObj) {
  476. return new Promise(function (resolve) {
  477. localStorage.setItem('pdfjs.preferences', JSON.stringify(prefObj));
  478. resolve();
  479. });
  480. };
  481. Preferences._readFromStorage = function (prefObj) {
  482. return new Promise(function (resolve) {
  483. var readPrefs = JSON.parse(localStorage.getItem('pdfjs.preferences'));
  484. resolve(readPrefs);
  485. });
  486. };
  487. exports.Preferences = Preferences;
  488. }));
  489. (function (root, factory) {
  490. factory(root.pdfjsWebViewHistory = {});
  491. }(this, function (exports) {
  492. var DEFAULT_VIEW_HISTORY_CACHE_SIZE = 20;
  493. var ViewHistory = function ViewHistoryClosure() {
  494. function ViewHistory(fingerprint, cacheSize) {
  495. this.fingerprint = fingerprint;
  496. this.cacheSize = cacheSize || DEFAULT_VIEW_HISTORY_CACHE_SIZE;
  497. this.isInitializedPromiseResolved = false;
  498. this.initializedPromise = this._readFromStorage().then(function (databaseStr) {
  499. this.isInitializedPromiseResolved = true;
  500. var database = JSON.parse(databaseStr || '{}');
  501. if (!('files' in database)) {
  502. database.files = [];
  503. }
  504. if (database.files.length >= this.cacheSize) {
  505. database.files.shift();
  506. }
  507. var index;
  508. for (var i = 0, length = database.files.length; i < length; i++) {
  509. var branch = database.files[i];
  510. if (branch.fingerprint === this.fingerprint) {
  511. index = i;
  512. break;
  513. }
  514. }
  515. if (typeof index !== 'number') {
  516. index = database.files.push({ fingerprint: this.fingerprint }) - 1;
  517. }
  518. this.file = database.files[index];
  519. this.database = database;
  520. }.bind(this));
  521. }
  522. ViewHistory.prototype = {
  523. _writeToStorage: function ViewHistory_writeToStorage() {
  524. return new Promise(function (resolve) {
  525. var databaseStr = JSON.stringify(this.database);
  526. localStorage.setItem('pdfjs.history', databaseStr);
  527. resolve();
  528. }.bind(this));
  529. },
  530. _readFromStorage: function ViewHistory_readFromStorage() {
  531. return new Promise(function (resolve) {
  532. var value = localStorage.getItem('pdfjs.history');
  533. if (!value) {
  534. var databaseStr = localStorage.getItem('database');
  535. if (databaseStr) {
  536. try {
  537. var database = JSON.parse(databaseStr);
  538. if (typeof database.files[0].fingerprint === 'string') {
  539. localStorage.setItem('pdfjs.history', databaseStr);
  540. localStorage.removeItem('database');
  541. value = databaseStr;
  542. }
  543. } catch (ex) {
  544. }
  545. }
  546. }
  547. resolve(value);
  548. });
  549. },
  550. set: function ViewHistory_set(name, val) {
  551. if (!this.isInitializedPromiseResolved) {
  552. return;
  553. }
  554. this.file[name] = val;
  555. return this._writeToStorage();
  556. },
  557. setMultiple: function ViewHistory_setMultiple(properties) {
  558. if (!this.isInitializedPromiseResolved) {
  559. return;
  560. }
  561. for (var name in properties) {
  562. this.file[name] = properties[name];
  563. }
  564. return this._writeToStorage();
  565. },
  566. get: function ViewHistory_get(name, defaultValue) {
  567. if (!this.isInitializedPromiseResolved) {
  568. return defaultValue;
  569. }
  570. return this.file[name] || defaultValue;
  571. }
  572. };
  573. return ViewHistory;
  574. }();
  575. exports.ViewHistory = ViewHistory;
  576. }));
  577. (function (root, factory) {
  578. factory(root.pdfjsWebDownloadManager = {}, root.pdfjsWebPDFJS);
  579. }(this, function (exports, pdfjsLib) {
  580. function download(blobUrl, filename) {
  581. var a = document.createElement('a');
  582. if (a.click) {
  583. a.href = blobUrl;
  584. a.target = '_parent';
  585. if ('download' in a) {
  586. a.download = filename;
  587. }
  588. (document.body || document.documentElement).appendChild(a);
  589. a.click();
  590. a.parentNode.removeChild(a);
  591. } else {
  592. if (window.top === window && blobUrl.split('#')[0] === window.location.href.split('#')[0]) {
  593. var padCharacter = blobUrl.indexOf('?') === -1 ? '?' : '&';
  594. blobUrl = blobUrl.replace(/#|$/, padCharacter + '$&');
  595. }
  596. window.open(blobUrl, '_parent');
  597. }
  598. }
  599. function DownloadManager() {
  600. }
  601. DownloadManager.prototype = {
  602. downloadUrl: function DownloadManager_downloadUrl(url, filename) {
  603. if (!pdfjsLib.createValidAbsoluteUrl(url, 'http://example.com')) {
  604. return;
  605. }
  606. download(url + '#pdfjs.action=download', filename);
  607. },
  608. downloadData: function DownloadManager_downloadData(data, filename, contentType) {
  609. if (navigator.msSaveBlob) {
  610. return navigator.msSaveBlob(new Blob([data], { type: contentType }), filename);
  611. }
  612. var blobUrl = pdfjsLib.createObjectURL(data, contentType, pdfjsLib.PDFJS.disableCreateObjectURL);
  613. download(blobUrl, filename);
  614. },
  615. download: function DownloadManager_download(blob, url, filename) {
  616. if (!URL) {
  617. this.downloadUrl(url, filename);
  618. return;
  619. }
  620. if (navigator.msSaveBlob) {
  621. if (!navigator.msSaveBlob(blob, filename)) {
  622. this.downloadUrl(url, filename);
  623. }
  624. return;
  625. }
  626. var blobUrl = URL.createObjectURL(blob);
  627. download(blobUrl, filename);
  628. }
  629. };
  630. exports.DownloadManager = DownloadManager;
  631. }));
  632. (function (root, factory) {
  633. factory(root.pdfjsWebPDFAttachmentViewer = {}, root.pdfjsWebPDFJS);
  634. }(this, function (exports, pdfjsLib) {
  635. var PDFAttachmentViewer = function PDFAttachmentViewerClosure() {
  636. function PDFAttachmentViewer(options) {
  637. this.attachments = null;
  638. this.container = options.container;
  639. this.eventBus = options.eventBus;
  640. this.downloadManager = options.downloadManager;
  641. }
  642. PDFAttachmentViewer.prototype = {
  643. reset: function PDFAttachmentViewer_reset() {
  644. this.attachments = null;
  645. var container = this.container;
  646. while (container.firstChild) {
  647. container.removeChild(container.firstChild);
  648. }
  649. },
  650. _dispatchEvent: function PDFAttachmentViewer_dispatchEvent(attachmentsCount) {
  651. this.eventBus.dispatch('attachmentsloaded', {
  652. source: this,
  653. attachmentsCount: attachmentsCount
  654. });
  655. },
  656. _bindLink: function PDFAttachmentViewer_bindLink(button, content, filename) {
  657. button.onclick = function downloadFile(e) {
  658. this.downloadManager.downloadData(content, filename, '');
  659. return false;
  660. }.bind(this);
  661. },
  662. render: function PDFAttachmentViewer_render(params) {
  663. var attachments = params && params.attachments || null;
  664. var attachmentsCount = 0;
  665. if (this.attachments) {
  666. this.reset();
  667. }
  668. this.attachments = attachments;
  669. if (!attachments) {
  670. this._dispatchEvent(attachmentsCount);
  671. return;
  672. }
  673. var names = Object.keys(attachments).sort(function (a, b) {
  674. return a.toLowerCase().localeCompare(b.toLowerCase());
  675. });
  676. attachmentsCount = names.length;
  677. for (var i = 0; i < attachmentsCount; i++) {
  678. var item = attachments[names[i]];
  679. var filename = pdfjsLib.getFilenameFromUrl(item.filename);
  680. var div = document.createElement('div');
  681. div.className = 'attachmentsItem';
  682. var button = document.createElement('button');
  683. this._bindLink(button, item.content, filename);
  684. button.textContent = pdfjsLib.removeNullCharacters(filename);
  685. div.appendChild(button);
  686. this.container.appendChild(div);
  687. }
  688. this._dispatchEvent(attachmentsCount);
  689. }
  690. };
  691. return PDFAttachmentViewer;
  692. }();
  693. exports.PDFAttachmentViewer = PDFAttachmentViewer;
  694. }));
  695. (function (root, factory) {
  696. factory(root.pdfjsWebPDFOutlineViewer = {}, root.pdfjsWebPDFJS);
  697. }(this, function (exports, pdfjsLib) {
  698. var PDFJS = pdfjsLib.PDFJS;
  699. var DEFAULT_TITLE = '\u2013';
  700. var PDFOutlineViewer = function PDFOutlineViewerClosure() {
  701. function PDFOutlineViewer(options) {
  702. this.outline = null;
  703. this.lastToggleIsShow = true;
  704. this.container = options.container;
  705. this.linkService = options.linkService;
  706. this.eventBus = options.eventBus;
  707. }
  708. PDFOutlineViewer.prototype = {
  709. reset: function PDFOutlineViewer_reset() {
  710. this.outline = null;
  711. this.lastToggleIsShow = true;
  712. var container = this.container;
  713. while (container.firstChild) {
  714. container.removeChild(container.firstChild);
  715. }
  716. },
  717. _dispatchEvent: function PDFOutlineViewer_dispatchEvent(outlineCount) {
  718. this.eventBus.dispatch('outlineloaded', {
  719. source: this,
  720. outlineCount: outlineCount
  721. });
  722. },
  723. _bindLink: function PDFOutlineViewer_bindLink(element, item) {
  724. if (item.url) {
  725. pdfjsLib.addLinkAttributes(element, {
  726. url: item.url,
  727. target: item.newWindow ? PDFJS.LinkTarget.BLANK : undefined
  728. });
  729. return;
  730. }
  731. var self = this, destination = item.dest;
  732. element.href = self.linkService.getDestinationHash(destination);
  733. element.onclick = function () {
  734. if (destination) {
  735. self.linkService.navigateTo(destination);
  736. }
  737. return false;
  738. };
  739. },
  740. _setStyles: function PDFOutlineViewer_setStyles(element, item) {
  741. var styleStr = '';
  742. if (item.bold) {
  743. styleStr += 'font-weight: bold;';
  744. }
  745. if (item.italic) {
  746. styleStr += 'font-style: italic;';
  747. }
  748. if (styleStr) {
  749. element.setAttribute('style', styleStr);
  750. }
  751. },
  752. _addToggleButton: function PDFOutlineViewer_addToggleButton(div) {
  753. var toggler = document.createElement('div');
  754. toggler.className = 'outlineItemToggler';
  755. toggler.onclick = function (event) {
  756. event.stopPropagation();
  757. toggler.classList.toggle('outlineItemsHidden');
  758. if (event.shiftKey) {
  759. var shouldShowAll = !toggler.classList.contains('outlineItemsHidden');
  760. this._toggleOutlineItem(div, shouldShowAll);
  761. }
  762. }.bind(this);
  763. div.insertBefore(toggler, div.firstChild);
  764. },
  765. _toggleOutlineItem: function PDFOutlineViewer_toggleOutlineItem(root, show) {
  766. this.lastToggleIsShow = show;
  767. var togglers = root.querySelectorAll('.outlineItemToggler');
  768. for (var i = 0, ii = togglers.length; i < ii; ++i) {
  769. togglers[i].classList[show ? 'remove' : 'add']('outlineItemsHidden');
  770. }
  771. },
  772. toggleOutlineTree: function PDFOutlineViewer_toggleOutlineTree() {
  773. if (!this.outline) {
  774. return;
  775. }
  776. this._toggleOutlineItem(this.container, !this.lastToggleIsShow);
  777. },
  778. render: function PDFOutlineViewer_render(params) {
  779. var outline = params && params.outline || null;
  780. var outlineCount = 0;
  781. if (this.outline) {
  782. this.reset();
  783. }
  784. this.outline = outline;
  785. if (!outline) {
  786. this._dispatchEvent(outlineCount);
  787. return;
  788. }
  789. var fragment = document.createDocumentFragment();
  790. var queue = [{
  791. parent: fragment,
  792. items: this.outline
  793. }];
  794. var hasAnyNesting = false;
  795. while (queue.length > 0) {
  796. var levelData = queue.shift();
  797. for (var i = 0, len = levelData.items.length; i < len; i++) {
  798. var item = levelData.items[i];
  799. var div = document.createElement('div');
  800. div.className = 'outlineItem';
  801. var element = document.createElement('a');
  802. this._bindLink(element, item);
  803. this._setStyles(element, item);
  804. element.textContent = pdfjsLib.removeNullCharacters(item.title) || DEFAULT_TITLE;
  805. div.appendChild(element);
  806. if (item.items.length > 0) {
  807. hasAnyNesting = true;
  808. this._addToggleButton(div);
  809. var itemsDiv = document.createElement('div');
  810. itemsDiv.className = 'outlineItems';
  811. div.appendChild(itemsDiv);
  812. queue.push({
  813. parent: itemsDiv,
  814. items: item.items
  815. });
  816. }
  817. levelData.parent.appendChild(div);
  818. outlineCount++;
  819. }
  820. }
  821. if (hasAnyNesting) {
  822. this.container.classList.add('outlineWithDeepNesting');
  823. }
  824. this.container.appendChild(fragment);
  825. this._dispatchEvent(outlineCount);
  826. }
  827. };
  828. return PDFOutlineViewer;
  829. }();
  830. exports.PDFOutlineViewer = PDFOutlineViewer;
  831. }));
  832. (function (root, factory) {
  833. factory(root.pdfjsWebPDFSidebar = {}, root.pdfjsWebPDFRenderingQueue);
  834. }(this, function (exports, pdfRenderingQueue) {
  835. var RenderingStates = pdfRenderingQueue.RenderingStates;
  836. var SidebarView = {
  837. NONE: 0,
  838. THUMBS: 1,
  839. OUTLINE: 2,
  840. ATTACHMENTS: 3
  841. };
  842. var PDFSidebar = function PDFSidebarClosure() {
  843. function PDFSidebar(options) {
  844. this.isOpen = false;
  845. this.active = SidebarView.THUMBS;
  846. this.isInitialViewSet = false;
  847. this.onToggled = null;
  848. this.pdfViewer = options.pdfViewer;
  849. this.pdfThumbnailViewer = options.pdfThumbnailViewer;
  850. this.pdfOutlineViewer = options.pdfOutlineViewer;
  851. this.mainContainer = options.mainContainer;
  852. this.outerContainer = options.outerContainer;
  853. this.eventBus = options.eventBus;
  854. this.toggleButton = options.toggleButton;
  855. this.thumbnailButton = options.thumbnailButton;
  856. this.outlineButton = options.outlineButton;
  857. this.attachmentsButton = options.attachmentsButton;
  858. this.thumbnailView = options.thumbnailView;
  859. this.outlineView = options.outlineView;
  860. this.attachmentsView = options.attachmentsView;
  861. this._addEventListeners();
  862. }
  863. PDFSidebar.prototype = {
  864. reset: function PDFSidebar_reset() {
  865. this.isInitialViewSet = false;
  866. this.close();
  867. this.switchView(SidebarView.THUMBS);
  868. this.outlineButton.disabled = false;
  869. this.attachmentsButton.disabled = false;
  870. },
  871. get visibleView() {
  872. return this.isOpen ? this.active : SidebarView.NONE;
  873. },
  874. get isThumbnailViewVisible() {
  875. return this.isOpen && this.active === SidebarView.THUMBS;
  876. },
  877. get isOutlineViewVisible() {
  878. return this.isOpen && this.active === SidebarView.OUTLINE;
  879. },
  880. get isAttachmentsViewVisible() {
  881. return this.isOpen && this.active === SidebarView.ATTACHMENTS;
  882. },
  883. setInitialView: function PDFSidebar_setInitialView(view) {
  884. if (this.isInitialViewSet) {
  885. return;
  886. }
  887. this.isInitialViewSet = true;
  888. if (this.isOpen && view === SidebarView.NONE) {
  889. this._dispatchEvent();
  890. return;
  891. }
  892. var isViewPreserved = view === this.visibleView;
  893. this.switchView(view, true);
  894. if (isViewPreserved) {
  895. this._dispatchEvent();
  896. }
  897. },
  898. switchView: function PDFSidebar_switchView(view, forceOpen) {
  899. if (view === SidebarView.NONE) {
  900. this.close();
  901. return;
  902. }
  903. var isViewChanged = view !== this.active;
  904. var shouldForceRendering = false;
  905. switch (view) {
  906. case SidebarView.THUMBS:
  907. this.thumbnailButton.classList.add('toggled');
  908. this.outlineButton.classList.remove('toggled');
  909. this.attachmentsButton.classList.remove('toggled');
  910. this.thumbnailView.classList.remove('hidden');
  911. this.outlineView.classList.add('hidden');
  912. this.attachmentsView.classList.add('hidden');
  913. if (this.isOpen && isViewChanged) {
  914. this._updateThumbnailViewer();
  915. shouldForceRendering = true;
  916. }
  917. break;
  918. case SidebarView.OUTLINE:
  919. if (this.outlineButton.disabled) {
  920. return;
  921. }
  922. this.thumbnailButton.classList.remove('toggled');
  923. this.outlineButton.classList.add('toggled');
  924. this.attachmentsButton.classList.remove('toggled');
  925. this.thumbnailView.classList.add('hidden');
  926. this.outlineView.classList.remove('hidden');
  927. this.attachmentsView.classList.add('hidden');
  928. break;
  929. case SidebarView.ATTACHMENTS:
  930. if (this.attachmentsButton.disabled) {
  931. return;
  932. }
  933. this.thumbnailButton.classList.remove('toggled');
  934. this.outlineButton.classList.remove('toggled');
  935. this.attachmentsButton.classList.add('toggled');
  936. this.thumbnailView.classList.add('hidden');
  937. this.outlineView.classList.add('hidden');
  938. this.attachmentsView.classList.remove('hidden');
  939. break;
  940. default:
  941. console.error('PDFSidebar_switchView: "' + view + '" is an unsupported value.');
  942. return;
  943. }
  944. this.active = view | 0;
  945. if (forceOpen && !this.isOpen) {
  946. this.open();
  947. return;
  948. }
  949. if (shouldForceRendering) {
  950. this._forceRendering();
  951. }
  952. if (isViewChanged) {
  953. this._dispatchEvent();
  954. }
  955. },
  956. open: function PDFSidebar_open() {
  957. if (this.isOpen) {
  958. return;
  959. }
  960. this.isOpen = true;
  961. this.toggleButton.classList.add('toggled');
  962. this.outerContainer.classList.add('sidebarMoving');
  963. this.outerContainer.classList.add('sidebarOpen');
  964. if (this.active === SidebarView.THUMBS) {
  965. this._updateThumbnailViewer();
  966. }
  967. this._forceRendering();
  968. this._dispatchEvent();
  969. },
  970. close: function PDFSidebar_close() {
  971. if (!this.isOpen) {
  972. return;
  973. }
  974. this.isOpen = false;
  975. this.toggleButton.classList.remove('toggled');
  976. this.outerContainer.classList.add('sidebarMoving');
  977. this.outerContainer.classList.remove('sidebarOpen');
  978. this._forceRendering();
  979. this._dispatchEvent();
  980. },
  981. toggle: function PDFSidebar_toggle() {
  982. if (this.isOpen) {
  983. this.close();
  984. } else {
  985. this.open();
  986. }
  987. },
  988. _dispatchEvent: function PDFSidebar_dispatchEvent() {
  989. this.eventBus.dispatch('sidebarviewchanged', {
  990. source: this,
  991. view: this.visibleView
  992. });
  993. },
  994. _forceRendering: function PDFSidebar_forceRendering() {
  995. if (this.onToggled) {
  996. this.onToggled();
  997. } else {
  998. this.pdfViewer.forceRendering();
  999. this.pdfThumbnailViewer.forceRendering();
  1000. }
  1001. },
  1002. _updateThumbnailViewer: function PDFSidebar_updateThumbnailViewer() {
  1003. var pdfViewer = this.pdfViewer;
  1004. var thumbnailViewer = this.pdfThumbnailViewer;
  1005. var pagesCount = pdfViewer.pagesCount;
  1006. for (var pageIndex = 0; pageIndex < pagesCount; pageIndex++) {
  1007. var pageView = pdfViewer.getPageView(pageIndex);
  1008. if (pageView && pageView.renderingState === RenderingStates.FINISHED) {
  1009. var thumbnailView = thumbnailViewer.getThumbnail(pageIndex);
  1010. thumbnailView.setImage(pageView);
  1011. }
  1012. }
  1013. thumbnailViewer.scrollThumbnailIntoView(pdfViewer.currentPageNumber);
  1014. },
  1015. _addEventListeners: function PDFSidebar_addEventListeners() {
  1016. var self = this;
  1017. self.mainContainer.addEventListener('transitionend', function (evt) {
  1018. if (evt.target === this) {
  1019. self.outerContainer.classList.remove('sidebarMoving');
  1020. }
  1021. });
  1022. self.thumbnailButton.addEventListener('click', function () {
  1023. self.switchView(SidebarView.THUMBS);
  1024. });
  1025. self.outlineButton.addEventListener('click', function () {
  1026. self.switchView(SidebarView.OUTLINE);
  1027. });
  1028. self.outlineButton.addEventListener('dblclick', function () {
  1029. self.pdfOutlineViewer.toggleOutlineTree();
  1030. });
  1031. self.attachmentsButton.addEventListener('click', function () {
  1032. self.switchView(SidebarView.ATTACHMENTS);
  1033. });
  1034. self.eventBus.on('outlineloaded', function (e) {
  1035. var outlineCount = e.outlineCount;
  1036. self.outlineButton.disabled = !outlineCount;
  1037. if (!outlineCount && self.active === SidebarView.OUTLINE) {
  1038. self.switchView(SidebarView.THUMBS);
  1039. }
  1040. });
  1041. self.eventBus.on('attachmentsloaded', function (e) {
  1042. var attachmentsCount = e.attachmentsCount;
  1043. self.attachmentsButton.disabled = !attachmentsCount;
  1044. if (!attachmentsCount && self.active === SidebarView.ATTACHMENTS) {
  1045. self.switchView(SidebarView.THUMBS);
  1046. }
  1047. });
  1048. self.eventBus.on('presentationmodechanged', function (e) {
  1049. if (!e.active && !e.switchInProgress && self.isThumbnailViewVisible) {
  1050. self._updateThumbnailViewer();
  1051. }
  1052. });
  1053. }
  1054. };
  1055. return PDFSidebar;
  1056. }();
  1057. exports.SidebarView = SidebarView;
  1058. exports.PDFSidebar = PDFSidebar;
  1059. }));
  1060. (function (root, factory) {
  1061. factory(root.pdfjsWebUIUtils = {}, root.pdfjsWebPDFJS);
  1062. }(this, function (exports, pdfjsLib) {
  1063. var CSS_UNITS = 96.0 / 72.0;
  1064. var DEFAULT_SCALE_VALUE = 'auto';
  1065. var DEFAULT_SCALE = 1.0;
  1066. var MIN_SCALE = 0.25;
  1067. var MAX_SCALE = 10.0;
  1068. var UNKNOWN_SCALE = 0;
  1069. var MAX_AUTO_SCALE = 1.25;
  1070. var SCROLLBAR_PADDING = 40;
  1071. var VERTICAL_PADDING = 5;
  1072. var RendererType = {
  1073. CANVAS: 'canvas',
  1074. SVG: 'svg'
  1075. };
  1076. var mozL10n = document.mozL10n || document.webL10n;
  1077. var PDFJS = pdfjsLib.PDFJS;
  1078. PDFJS.disableFullscreen = PDFJS.disableFullscreen === undefined ? false : PDFJS.disableFullscreen;
  1079. PDFJS.useOnlyCssZoom = PDFJS.useOnlyCssZoom === undefined ? false : PDFJS.useOnlyCssZoom;
  1080. PDFJS.maxCanvasPixels = PDFJS.maxCanvasPixels === undefined ? 16777216 : PDFJS.maxCanvasPixels;
  1081. PDFJS.disableHistory = PDFJS.disableHistory === undefined ? false : PDFJS.disableHistory;
  1082. PDFJS.disableTextLayer = PDFJS.disableTextLayer === undefined ? false : PDFJS.disableTextLayer;
  1083. PDFJS.ignoreCurrentPositionOnZoom = PDFJS.ignoreCurrentPositionOnZoom === undefined ? false : PDFJS.ignoreCurrentPositionOnZoom;
  1084. PDFJS.locale = PDFJS.locale === undefined ? navigator.language : PDFJS.locale;
  1085. function getOutputScale(ctx) {
  1086. var devicePixelRatio = window.devicePixelRatio || 1;
  1087. var backingStoreRatio = ctx.webkitBackingStorePixelRatio || ctx.mozBackingStorePixelRatio || ctx.msBackingStorePixelRatio || ctx.oBackingStorePixelRatio || ctx.backingStorePixelRatio || 1;
  1088. var pixelRatio = devicePixelRatio / backingStoreRatio;
  1089. return {
  1090. sx: pixelRatio,
  1091. sy: pixelRatio,
  1092. scaled: pixelRatio !== 1
  1093. };
  1094. }
  1095. function scrollIntoView(element, spot, skipOverflowHiddenElements) {
  1096. var parent = element.offsetParent;
  1097. if (!parent) {
  1098. console.error('offsetParent is not set -- cannot scroll');
  1099. return;
  1100. }
  1101. var checkOverflow = skipOverflowHiddenElements || false;
  1102. var offsetY = element.offsetTop + element.clientTop;
  1103. var offsetX = element.offsetLeft + element.clientLeft;
  1104. while (parent.clientHeight === parent.scrollHeight || checkOverflow && getComputedStyle(parent).overflow === 'hidden') {
  1105. if (parent.dataset._scaleY) {
  1106. offsetY /= parent.dataset._scaleY;
  1107. offsetX /= parent.dataset._scaleX;
  1108. }
  1109. offsetY += parent.offsetTop;
  1110. offsetX += parent.offsetLeft;
  1111. parent = parent.offsetParent;
  1112. if (!parent) {
  1113. return;
  1114. }
  1115. }
  1116. if (spot) {
  1117. if (spot.top !== undefined) {
  1118. offsetY += spot.top;
  1119. }
  1120. if (spot.left !== undefined) {
  1121. offsetX += spot.left;
  1122. parent.scrollLeft = offsetX;
  1123. }
  1124. }
  1125. parent.scrollTop = offsetY;
  1126. }
  1127. function watchScroll(viewAreaElement, callback) {
  1128. var debounceScroll = function debounceScroll(evt) {
  1129. if (rAF) {
  1130. return;
  1131. }
  1132. rAF = window.requestAnimationFrame(function viewAreaElementScrolled() {
  1133. rAF = null;
  1134. var currentY = viewAreaElement.scrollTop;
  1135. var lastY = state.lastY;
  1136. if (currentY !== lastY) {
  1137. state.down = currentY > lastY;
  1138. }
  1139. state.lastY = currentY;
  1140. callback(state);
  1141. });
  1142. };
  1143. var state = {
  1144. down: true,
  1145. lastY: viewAreaElement.scrollTop,
  1146. _eventHandler: debounceScroll
  1147. };
  1148. var rAF = null;
  1149. viewAreaElement.addEventListener('scroll', debounceScroll, true);
  1150. return state;
  1151. }
  1152. function parseQueryString(query) {
  1153. var innerUrl;
  1154. if(query.indexOf("?url=") > -1) {
  1155. var parts = query.split('?url=');
  1156. query = parts[0];
  1157. innerUrl = parts[1];
  1158. }
  1159. var parts = query.split('&');
  1160. var params = {};
  1161. for (var i = 0, ii = parts.length; i < ii; ++i) {
  1162. var param = parts[i].split('=');
  1163. var key = param[0].toLowerCase();
  1164. var value = param.length > 1 ? param.slice(1, param.length).join("=") : null;
  1165. params[decodeURIComponent(key)] = decodeURIComponent(value);
  1166. }
  1167. for(var key in params) {
  1168. if(!params.hasOwnProperty(key) || key === 'file') {
  1169. continue;
  1170. } else {
  1171. params.file += ('&' + key + '=' + params[key]);
  1172. }
  1173. }
  1174. if(params.file && innerUrl) {
  1175. params.file += ('?url=' + innerUrl);
  1176. }
  1177. return params;
  1178. }
  1179. function binarySearchFirstItem(items, condition) {
  1180. var minIndex = 0;
  1181. var maxIndex = items.length - 1;
  1182. if (items.length === 0 || !condition(items[maxIndex])) {
  1183. return items.length;
  1184. }
  1185. if (condition(items[minIndex])) {
  1186. return minIndex;
  1187. }
  1188. while (minIndex < maxIndex) {
  1189. var currentIndex = minIndex + maxIndex >> 1;
  1190. var currentItem = items[currentIndex];
  1191. if (condition(currentItem)) {
  1192. maxIndex = currentIndex;
  1193. } else {
  1194. minIndex = currentIndex + 1;
  1195. }
  1196. }
  1197. return minIndex;
  1198. }
  1199. function approximateFraction(x) {
  1200. if (Math.floor(x) === x) {
  1201. return [
  1202. x,
  1203. 1
  1204. ];
  1205. }
  1206. var xinv = 1 / x;
  1207. var limit = 8;
  1208. if (xinv > limit) {
  1209. return [
  1210. 1,
  1211. limit
  1212. ];
  1213. } else if (Math.floor(xinv) === xinv) {
  1214. return [
  1215. 1,
  1216. xinv
  1217. ];
  1218. }
  1219. var x_ = x > 1 ? xinv : x;
  1220. var a = 0, b = 1, c = 1, d = 1;
  1221. while (true) {
  1222. var p = a + c, q = b + d;
  1223. if (q > limit) {
  1224. break;
  1225. }
  1226. if (x_ <= p / q) {
  1227. c = p;
  1228. d = q;
  1229. } else {
  1230. a = p;
  1231. b = q;
  1232. }
  1233. }
  1234. var result;
  1235. if (x_ - a / b < c / d - x_) {
  1236. result = x_ === x ? [
  1237. a,
  1238. b
  1239. ] : [
  1240. b,
  1241. a
  1242. ];
  1243. } else {
  1244. result = x_ === x ? [
  1245. c,
  1246. d
  1247. ] : [
  1248. d,
  1249. c
  1250. ];
  1251. }
  1252. return result;
  1253. }
  1254. function roundToDivide(x, div) {
  1255. var r = x % div;
  1256. return r === 0 ? x : Math.round(x - r + div);
  1257. }
  1258. function getVisibleElements(scrollEl, views, sortByVisibility) {
  1259. var top = scrollEl.scrollTop, bottom = top + scrollEl.clientHeight;
  1260. var left = scrollEl.scrollLeft, right = left + scrollEl.clientWidth;
  1261. function isElementBottomBelowViewTop(view) {
  1262. var element = view.div;
  1263. var elementBottom = element.offsetTop + element.clientTop + element.clientHeight;
  1264. return elementBottom > top;
  1265. }
  1266. var visible = [], view, element;
  1267. var currentHeight, viewHeight, hiddenHeight, percentHeight;
  1268. var currentWidth, viewWidth;
  1269. var firstVisibleElementInd = views.length === 0 ? 0 : binarySearchFirstItem(views, isElementBottomBelowViewTop);
  1270. for (var i = firstVisibleElementInd, ii = views.length; i < ii; i++) {
  1271. view = views[i];
  1272. element = view.div;
  1273. currentHeight = element.offsetTop + element.clientTop;
  1274. viewHeight = element.clientHeight;
  1275. if (currentHeight > bottom) {
  1276. break;
  1277. }
  1278. currentWidth = element.offsetLeft + element.clientLeft;
  1279. viewWidth = element.clientWidth;
  1280. if (currentWidth + viewWidth < left || currentWidth > right) {
  1281. continue;
  1282. }
  1283. hiddenHeight = Math.max(0, top - currentHeight) + Math.max(0, currentHeight + viewHeight - bottom);
  1284. percentHeight = (viewHeight - hiddenHeight) * 100 / viewHeight | 0;
  1285. visible.push({
  1286. id: view.id,
  1287. x: currentWidth,
  1288. y: currentHeight,
  1289. view: view,
  1290. percent: percentHeight
  1291. });
  1292. }
  1293. var first = visible[0];
  1294. var last = visible[visible.length - 1];
  1295. if (sortByVisibility) {
  1296. visible.sort(function (a, b) {
  1297. var pc = a.percent - b.percent;
  1298. if (Math.abs(pc) > 0.001) {
  1299. return -pc;
  1300. }
  1301. return a.id - b.id;
  1302. });
  1303. }
  1304. return {
  1305. first: first,
  1306. last: last,
  1307. views: visible
  1308. };
  1309. }
  1310. function noContextMenuHandler(e) {
  1311. e.preventDefault();
  1312. }
  1313. function getPDFFileNameFromURL(url) {
  1314. var reURI = /^(?:([^:]+:)?\/\/[^\/]+)?([^?#]*)(\?[^#]*)?(#.*)?$/;
  1315. var reFilename = /[^\/?#=]+\.pdf\b(?!.*\.pdf\b)/i;
  1316. var splitURI = reURI.exec(url);
  1317. var suggestedFilename = reFilename.exec(splitURI[1]) || reFilename.exec(splitURI[2]) || reFilename.exec(splitURI[3]);
  1318. if (suggestedFilename) {
  1319. suggestedFilename = suggestedFilename[0];
  1320. if (suggestedFilename.indexOf('%') !== -1) {
  1321. try {
  1322. suggestedFilename = reFilename.exec(decodeURIComponent(suggestedFilename))[0];
  1323. } catch (e) {
  1324. }
  1325. }
  1326. }
  1327. return suggestedFilename || 'document.pdf';
  1328. }
  1329. function normalizeWheelEventDelta(evt) {
  1330. var delta = Math.sqrt(evt.deltaX * evt.deltaX + evt.deltaY * evt.deltaY);
  1331. var angle = Math.atan2(evt.deltaY, evt.deltaX);
  1332. if (-0.25 * Math.PI < angle && angle < 0.75 * Math.PI) {
  1333. delta = -delta;
  1334. }
  1335. var MOUSE_DOM_DELTA_PIXEL_MODE = 0;
  1336. var MOUSE_DOM_DELTA_LINE_MODE = 1;
  1337. var MOUSE_PIXELS_PER_LINE = 30;
  1338. var MOUSE_LINES_PER_PAGE = 30;
  1339. if (evt.deltaMode === MOUSE_DOM_DELTA_PIXEL_MODE) {
  1340. delta /= MOUSE_PIXELS_PER_LINE * MOUSE_LINES_PER_PAGE;
  1341. } else if (evt.deltaMode === MOUSE_DOM_DELTA_LINE_MODE) {
  1342. delta /= MOUSE_LINES_PER_PAGE;
  1343. }
  1344. return delta;
  1345. }
  1346. var animationStarted = new Promise(function (resolve) {
  1347. window.requestAnimationFrame(resolve);
  1348. });
  1349. var localized = new Promise(function (resolve, reject) {
  1350. if (!mozL10n) {
  1351. resolve();
  1352. return;
  1353. }
  1354. if (mozL10n.getReadyState() !== 'loading') {
  1355. resolve();
  1356. return;
  1357. }
  1358. window.addEventListener('localized', function localized(evt) {
  1359. resolve();
  1360. });
  1361. });
  1362. var EventBus = function EventBusClosure() {
  1363. function EventBus() {
  1364. this._listeners = Object.create(null);
  1365. }
  1366. EventBus.prototype = {
  1367. on: function EventBus_on(eventName, listener) {
  1368. var eventListeners = this._listeners[eventName];
  1369. if (!eventListeners) {
  1370. eventListeners = [];
  1371. this._listeners[eventName] = eventListeners;
  1372. }
  1373. eventListeners.push(listener);
  1374. },
  1375. off: function EventBus_on(eventName, listener) {
  1376. var eventListeners = this._listeners[eventName];
  1377. var i;
  1378. if (!eventListeners || (i = eventListeners.indexOf(listener)) < 0) {
  1379. return;
  1380. }
  1381. eventListeners.splice(i, 1);
  1382. },
  1383. dispatch: function EventBus_dispath(eventName) {
  1384. var eventListeners = this._listeners[eventName];
  1385. if (!eventListeners || eventListeners.length === 0) {
  1386. return;
  1387. }
  1388. var args = Array.prototype.slice.call(arguments, 1);
  1389. eventListeners.slice(0).forEach(function (listener) {
  1390. listener.apply(null, args);
  1391. });
  1392. }
  1393. };
  1394. return EventBus;
  1395. }();
  1396. var ProgressBar = function ProgressBarClosure() {
  1397. function clamp(v, min, max) {
  1398. return Math.min(Math.max(v, min), max);
  1399. }
  1400. function ProgressBar(id, opts) {
  1401. this.visible = true;
  1402. this.div = document.querySelector(id + ' .progress');
  1403. this.bar = this.div.parentNode;
  1404. this.height = opts.height || 100;
  1405. this.width = opts.width || 100;
  1406. this.units = opts.units || '%';
  1407. this.div.style.height = this.height + this.units;
  1408. this.percent = 0;
  1409. }
  1410. ProgressBar.prototype = {
  1411. updateBar: function ProgressBar_updateBar() {
  1412. if (this._indeterminate) {
  1413. this.div.classList.add('indeterminate');
  1414. this.div.style.width = this.width + this.units;
  1415. return;
  1416. }
  1417. this.div.classList.remove('indeterminate');
  1418. var progressSize = this.width * this._percent / 100;
  1419. this.div.style.width = progressSize + this.units;
  1420. },
  1421. get percent() {
  1422. return this._percent;
  1423. },
  1424. set percent(val) {
  1425. this._indeterminate = isNaN(val);
  1426. this._percent = clamp(val, 0, 100);
  1427. this.updateBar();
  1428. },
  1429. setWidth: function ProgressBar_setWidth(viewer) {
  1430. if (viewer) {
  1431. var container = viewer.parentNode;
  1432. var scrollbarWidth = container.offsetWidth - viewer.offsetWidth;
  1433. if (scrollbarWidth > 0) {
  1434. this.bar.setAttribute('style', 'width: calc(100% - ' + scrollbarWidth + 'px);');
  1435. }
  1436. }
  1437. },
  1438. hide: function ProgressBar_hide() {
  1439. if (!this.visible) {
  1440. return;
  1441. }
  1442. this.visible = false;
  1443. this.bar.classList.add('hidden');
  1444. document.body.classList.remove('loadingInProgress');
  1445. },
  1446. show: function ProgressBar_show() {
  1447. if (this.visible) {
  1448. return;
  1449. }
  1450. this.visible = true;
  1451. document.body.classList.add('loadingInProgress');
  1452. this.bar.classList.remove('hidden');
  1453. }
  1454. };
  1455. return ProgressBar;
  1456. }();
  1457. exports.CSS_UNITS = CSS_UNITS;
  1458. exports.DEFAULT_SCALE_VALUE = DEFAULT_SCALE_VALUE;
  1459. exports.DEFAULT_SCALE = DEFAULT_SCALE;
  1460. exports.MIN_SCALE = MIN_SCALE;
  1461. exports.MAX_SCALE = MAX_SCALE;
  1462. exports.UNKNOWN_SCALE = UNKNOWN_SCALE;
  1463. exports.MAX_AUTO_SCALE = MAX_AUTO_SCALE;
  1464. exports.SCROLLBAR_PADDING = SCROLLBAR_PADDING;
  1465. exports.VERTICAL_PADDING = VERTICAL_PADDING;
  1466. exports.RendererType = RendererType;
  1467. exports.mozL10n = mozL10n;
  1468. exports.EventBus = EventBus;
  1469. exports.ProgressBar = ProgressBar;
  1470. exports.getPDFFileNameFromURL = getPDFFileNameFromURL;
  1471. exports.noContextMenuHandler = noContextMenuHandler;
  1472. exports.parseQueryString = parseQueryString;
  1473. exports.getVisibleElements = getVisibleElements;
  1474. exports.roundToDivide = roundToDivide;
  1475. exports.approximateFraction = approximateFraction;
  1476. exports.getOutputScale = getOutputScale;
  1477. exports.scrollIntoView = scrollIntoView;
  1478. exports.watchScroll = watchScroll;
  1479. exports.binarySearchFirstItem = binarySearchFirstItem;
  1480. exports.normalizeWheelEventDelta = normalizeWheelEventDelta;
  1481. exports.animationStarted = animationStarted;
  1482. exports.localized = localized;
  1483. }));
  1484. (function (root, factory) {
  1485. factory(root.pdfjsWebDOMEvents = {}, root.pdfjsWebUIUtils);
  1486. }(this, function (exports, uiUtils) {
  1487. var EventBus = uiUtils.EventBus;
  1488. function attachDOMEventsToEventBus(eventBus) {
  1489. eventBus.on('documentload', function () {
  1490. var event = document.createEvent('CustomEvent');
  1491. event.initCustomEvent('documentload', true, true, {});
  1492. window.dispatchEvent(event);
  1493. });
  1494. eventBus.on('pagerendered', function (e) {
  1495. var event = document.createEvent('CustomEvent');
  1496. event.initCustomEvent('pagerendered', true, true, {
  1497. pageNumber: e.pageNumber,
  1498. cssTransform: e.cssTransform
  1499. });
  1500. e.source.div.dispatchEvent(event);
  1501. });
  1502. eventBus.on('textlayerrendered', function (e) {
  1503. var event = document.createEvent('CustomEvent');
  1504. event.initCustomEvent('textlayerrendered', true, true, { pageNumber: e.pageNumber });
  1505. e.source.textLayerDiv.dispatchEvent(event);
  1506. });
  1507. eventBus.on('pagechange', function (e) {
  1508. var event = document.createEvent('UIEvents');
  1509. event.initUIEvent('pagechange', true, true, window, 0);
  1510. event.pageNumber = e.pageNumber;
  1511. e.source.container.dispatchEvent(event);
  1512. });
  1513. eventBus.on('pagesinit', function (e) {
  1514. var event = document.createEvent('CustomEvent');
  1515. event.initCustomEvent('pagesinit', true, true, null);
  1516. e.source.container.dispatchEvent(event);
  1517. });
  1518. eventBus.on('pagesloaded', function (e) {
  1519. var event = document.createEvent('CustomEvent');
  1520. event.initCustomEvent('pagesloaded', true, true, { pagesCount: e.pagesCount });
  1521. e.source.container.dispatchEvent(event);
  1522. });
  1523. eventBus.on('scalechange', function (e) {
  1524. var event = document.createEvent('UIEvents');
  1525. event.initUIEvent('scalechange', true, true, window, 0);
  1526. event.scale = e.scale;
  1527. event.presetValue = e.presetValue;
  1528. e.source.container.dispatchEvent(event);
  1529. });
  1530. eventBus.on('updateviewarea', function (e) {
  1531. var event = document.createEvent('UIEvents');
  1532. event.initUIEvent('updateviewarea', true, true, window, 0);
  1533. event.location = e.location;
  1534. e.source.container.dispatchEvent(event);
  1535. });
  1536. eventBus.on('find', function (e) {
  1537. if (e.source === window) {
  1538. return;
  1539. }
  1540. var event = document.createEvent('CustomEvent');
  1541. event.initCustomEvent('find' + e.type, true, true, {
  1542. query: e.query,
  1543. phraseSearch: e.phraseSearch,
  1544. caseSensitive: e.caseSensitive,
  1545. highlightAll: e.highlightAll,
  1546. findPrevious: e.findPrevious
  1547. });
  1548. window.dispatchEvent(event);
  1549. });
  1550. eventBus.on('attachmentsloaded', function (e) {
  1551. var event = document.createEvent('CustomEvent');
  1552. event.initCustomEvent('attachmentsloaded', true, true, { attachmentsCount: e.attachmentsCount });
  1553. e.source.container.dispatchEvent(event);
  1554. });
  1555. eventBus.on('sidebarviewchanged', function (e) {
  1556. var event = document.createEvent('CustomEvent');
  1557. event.initCustomEvent('sidebarviewchanged', true, true, { view: e.view });
  1558. e.source.outerContainer.dispatchEvent(event);
  1559. });
  1560. eventBus.on('pagemode', function (e) {
  1561. var event = document.createEvent('CustomEvent');
  1562. event.initCustomEvent('pagemode', true, true, { mode: e.mode });
  1563. e.source.pdfViewer.container.dispatchEvent(event);
  1564. });
  1565. eventBus.on('namedaction', function (e) {
  1566. var event = document.createEvent('CustomEvent');
  1567. event.initCustomEvent('namedaction', true, true, { action: e.action });
  1568. e.source.pdfViewer.container.dispatchEvent(event);
  1569. });
  1570. eventBus.on('presentationmodechanged', function (e) {
  1571. var event = document.createEvent('CustomEvent');
  1572. event.initCustomEvent('presentationmodechanged', true, true, {
  1573. active: e.active,
  1574. switchInProgress: e.switchInProgress
  1575. });
  1576. window.dispatchEvent(event);
  1577. });
  1578. eventBus.on('outlineloaded', function (e) {
  1579. var event = document.createEvent('CustomEvent');
  1580. event.initCustomEvent('outlineloaded', true, true, { outlineCount: e.outlineCount });
  1581. e.source.container.dispatchEvent(event);
  1582. });
  1583. }
  1584. var globalEventBus = null;
  1585. function getGlobalEventBus() {
  1586. if (globalEventBus) {
  1587. return globalEventBus;
  1588. }
  1589. globalEventBus = new EventBus();
  1590. attachDOMEventsToEventBus(globalEventBus);
  1591. return globalEventBus;
  1592. }
  1593. exports.attachDOMEventsToEventBus = attachDOMEventsToEventBus;
  1594. exports.getGlobalEventBus = getGlobalEventBus;
  1595. }));
  1596. (function (root, factory) {
  1597. factory(root.pdfjsWebHandTool = {}, root.pdfjsWebGrabToPan, root.pdfjsWebPreferences, root.pdfjsWebUIUtils);
  1598. }(this, function (exports, grabToPan, preferences, uiUtils) {
  1599. var GrabToPan = grabToPan.GrabToPan;
  1600. var Preferences = preferences.Preferences;
  1601. var localized = uiUtils.localized;
  1602. var HandTool = function HandToolClosure() {
  1603. function HandTool(options) {
  1604. this.container = options.container;
  1605. this.eventBus = options.eventBus;
  1606. this.wasActive = false;
  1607. this.handTool = new GrabToPan({
  1608. element: this.container,
  1609. onActiveChanged: function (isActive) {
  1610. this.eventBus.dispatch('handtoolchanged', { isActive: isActive });
  1611. }.bind(this)
  1612. });
  1613. this.eventBus.on('togglehandtool', this.toggle.bind(this));
  1614. Promise.all([
  1615. localized,
  1616. Preferences.get('enableHandToolOnLoad')
  1617. ]).then(function resolved(values) {
  1618. if (values[1] === true) {
  1619. this.handTool.activate();
  1620. }
  1621. }.bind(this)).catch(function rejected(reason) {
  1622. });
  1623. this.eventBus.on('presentationmodechanged', function (e) {
  1624. if (e.switchInProgress) {
  1625. return;
  1626. }
  1627. if (e.active) {
  1628. this.enterPresentationMode();
  1629. } else {
  1630. this.exitPresentationMode();
  1631. }
  1632. }.bind(this));
  1633. }
  1634. HandTool.prototype = {
  1635. get isActive() {
  1636. return !!this.handTool.active;
  1637. },
  1638. toggle: function HandTool_toggle() {
  1639. this.handTool.toggle();
  1640. },
  1641. enterPresentationMode: function HandTool_enterPresentationMode() {
  1642. if (this.isActive) {
  1643. this.wasActive = true;
  1644. this.handTool.deactivate();
  1645. }
  1646. },
  1647. exitPresentationMode: function HandTool_exitPresentationMode() {
  1648. if (this.wasActive) {
  1649. this.wasActive = false;
  1650. this.handTool.activate();
  1651. }
  1652. }
  1653. };
  1654. return HandTool;
  1655. }();
  1656. exports.HandTool = HandTool;
  1657. }));
  1658. (function (root, factory) {
  1659. factory(root.pdfjsWebPasswordPrompt = {}, root.pdfjsWebUIUtils, root.pdfjsWebOverlayManager, root.pdfjsWebPDFJS);
  1660. }(this, function (exports, uiUtils, overlayManager, pdfjsLib) {
  1661. var mozL10n = uiUtils.mozL10n;
  1662. var OverlayManager = overlayManager.OverlayManager;
  1663. var PasswordPrompt = function PasswordPromptClosure() {
  1664. function PasswordPrompt(options) {
  1665. this.overlayName = options.overlayName;
  1666. this.container = options.container;
  1667. this.label = options.label;
  1668. this.input = options.input;
  1669. this.submitButton = options.submitButton;
  1670. this.cancelButton = options.cancelButton;
  1671. this.updateCallback = null;
  1672. this.reason = null;
  1673. this.submitButton.addEventListener('click', this.verify.bind(this));
  1674. this.cancelButton.addEventListener('click', this.close.bind(this));
  1675. this.input.addEventListener('keydown', function (e) {
  1676. if (e.keyCode === 13) {
  1677. this.verify();
  1678. }
  1679. }.bind(this));
  1680. OverlayManager.register(this.overlayName, this.container, this.close.bind(this), true);
  1681. }
  1682. PasswordPrompt.prototype = {
  1683. open: function PasswordPrompt_open() {
  1684. OverlayManager.open(this.overlayName).then(function () {
  1685. this.input.type = 'password';
  1686. this.input.focus();
  1687. var promptString = mozL10n.get('password_label', null, 'Enter the password to open this PDF file.');
  1688. if (this.reason === pdfjsLib.PasswordResponses.INCORRECT_PASSWORD) {
  1689. promptString = mozL10n.get('password_invalid', null, 'Invalid password. Please try again.');
  1690. }
  1691. this.label.textContent = promptString;
  1692. }.bind(this));
  1693. },
  1694. close: function PasswordPrompt_close() {
  1695. OverlayManager.close(this.overlayName).then(function () {
  1696. this.input.value = '';
  1697. this.input.type = '';
  1698. }.bind(this));
  1699. },
  1700. verify: function PasswordPrompt_verify() {
  1701. var password = this.input.value;
  1702. if (password && password.length > 0) {
  1703. this.close();
  1704. return this.updateCallback(password);
  1705. }
  1706. },
  1707. setUpdateCallback: function PasswordPrompt_setUpdateCallback(updateCallback, reason) {
  1708. this.updateCallback = updateCallback;
  1709. this.reason = reason;
  1710. }
  1711. };
  1712. return PasswordPrompt;
  1713. }();
  1714. exports.PasswordPrompt = PasswordPrompt;
  1715. }));
  1716. (function (root, factory) {
  1717. factory(root.pdfjsWebPDFDocumentProperties = {}, root.pdfjsWebUIUtils, root.pdfjsWebOverlayManager);
  1718. }(this, function (exports, uiUtils, overlayManager) {
  1719. var getPDFFileNameFromURL = uiUtils.getPDFFileNameFromURL;
  1720. var mozL10n = uiUtils.mozL10n;
  1721. var OverlayManager = overlayManager.OverlayManager;
  1722. var PDFDocumentProperties = function PDFDocumentPropertiesClosure() {
  1723. function PDFDocumentProperties(options) {
  1724. this.fields = options.fields;
  1725. this.overlayName = options.overlayName;
  1726. this.container = options.container;
  1727. this.rawFileSize = 0;
  1728. this.url = null;
  1729. this.pdfDocument = null;
  1730. if (options.closeButton) {
  1731. options.closeButton.addEventListener('click', this.close.bind(this));
  1732. }
  1733. this.dataAvailablePromise = new Promise(function (resolve) {
  1734. this.resolveDataAvailable = resolve;
  1735. }.bind(this));
  1736. OverlayManager.register(this.overlayName, this.container, this.close.bind(this));
  1737. }
  1738. PDFDocumentProperties.prototype = {
  1739. open: function PDFDocumentProperties_open() {
  1740. Promise.all([
  1741. OverlayManager.open(this.overlayName),
  1742. this.dataAvailablePromise
  1743. ]).then(function () {
  1744. this._getProperties();
  1745. }.bind(this));
  1746. },
  1747. close: function PDFDocumentProperties_close() {
  1748. OverlayManager.close(this.overlayName);
  1749. },
  1750. setFileSize: function PDFDocumentProperties_setFileSize(fileSize) {
  1751. if (fileSize > 0) {
  1752. this.rawFileSize = fileSize;
  1753. }
  1754. },
  1755. setDocumentAndUrl: function PDFDocumentProperties_setDocumentAndUrl(pdfDocument, url) {
  1756. this.pdfDocument = pdfDocument;
  1757. this.url = url;
  1758. this.resolveDataAvailable();
  1759. },
  1760. _getProperties: function PDFDocumentProperties_getProperties() {
  1761. if (!OverlayManager.active) {
  1762. return;
  1763. }
  1764. this.pdfDocument.getDownloadInfo().then(function (data) {
  1765. if (data.length === this.rawFileSize) {
  1766. return;
  1767. }
  1768. this.setFileSize(data.length);
  1769. this._updateUI(this.fields['fileSize'], this._parseFileSize());
  1770. }.bind(this));
  1771. this.pdfDocument.getMetadata().then(function (data) {
  1772. var content = {
  1773. 'fileName': getPDFFileNameFromURL(this.url),
  1774. 'fileSize': this._parseFileSize(),
  1775. 'title': data.info.Title,
  1776. 'author': data.info.Author,
  1777. 'subject': data.info.Subject,
  1778. 'keywords': data.info.Keywords,
  1779. 'creationDate': this._parseDate(data.info.CreationDate),
  1780. 'modificationDate': this._parseDate(data.info.ModDate),
  1781. 'creator': data.info.Creator,
  1782. 'producer': data.info.Producer,
  1783. 'version': data.info.PDFFormatVersion,
  1784. 'pageCount': this.pdfDocument.numPages
  1785. };
  1786. for (var identifier in content) {
  1787. this._updateUI(this.fields[identifier], content[identifier]);
  1788. }
  1789. }.bind(this));
  1790. },
  1791. _updateUI: function PDFDocumentProperties_updateUI(field, content) {
  1792. if (field && content !== undefined && content !== '') {
  1793. field.textContent = content;
  1794. }
  1795. },
  1796. _parseFileSize: function PDFDocumentProperties_parseFileSize() {
  1797. var fileSize = this.rawFileSize, kb = fileSize / 1024;
  1798. if (!kb) {
  1799. return;
  1800. } else if (kb < 1024) {
  1801. return mozL10n.get('document_properties_kb', {
  1802. size_kb: (+kb.toPrecision(3)).toLocaleString(),
  1803. size_b: fileSize.toLocaleString()
  1804. }, '{{size_kb}} KB ({{size_b}} bytes)');
  1805. }
  1806. return mozL10n.get('document_properties_mb', {
  1807. size_mb: (+(kb / 1024).toPrecision(3)).toLocaleString(),
  1808. size_b: fileSize.toLocaleString()
  1809. }, '{{size_mb}} MB ({{size_b}} bytes)');
  1810. },
  1811. _parseDate: function PDFDocumentProperties_parseDate(inputDate) {
  1812. var dateToParse = inputDate;
  1813. if (dateToParse === undefined) {
  1814. return '';
  1815. }
  1816. if (dateToParse.substring(0, 2) === 'D:') {
  1817. dateToParse = dateToParse.substring(2);
  1818. }
  1819. var year = parseInt(dateToParse.substring(0, 4), 10);
  1820. var month = parseInt(dateToParse.substring(4, 6), 10) - 1;
  1821. var day = parseInt(dateToParse.substring(6, 8), 10);
  1822. var hours = parseInt(dateToParse.substring(8, 10), 10);
  1823. var minutes = parseInt(dateToParse.substring(10, 12), 10);
  1824. var seconds = parseInt(dateToParse.substring(12, 14), 10);
  1825. var utRel = dateToParse.substring(14, 15);
  1826. var offsetHours = parseInt(dateToParse.substring(15, 17), 10);
  1827. var offsetMinutes = parseInt(dateToParse.substring(18, 20), 10);
  1828. if (utRel === '-') {
  1829. hours += offsetHours;
  1830. minutes += offsetMinutes;
  1831. } else if (utRel === '+') {
  1832. hours -= offsetHours;
  1833. minutes -= offsetMinutes;
  1834. }
  1835. var date = new Date(Date.UTC(year, month, day, hours, minutes, seconds));
  1836. var dateString = date.toLocaleDateString();
  1837. var timeString = date.toLocaleTimeString();
  1838. return mozL10n.get('document_properties_date_string', {
  1839. date: dateString,
  1840. time: timeString
  1841. }, '{{date}}, {{time}}');
  1842. }
  1843. };
  1844. return PDFDocumentProperties;
  1845. }();
  1846. exports.PDFDocumentProperties = PDFDocumentProperties;
  1847. }));
  1848. (function (root, factory) {
  1849. factory(root.pdfjsWebPDFFindController = {}, root.pdfjsWebUIUtils);
  1850. }(this, function (exports, uiUtils) {
  1851. var scrollIntoView = uiUtils.scrollIntoView;
  1852. var FindStates = {
  1853. FIND_FOUND: 0,
  1854. FIND_NOTFOUND: 1,
  1855. FIND_WRAPPED: 2,
  1856. FIND_PENDING: 3
  1857. };
  1858. var FIND_SCROLL_OFFSET_TOP = -50;
  1859. var FIND_SCROLL_OFFSET_LEFT = -400;
  1860. var CHARACTERS_TO_NORMALIZE = {
  1861. '\u2018': '\'',
  1862. '\u2019': '\'',
  1863. '\u201A': '\'',
  1864. '\u201B': '\'',
  1865. '\u201C': '"',
  1866. '\u201D': '"',
  1867. '\u201E': '"',
  1868. '\u201F': '"',
  1869. '\u00BC': '1/4',
  1870. '\u00BD': '1/2',
  1871. '\u00BE': '3/4'
  1872. };
  1873. var PDFFindController = function PDFFindControllerClosure() {
  1874. function PDFFindController(options) {
  1875. this.pdfViewer = options.pdfViewer || null;
  1876. this.onUpdateResultsCount = null;
  1877. this.onUpdateState = null;
  1878. this.reset();
  1879. var replace = Object.keys(CHARACTERS_TO_NORMALIZE).join('');
  1880. this.normalizationRegex = new RegExp('[' + replace + ']', 'g');
  1881. }
  1882. PDFFindController.prototype = {
  1883. reset: function PDFFindController_reset() {
  1884. this.startedTextExtraction = false;
  1885. this.extractTextPromises = [];
  1886. this.pendingFindMatches = Object.create(null);
  1887. this.active = false;
  1888. this.pageContents = [];
  1889. this.pageMatches = [];
  1890. this.pageMatchesLength = null;
  1891. this.matchCount = 0;
  1892. this.selected = {
  1893. pageIdx: -1,
  1894. matchIdx: -1
  1895. };
  1896. this.offset = {
  1897. pageIdx: null,
  1898. matchIdx: null
  1899. };
  1900. this.pagesToSearch = null;
  1901. this.resumePageIdx = null;
  1902. this.state = null;
  1903. this.dirtyMatch = false;
  1904. this.findTimeout = null;
  1905. this.firstPagePromise = new Promise(function (resolve) {
  1906. this.resolveFirstPage = resolve;
  1907. }.bind(this));
  1908. },
  1909. normalize: function PDFFindController_normalize(text) {
  1910. return text.replace(this.normalizationRegex, function (ch) {
  1911. return CHARACTERS_TO_NORMALIZE[ch];
  1912. });
  1913. },
  1914. _prepareMatches: function PDFFindController_prepareMatches(matchesWithLength, matches, matchesLength) {
  1915. function isSubTerm(matchesWithLength, currentIndex) {
  1916. var currentElem, prevElem, nextElem;
  1917. currentElem = matchesWithLength[currentIndex];
  1918. nextElem = matchesWithLength[currentIndex + 1];
  1919. if (currentIndex < matchesWithLength.length - 1 && currentElem.match === nextElem.match) {
  1920. currentElem.skipped = true;
  1921. return true;
  1922. }
  1923. for (var i = currentIndex - 1; i >= 0; i--) {
  1924. prevElem = matchesWithLength[i];
  1925. if (prevElem.skipped) {
  1926. continue;
  1927. }
  1928. if (prevElem.match + prevElem.matchLength < currentElem.match) {
  1929. break;
  1930. }
  1931. if (prevElem.match + prevElem.matchLength >= currentElem.match + currentElem.matchLength) {
  1932. currentElem.skipped = true;
  1933. return true;
  1934. }
  1935. }
  1936. return false;
  1937. }
  1938. var i, len;
  1939. matchesWithLength.sort(function (a, b) {
  1940. return a.match === b.match ? a.matchLength - b.matchLength : a.match - b.match;
  1941. });
  1942. for (i = 0, len = matchesWithLength.length; i < len; i++) {
  1943. if (isSubTerm(matchesWithLength, i)) {
  1944. continue;
  1945. }
  1946. matches.push(matchesWithLength[i].match);
  1947. matchesLength.push(matchesWithLength[i].matchLength);
  1948. }
  1949. },
  1950. calcFindPhraseMatch: function PDFFindController_calcFindPhraseMatch(query, pageIndex, pageContent) {
  1951. var matches = [];
  1952. var queryLen = query.length;
  1953. var matchIdx = -queryLen;
  1954. while (true) {
  1955. matchIdx = pageContent.indexOf(query, matchIdx + queryLen);
  1956. if (matchIdx === -1) {
  1957. break;
  1958. }
  1959. matches.push(matchIdx);
  1960. }
  1961. this.pageMatches[pageIndex] = matches;
  1962. },
  1963. calcFindWordMatch: function PDFFindController_calcFindWordMatch(query, pageIndex, pageContent) {
  1964. var matchesWithLength = [];
  1965. var queryArray = query.match(/\S+/g);
  1966. var subquery, subqueryLen, matchIdx;
  1967. for (var i = 0, len = queryArray.length; i < len; i++) {
  1968. subquery = queryArray[i];
  1969. subqueryLen = subquery.length;
  1970. matchIdx = -subqueryLen;
  1971. while (true) {
  1972. matchIdx = pageContent.indexOf(subquery, matchIdx + subqueryLen);
  1973. if (matchIdx === -1) {
  1974. break;
  1975. }
  1976. matchesWithLength.push({
  1977. match: matchIdx,
  1978. matchLength: subqueryLen,
  1979. skipped: false
  1980. });
  1981. }
  1982. }
  1983. if (!this.pageMatchesLength) {
  1984. this.pageMatchesLength = [];
  1985. }
  1986. this.pageMatchesLength[pageIndex] = [];
  1987. this.pageMatches[pageIndex] = [];
  1988. this._prepareMatches(matchesWithLength, this.pageMatches[pageIndex], this.pageMatchesLength[pageIndex]);
  1989. },
  1990. calcFindMatch: function PDFFindController_calcFindMatch(pageIndex) {
  1991. var pageContent = this.normalize(this.pageContents[pageIndex]);
  1992. var query = this.normalize(this.state.query);
  1993. var caseSensitive = this.state.caseSensitive;
  1994. var phraseSearch = this.state.phraseSearch;
  1995. var queryLen = query.length;
  1996. if (queryLen === 0) {
  1997. return;
  1998. }
  1999. if (!caseSensitive) {
  2000. pageContent = pageContent.toLowerCase();
  2001. query = query.toLowerCase();
  2002. }
  2003. if (phraseSearch) {
  2004. this.calcFindPhraseMatch(query, pageIndex, pageContent);
  2005. } else {
  2006. this.calcFindWordMatch(query, pageIndex, pageContent);
  2007. }
  2008. this.updatePage(pageIndex);
  2009. if (this.resumePageIdx === pageIndex) {
  2010. this.resumePageIdx = null;
  2011. this.nextPageMatch();
  2012. }
  2013. if (this.pageMatches[pageIndex].length > 0) {
  2014. this.matchCount += this.pageMatches[pageIndex].length;
  2015. this.updateUIResultsCount();
  2016. }
  2017. },
  2018. extractText: function PDFFindController_extractText() {
  2019. if (this.startedTextExtraction) {
  2020. return;
  2021. }
  2022. this.startedTextExtraction = true;
  2023. this.pageContents = [];
  2024. var extractTextPromisesResolves = [];
  2025. var numPages = this.pdfViewer.pagesCount;
  2026. for (var i = 0; i < numPages; i++) {
  2027. this.extractTextPromises.push(new Promise(function (resolve) {
  2028. extractTextPromisesResolves.push(resolve);
  2029. }));
  2030. }
  2031. var self = this;
  2032. function extractPageText(pageIndex) {
  2033. self.pdfViewer.getPageTextContent(pageIndex).then(function textContentResolved(textContent) {
  2034. var textItems = textContent.items;
  2035. var str = [];
  2036. for (var i = 0, len = textItems.length; i < len; i++) {
  2037. str.push(textItems[i].str);
  2038. }
  2039. self.pageContents.push(str.join(''));
  2040. extractTextPromisesResolves[pageIndex](pageIndex);
  2041. if (pageIndex + 1 < self.pdfViewer.pagesCount) {
  2042. extractPageText(pageIndex + 1);
  2043. }
  2044. });
  2045. }
  2046. extractPageText(0);
  2047. },
  2048. executeCommand: function PDFFindController_executeCommand(cmd, state) {
  2049. if (this.state === null || cmd !== 'findagain') {
  2050. this.dirtyMatch = true;
  2051. }
  2052. this.state = state;
  2053. this.updateUIState(FindStates.FIND_PENDING);
  2054. this.firstPagePromise.then(function () {
  2055. this.extractText();
  2056. clearTimeout(this.findTimeout);
  2057. if (cmd === 'find') {
  2058. this.findTimeout = setTimeout(this.nextMatch.bind(this), 250);
  2059. } else {
  2060. this.nextMatch();
  2061. }
  2062. }.bind(this));
  2063. },
  2064. updatePage: function PDFFindController_updatePage(index) {
  2065. if (this.selected.pageIdx === index) {
  2066. this.pdfViewer.currentPageNumber = index + 1;
  2067. }
  2068. var page = this.pdfViewer.getPageView(index);
  2069. if (page.textLayer) {
  2070. page.textLayer.updateMatches();
  2071. }
  2072. },
  2073. nextMatch: function PDFFindController_nextMatch() {
  2074. var previous = this.state.findPrevious;
  2075. var currentPageIndex = this.pdfViewer.currentPageNumber - 1;
  2076. var numPages = this.pdfViewer.pagesCount;
  2077. this.active = true;
  2078. if (this.dirtyMatch) {
  2079. this.dirtyMatch = false;
  2080. this.selected.pageIdx = this.selected.matchIdx = -1;
  2081. this.offset.pageIdx = currentPageIndex;
  2082. this.offset.matchIdx = null;
  2083. this.hadMatch = false;
  2084. this.resumePageIdx = null;
  2085. this.pageMatches = [];
  2086. this.matchCount = 0;
  2087. this.pageMatchesLength = null;
  2088. var self = this;
  2089. for (var i = 0; i < numPages; i++) {
  2090. this.updatePage(i);
  2091. if (!(i in this.pendingFindMatches)) {
  2092. this.pendingFindMatches[i] = true;
  2093. this.extractTextPromises[i].then(function (pageIdx) {
  2094. delete self.pendingFindMatches[pageIdx];
  2095. self.calcFindMatch(pageIdx);
  2096. });
  2097. }
  2098. }
  2099. }
  2100. if (this.state.query === '') {
  2101. this.updateUIState(FindStates.FIND_FOUND);
  2102. return;
  2103. }
  2104. if (this.resumePageIdx) {
  2105. return;
  2106. }
  2107. var offset = this.offset;
  2108. this.pagesToSearch = numPages;
  2109. if (offset.matchIdx !== null) {
  2110. var numPageMatches = this.pageMatches[offset.pageIdx].length;
  2111. if (!previous && offset.matchIdx + 1 < numPageMatches || previous && offset.matchIdx > 0) {
  2112. this.hadMatch = true;
  2113. offset.matchIdx = previous ? offset.matchIdx - 1 : offset.matchIdx + 1;
  2114. this.updateMatch(true);
  2115. return;
  2116. }
  2117. this.advanceOffsetPage(previous);
  2118. }
  2119. this.nextPageMatch();
  2120. },
  2121. matchesReady: function PDFFindController_matchesReady(matches) {
  2122. var offset = this.offset;
  2123. var numMatches = matches.length;
  2124. var previous = this.state.findPrevious;
  2125. if (numMatches) {
  2126. this.hadMatch = true;
  2127. offset.matchIdx = previous ? numMatches - 1 : 0;
  2128. this.updateMatch(true);
  2129. return true;
  2130. }
  2131. this.advanceOffsetPage(previous);
  2132. if (offset.wrapped) {
  2133. offset.matchIdx = null;
  2134. if (this.pagesToSearch < 0) {
  2135. this.updateMatch(false);
  2136. return true;
  2137. }
  2138. }
  2139. return false;
  2140. },
  2141. updateMatchPosition: function PDFFindController_updateMatchPosition(pageIndex, index, elements, beginIdx) {
  2142. if (this.selected.matchIdx === index && this.selected.pageIdx === pageIndex) {
  2143. var spot = {
  2144. top: FIND_SCROLL_OFFSET_TOP,
  2145. left: FIND_SCROLL_OFFSET_LEFT
  2146. };
  2147. scrollIntoView(elements[beginIdx], spot, true);
  2148. }
  2149. },
  2150. nextPageMatch: function PDFFindController_nextPageMatch() {
  2151. if (this.resumePageIdx !== null) {
  2152. console.error('There can only be one pending page.');
  2153. }
  2154. do {
  2155. var pageIdx = this.offset.pageIdx;
  2156. var matches = this.pageMatches[pageIdx];
  2157. if (!matches) {
  2158. this.resumePageIdx = pageIdx;
  2159. break;
  2160. }
  2161. } while (!this.matchesReady(matches));
  2162. },
  2163. advanceOffsetPage: function PDFFindController_advanceOffsetPage(previous) {
  2164. var offset = this.offset;
  2165. var numPages = this.extractTextPromises.length;
  2166. offset.pageIdx = previous ? offset.pageIdx - 1 : offset.pageIdx + 1;
  2167. offset.matchIdx = null;
  2168. this.pagesToSearch--;
  2169. if (offset.pageIdx >= numPages || offset.pageIdx < 0) {
  2170. offset.pageIdx = previous ? numPages - 1 : 0;
  2171. offset.wrapped = true;
  2172. }
  2173. },
  2174. updateMatch: function PDFFindController_updateMatch(found) {
  2175. var state = FindStates.FIND_NOTFOUND;
  2176. var wrapped = this.offset.wrapped;
  2177. this.offset.wrapped = false;
  2178. if (found) {
  2179. var previousPage = this.selected.pageIdx;
  2180. this.selected.pageIdx = this.offset.pageIdx;
  2181. this.selected.matchIdx = this.offset.matchIdx;
  2182. state = wrapped ? FindStates.FIND_WRAPPED : FindStates.FIND_FOUND;
  2183. if (previousPage !== -1 && previousPage !== this.selected.pageIdx) {
  2184. this.updatePage(previousPage);
  2185. }
  2186. }
  2187. this.updateUIState(state, this.state.findPrevious);
  2188. if (this.selected.pageIdx !== -1) {
  2189. this.updatePage(this.selected.pageIdx);
  2190. }
  2191. },
  2192. updateUIResultsCount: function PDFFindController_updateUIResultsCount() {
  2193. if (this.onUpdateResultsCount) {
  2194. this.onUpdateResultsCount(this.matchCount);
  2195. }
  2196. },
  2197. updateUIState: function PDFFindController_updateUIState(state, previous) {
  2198. if (this.onUpdateState) {
  2199. this.onUpdateState(state, previous, this.matchCount);
  2200. }
  2201. }
  2202. };
  2203. return PDFFindController;
  2204. }();
  2205. exports.FindStates = FindStates;
  2206. exports.PDFFindController = PDFFindController;
  2207. }));
  2208. (function (root, factory) {
  2209. factory(root.pdfjsWebPDFPresentationMode = {}, root.pdfjsWebUIUtils);
  2210. }(this, function (exports, uiUtils) {
  2211. var normalizeWheelEventDelta = uiUtils.normalizeWheelEventDelta;
  2212. var DELAY_BEFORE_RESETTING_SWITCH_IN_PROGRESS = 1500;
  2213. var DELAY_BEFORE_HIDING_CONTROLS = 3000;
  2214. var ACTIVE_SELECTOR = 'pdfPresentationMode';
  2215. var CONTROLS_SELECTOR = 'pdfPresentationModeControls';
  2216. var PDFPresentationMode = function PDFPresentationModeClosure() {
  2217. function PDFPresentationMode(options) {
  2218. this.container = options.container;
  2219. this.viewer = options.viewer || options.container.firstElementChild;
  2220. this.pdfViewer = options.pdfViewer;
  2221. this.eventBus = options.eventBus;
  2222. var contextMenuItems = options.contextMenuItems || null;
  2223. this.active = false;
  2224. this.args = null;
  2225. this.contextMenuOpen = false;
  2226. this.mouseScrollTimeStamp = 0;
  2227. this.mouseScrollDelta = 0;
  2228. this.touchSwipeState = null;
  2229. if (contextMenuItems) {
  2230. contextMenuItems.contextFirstPage.addEventListener('click', function PDFPresentationMode_contextFirstPageClick(e) {
  2231. this.contextMenuOpen = false;
  2232. this.eventBus.dispatch('firstpage');
  2233. }.bind(this));
  2234. contextMenuItems.contextLastPage.addEventListener('click', function PDFPresentationMode_contextLastPageClick(e) {
  2235. this.contextMenuOpen = false;
  2236. this.eventBus.dispatch('lastpage');
  2237. }.bind(this));
  2238. contextMenuItems.contextPageRotateCw.addEventListener('click', function PDFPresentationMode_contextPageRotateCwClick(e) {
  2239. this.contextMenuOpen = false;
  2240. this.eventBus.dispatch('rotatecw');
  2241. }.bind(this));
  2242. contextMenuItems.contextPageRotateCcw.addEventListener('click', function PDFPresentationMode_contextPageRotateCcwClick(e) {
  2243. this.contextMenuOpen = false;
  2244. this.eventBus.dispatch('rotateccw');
  2245. }.bind(this));
  2246. }
  2247. }
  2248. PDFPresentationMode.prototype = {
  2249. request: function PDFPresentationMode_request() {
  2250. if (this.switchInProgress || this.active || !this.viewer.hasChildNodes()) {
  2251. return false;
  2252. }
  2253. this._addFullscreenChangeListeners();
  2254. this._setSwitchInProgress();
  2255. this._notifyStateChange();
  2256. if (this.container.requestFullscreen) {
  2257. this.container.requestFullscreen();
  2258. } else if (this.container.mozRequestFullScreen) {
  2259. this.container.mozRequestFullScreen();
  2260. } else if (this.container.webkitRequestFullscreen) {
  2261. this.container.webkitRequestFullscreen(Element.ALLOW_KEYBOARD_INPUT);
  2262. } else if (this.container.msRequestFullscreen) {
  2263. this.container.msRequestFullscreen();
  2264. } else {
  2265. return false;
  2266. }
  2267. this.args = {
  2268. page: this.pdfViewer.currentPageNumber,
  2269. previousScale: this.pdfViewer.currentScaleValue
  2270. };
  2271. return true;
  2272. },
  2273. _mouseWheel: function PDFPresentationMode_mouseWheel(evt) {
  2274. if (!this.active) {
  2275. return;
  2276. }
  2277. evt.preventDefault();
  2278. var delta = normalizeWheelEventDelta(evt);
  2279. var MOUSE_SCROLL_COOLDOWN_TIME = 50;
  2280. var PAGE_SWITCH_THRESHOLD = 0.1;
  2281. var currentTime = new Date().getTime();
  2282. var storedTime = this.mouseScrollTimeStamp;
  2283. if (currentTime > storedTime && currentTime - storedTime < MOUSE_SCROLL_COOLDOWN_TIME) {
  2284. return;
  2285. }
  2286. if (this.mouseScrollDelta > 0 && delta < 0 || this.mouseScrollDelta < 0 && delta > 0) {
  2287. this._resetMouseScrollState();
  2288. }
  2289. this.mouseScrollDelta += delta;
  2290. if (Math.abs(this.mouseScrollDelta) >= PAGE_SWITCH_THRESHOLD) {
  2291. var totalDelta = this.mouseScrollDelta;
  2292. this._resetMouseScrollState();
  2293. var success = totalDelta > 0 ? this._goToPreviousPage() : this._goToNextPage();
  2294. if (success) {
  2295. this.mouseScrollTimeStamp = currentTime;
  2296. }
  2297. }
  2298. },
  2299. get isFullscreen() {
  2300. return !!(document.fullscreenElement || document.mozFullScreen || document.webkitIsFullScreen || document.msFullscreenElement);
  2301. },
  2302. _goToPreviousPage: function PDFPresentationMode_goToPreviousPage() {
  2303. var page = this.pdfViewer.currentPageNumber;
  2304. if (page <= 1) {
  2305. return false;
  2306. }
  2307. this.pdfViewer.currentPageNumber = page - 1;
  2308. return true;
  2309. },
  2310. _goToNextPage: function PDFPresentationMode_goToNextPage() {
  2311. var page = this.pdfViewer.currentPageNumber;
  2312. if (page >= this.pdfViewer.pagesCount) {
  2313. return false;
  2314. }
  2315. this.pdfViewer.currentPageNumber = page + 1;
  2316. return true;
  2317. },
  2318. _notifyStateChange: function PDFPresentationMode_notifyStateChange() {
  2319. this.eventBus.dispatch('presentationmodechanged', {
  2320. source: this,
  2321. active: this.active,
  2322. switchInProgress: !!this.switchInProgress
  2323. });
  2324. },
  2325. _setSwitchInProgress: function PDFPresentationMode_setSwitchInProgress() {
  2326. if (this.switchInProgress) {
  2327. clearTimeout(this.switchInProgress);
  2328. }
  2329. this.switchInProgress = setTimeout(function switchInProgressTimeout() {
  2330. this._removeFullscreenChangeListeners();
  2331. delete this.switchInProgress;
  2332. this._notifyStateChange();
  2333. }.bind(this), DELAY_BEFORE_RESETTING_SWITCH_IN_PROGRESS);
  2334. },
  2335. _resetSwitchInProgress: function PDFPresentationMode_resetSwitchInProgress() {
  2336. if (this.switchInProgress) {
  2337. clearTimeout(this.switchInProgress);
  2338. delete this.switchInProgress;
  2339. }
  2340. },
  2341. _enter: function PDFPresentationMode_enter() {
  2342. this.active = true;
  2343. this._resetSwitchInProgress();
  2344. this._notifyStateChange();
  2345. this.container.classList.add(ACTIVE_SELECTOR);
  2346. setTimeout(function enterPresentationModeTimeout() {
  2347. this.pdfViewer.currentPageNumber = this.args.page;
  2348. this.pdfViewer.currentScaleValue = 'page-fit';
  2349. }.bind(this), 0);
  2350. this._addWindowListeners();
  2351. this._showControls();
  2352. this.contextMenuOpen = false;
  2353. this.container.setAttribute('contextmenu', 'viewerContextMenu');
  2354. window.getSelection().removeAllRanges();
  2355. },
  2356. _exit: function PDFPresentationMode_exit() {
  2357. var page = this.pdfViewer.currentPageNumber;
  2358. this.container.classList.remove(ACTIVE_SELECTOR);
  2359. setTimeout(function exitPresentationModeTimeout() {
  2360. this.active = false;
  2361. this._removeFullscreenChangeListeners();
  2362. this._notifyStateChange();
  2363. this.pdfViewer.currentScaleValue = this.args.previousScale;
  2364. this.pdfViewer.currentPageNumber = page;
  2365. this.args = null;
  2366. }.bind(this), 0);
  2367. this._removeWindowListeners();
  2368. this._hideControls();
  2369. this._resetMouseScrollState();
  2370. this.container.removeAttribute('contextmenu');
  2371. this.contextMenuOpen = false;
  2372. },
  2373. _mouseDown: function PDFPresentationMode_mouseDown(evt) {
  2374. if (this.contextMenuOpen) {
  2375. this.contextMenuOpen = false;
  2376. evt.preventDefault();
  2377. return;
  2378. }
  2379. if (evt.button === 0) {
  2380. var isInternalLink = evt.target.href && evt.target.classList.contains('internalLink');
  2381. if (!isInternalLink) {
  2382. evt.preventDefault();
  2383. this.pdfViewer.currentPageNumber += evt.shiftKey ? -1 : 1;
  2384. }
  2385. }
  2386. },
  2387. _contextMenu: function PDFPresentationMode_contextMenu() {
  2388. this.contextMenuOpen = true;
  2389. },
  2390. _showControls: function PDFPresentationMode_showControls() {
  2391. if (this.controlsTimeout) {
  2392. clearTimeout(this.controlsTimeout);
  2393. } else {
  2394. this.container.classList.add(CONTROLS_SELECTOR);
  2395. }
  2396. this.controlsTimeout = setTimeout(function showControlsTimeout() {
  2397. this.container.classList.remove(CONTROLS_SELECTOR);
  2398. delete this.controlsTimeout;
  2399. }.bind(this), DELAY_BEFORE_HIDING_CONTROLS);
  2400. },
  2401. _hideControls: function PDFPresentationMode_hideControls() {
  2402. if (!this.controlsTimeout) {
  2403. return;
  2404. }
  2405. clearTimeout(this.controlsTimeout);
  2406. this.container.classList.remove(CONTROLS_SELECTOR);
  2407. delete this.controlsTimeout;
  2408. },
  2409. _resetMouseScrollState: function PDFPresentationMode_resetMouseScrollState() {
  2410. this.mouseScrollTimeStamp = 0;
  2411. this.mouseScrollDelta = 0;
  2412. },
  2413. _touchSwipe: function PDFPresentationMode_touchSwipe(evt) {
  2414. if (!this.active) {
  2415. return;
  2416. }
  2417. var SWIPE_MIN_DISTANCE_THRESHOLD = 50;
  2418. var SWIPE_ANGLE_THRESHOLD = Math.PI / 6;
  2419. if (evt.touches.length > 1) {
  2420. this.touchSwipeState = null;
  2421. return;
  2422. }
  2423. switch (evt.type) {
  2424. case 'touchstart':
  2425. this.touchSwipeState = {
  2426. startX: evt.touches[0].pageX,
  2427. startY: evt.touches[0].pageY,
  2428. endX: evt.touches[0].pageX,
  2429. endY: evt.touches[0].pageY
  2430. };
  2431. break;
  2432. case 'touchmove':
  2433. if (this.touchSwipeState === null) {
  2434. return;
  2435. }
  2436. this.touchSwipeState.endX = evt.touches[0].pageX;
  2437. this.touchSwipeState.endY = evt.touches[0].pageY;
  2438. evt.preventDefault();
  2439. break;
  2440. case 'touchend':
  2441. if (this.touchSwipeState === null) {
  2442. return;
  2443. }
  2444. var delta = 0;
  2445. var dx = this.touchSwipeState.endX - this.touchSwipeState.startX;
  2446. var dy = this.touchSwipeState.endY - this.touchSwipeState.startY;
  2447. var absAngle = Math.abs(Math.atan2(dy, dx));
  2448. if (Math.abs(dx) > SWIPE_MIN_DISTANCE_THRESHOLD && (absAngle <= SWIPE_ANGLE_THRESHOLD || absAngle >= Math.PI - SWIPE_ANGLE_THRESHOLD)) {
  2449. delta = dx;
  2450. } else if (Math.abs(dy) > SWIPE_MIN_DISTANCE_THRESHOLD && Math.abs(absAngle - Math.PI / 2) <= SWIPE_ANGLE_THRESHOLD) {
  2451. delta = dy;
  2452. }
  2453. if (delta > 0) {
  2454. this._goToPreviousPage();
  2455. } else if (delta < 0) {
  2456. this._goToNextPage();
  2457. }
  2458. break;
  2459. }
  2460. },
  2461. _addWindowListeners: function PDFPresentationMode_addWindowListeners() {
  2462. this.showControlsBind = this._showControls.bind(this);
  2463. this.mouseDownBind = this._mouseDown.bind(this);
  2464. this.mouseWheelBind = this._mouseWheel.bind(this);
  2465. this.resetMouseScrollStateBind = this._resetMouseScrollState.bind(this);
  2466. this.contextMenuBind = this._contextMenu.bind(this);
  2467. this.touchSwipeBind = this._touchSwipe.bind(this);
  2468. window.addEventListener('mousemove', this.showControlsBind);
  2469. window.addEventListener('mousedown', this.mouseDownBind);
  2470. window.addEventListener('wheel', this.mouseWheelBind);
  2471. window.addEventListener('keydown', this.resetMouseScrollStateBind);
  2472. window.addEventListener('contextmenu', this.contextMenuBind);
  2473. window.addEventListener('touchstart', this.touchSwipeBind);
  2474. window.addEventListener('touchmove', this.touchSwipeBind);
  2475. window.addEventListener('touchend', this.touchSwipeBind);
  2476. },
  2477. _removeWindowListeners: function PDFPresentationMode_removeWindowListeners() {
  2478. window.removeEventListener('mousemove', this.showControlsBind);
  2479. window.removeEventListener('mousedown', this.mouseDownBind);
  2480. window.removeEventListener('wheel', this.mouseWheelBind);
  2481. window.removeEventListener('keydown', this.resetMouseScrollStateBind);
  2482. window.removeEventListener('contextmenu', this.contextMenuBind);
  2483. window.removeEventListener('touchstart', this.touchSwipeBind);
  2484. window.removeEventListener('touchmove', this.touchSwipeBind);
  2485. window.removeEventListener('touchend', this.touchSwipeBind);
  2486. delete this.showControlsBind;
  2487. delete this.mouseDownBind;
  2488. delete this.mouseWheelBind;
  2489. delete this.resetMouseScrollStateBind;
  2490. delete this.contextMenuBind;
  2491. delete this.touchSwipeBind;
  2492. },
  2493. _fullscreenChange: function PDFPresentationMode_fullscreenChange() {
  2494. if (this.isFullscreen) {
  2495. this._enter();
  2496. } else {
  2497. this._exit();
  2498. }
  2499. },
  2500. _addFullscreenChangeListeners: function PDFPresentationMode_addFullscreenChangeListeners() {
  2501. this.fullscreenChangeBind = this._fullscreenChange.bind(this);
  2502. window.addEventListener('fullscreenchange', this.fullscreenChangeBind);
  2503. window.addEventListener('mozfullscreenchange', this.fullscreenChangeBind);
  2504. window.addEventListener('webkitfullscreenchange', this.fullscreenChangeBind);
  2505. window.addEventListener('MSFullscreenChange', this.fullscreenChangeBind);
  2506. },
  2507. _removeFullscreenChangeListeners: function PDFPresentationMode_removeFullscreenChangeListeners() {
  2508. window.removeEventListener('fullscreenchange', this.fullscreenChangeBind);
  2509. window.removeEventListener('mozfullscreenchange', this.fullscreenChangeBind);
  2510. window.removeEventListener('webkitfullscreenchange', this.fullscreenChangeBind);
  2511. window.removeEventListener('MSFullscreenChange', this.fullscreenChangeBind);
  2512. delete this.fullscreenChangeBind;
  2513. }
  2514. };
  2515. return PDFPresentationMode;
  2516. }();
  2517. exports.PDFPresentationMode = PDFPresentationMode;
  2518. }));
  2519. (function (root, factory) {
  2520. factory(root.pdfjsWebPDFThumbnailView = {}, root.pdfjsWebUIUtils, root.pdfjsWebPDFRenderingQueue);
  2521. }(this, function (exports, uiUtils, pdfRenderingQueue) {
  2522. var mozL10n = uiUtils.mozL10n;
  2523. var getOutputScale = uiUtils.getOutputScale;
  2524. var RenderingStates = pdfRenderingQueue.RenderingStates;
  2525. var THUMBNAIL_WIDTH = 98;
  2526. var THUMBNAIL_CANVAS_BORDER_WIDTH = 1;
  2527. var PDFThumbnailView = function PDFThumbnailViewClosure() {
  2528. function getTempCanvas(width, height) {
  2529. var tempCanvas = PDFThumbnailView.tempImageCache;
  2530. if (!tempCanvas) {
  2531. tempCanvas = document.createElement('canvas');
  2532. PDFThumbnailView.tempImageCache = tempCanvas;
  2533. }
  2534. tempCanvas.width = width;
  2535. tempCanvas.height = height;
  2536. tempCanvas.mozOpaque = true;
  2537. var ctx = tempCanvas.getContext('2d', { alpha: false });
  2538. ctx.save();
  2539. ctx.fillStyle = 'rgb(255, 255, 255)';
  2540. ctx.fillRect(0, 0, width, height);
  2541. ctx.restore();
  2542. return tempCanvas;
  2543. }
  2544. function PDFThumbnailView(options) {
  2545. var container = options.container;
  2546. var id = options.id;
  2547. var defaultViewport = options.defaultViewport;
  2548. var linkService = options.linkService;
  2549. var renderingQueue = options.renderingQueue;
  2550. var disableCanvasToImageConversion = options.disableCanvasToImageConversion || false;
  2551. this.id = id;
  2552. this.renderingId = 'thumbnail' + id;
  2553. this.pageLabel = null;
  2554. this.pdfPage = null;
  2555. this.rotation = 0;
  2556. this.viewport = defaultViewport;
  2557. this.pdfPageRotate = defaultViewport.rotation;
  2558. this.linkService = linkService;
  2559. this.renderingQueue = renderingQueue;
  2560. this.renderTask = null;
  2561. this.renderingState = RenderingStates.INITIAL;
  2562. this.resume = null;
  2563. this.disableCanvasToImageConversion = disableCanvasToImageConversion;
  2564. this.pageWidth = this.viewport.width;
  2565. this.pageHeight = this.viewport.height;
  2566. this.pageRatio = this.pageWidth / this.pageHeight;
  2567. this.canvasWidth = THUMBNAIL_WIDTH;
  2568. this.canvasHeight = this.canvasWidth / this.pageRatio | 0;
  2569. this.scale = this.canvasWidth / this.pageWidth;
  2570. var anchor = document.createElement('a');
  2571. anchor.href = linkService.getAnchorUrl('#page=' + id);
  2572. anchor.title = mozL10n.get('thumb_page_title', { page: id }, 'Page {{page}}');
  2573. anchor.onclick = function stopNavigation() {
  2574. linkService.page = id;
  2575. return false;
  2576. };
  2577. this.anchor = anchor;
  2578. var div = document.createElement('div');
  2579. div.className = 'thumbnail';
  2580. div.setAttribute('data-page-number', this.id);
  2581. this.div = div;
  2582. if (id === 1) {
  2583. div.classList.add('selected');
  2584. }
  2585. var ring = document.createElement('div');
  2586. ring.className = 'thumbnailSelectionRing';
  2587. var borderAdjustment = 2 * THUMBNAIL_CANVAS_BORDER_WIDTH;
  2588. ring.style.width = this.canvasWidth + borderAdjustment + 'px';
  2589. ring.style.height = this.canvasHeight + borderAdjustment + 'px';
  2590. this.ring = ring;
  2591. div.appendChild(ring);
  2592. anchor.appendChild(div);
  2593. container.appendChild(anchor);
  2594. }
  2595. PDFThumbnailView.prototype = {
  2596. setPdfPage: function PDFThumbnailView_setPdfPage(pdfPage) {
  2597. this.pdfPage = pdfPage;
  2598. this.pdfPageRotate = pdfPage.rotate;
  2599. var totalRotation = (this.rotation + this.pdfPageRotate) % 360;
  2600. this.viewport = pdfPage.getViewport(1, totalRotation);
  2601. this.reset();
  2602. },
  2603. reset: function PDFThumbnailView_reset() {
  2604. this.cancelRendering();
  2605. this.pageWidth = this.viewport.width;
  2606. this.pageHeight = this.viewport.height;
  2607. this.pageRatio = this.pageWidth / this.pageHeight;
  2608. this.canvasHeight = this.canvasWidth / this.pageRatio | 0;
  2609. this.scale = this.canvasWidth / this.pageWidth;
  2610. this.div.removeAttribute('data-loaded');
  2611. var ring = this.ring;
  2612. var childNodes = ring.childNodes;
  2613. for (var i = childNodes.length - 1; i >= 0; i--) {
  2614. ring.removeChild(childNodes[i]);
  2615. }
  2616. var borderAdjustment = 2 * THUMBNAIL_CANVAS_BORDER_WIDTH;
  2617. ring.style.width = this.canvasWidth + borderAdjustment + 'px';
  2618. ring.style.height = this.canvasHeight + borderAdjustment + 'px';
  2619. if (this.canvas) {
  2620. this.canvas.width = 0;
  2621. this.canvas.height = 0;
  2622. delete this.canvas;
  2623. }
  2624. if (this.image) {
  2625. this.image.removeAttribute('src');
  2626. delete this.image;
  2627. }
  2628. },
  2629. update: function PDFThumbnailView_update(rotation) {
  2630. if (typeof rotation !== 'undefined') {
  2631. this.rotation = rotation;
  2632. }
  2633. var totalRotation = (this.rotation + this.pdfPageRotate) % 360;
  2634. this.viewport = this.viewport.clone({
  2635. scale: 1,
  2636. rotation: totalRotation
  2637. });
  2638. this.reset();
  2639. },
  2640. cancelRendering: function PDFThumbnailView_cancelRendering() {
  2641. if (this.renderTask) {
  2642. this.renderTask.cancel();
  2643. this.renderTask = null;
  2644. }
  2645. this.renderingState = RenderingStates.INITIAL;
  2646. this.resume = null;
  2647. },
  2648. _getPageDrawContext: function PDFThumbnailView_getPageDrawContext(noCtxScale) {
  2649. var canvas = document.createElement('canvas');
  2650. this.canvas = canvas;
  2651. canvas.mozOpaque = true;
  2652. var ctx = canvas.getContext('2d', { alpha: false });
  2653. var outputScale = getOutputScale(ctx);
  2654. canvas.width = this.canvasWidth * outputScale.sx | 0;
  2655. canvas.height = this.canvasHeight * outputScale.sy | 0;
  2656. canvas.style.width = this.canvasWidth + 'px';
  2657. canvas.style.height = this.canvasHeight + 'px';
  2658. if (!noCtxScale && outputScale.scaled) {
  2659. ctx.scale(outputScale.sx, outputScale.sy);
  2660. }
  2661. return ctx;
  2662. },
  2663. _convertCanvasToImage: function PDFThumbnailView_convertCanvasToImage() {
  2664. if (!this.canvas) {
  2665. return;
  2666. }
  2667. if (this.renderingState !== RenderingStates.FINISHED) {
  2668. return;
  2669. }
  2670. var id = this.renderingId;
  2671. var className = 'thumbnailImage';
  2672. var ariaLabel = mozL10n.get('thumb_page_canvas', { page: this.pageId }, 'Thumbnail of Page {{page}}');
  2673. if (this.disableCanvasToImageConversion) {
  2674. this.canvas.id = id;
  2675. this.canvas.className = className;
  2676. this.canvas.setAttribute('aria-label', ariaLabel);
  2677. this.div.setAttribute('data-loaded', true);
  2678. this.ring.appendChild(this.canvas);
  2679. return;
  2680. }
  2681. var image = document.createElement('img');
  2682. image.id = id;
  2683. image.className = className;
  2684. image.setAttribute('aria-label', ariaLabel);
  2685. image.style.width = this.canvasWidth + 'px';
  2686. image.style.height = this.canvasHeight + 'px';
  2687. image.src = this.canvas.toDataURL();
  2688. this.image = image;
  2689. this.div.setAttribute('data-loaded', true);
  2690. this.ring.appendChild(image);
  2691. this.canvas.width = 0;
  2692. this.canvas.height = 0;
  2693. delete this.canvas;
  2694. },
  2695. draw: function PDFThumbnailView_draw() {
  2696. if (this.renderingState !== RenderingStates.INITIAL) {
  2697. console.error('Must be in new state before drawing');
  2698. return Promise.resolve(undefined);
  2699. }
  2700. this.renderingState = RenderingStates.RUNNING;
  2701. var resolveRenderPromise, rejectRenderPromise;
  2702. var promise = new Promise(function (resolve, reject) {
  2703. resolveRenderPromise = resolve;
  2704. rejectRenderPromise = reject;
  2705. });
  2706. var self = this;
  2707. function thumbnailDrawCallback(error) {
  2708. if (renderTask === self.renderTask) {
  2709. self.renderTask = null;
  2710. }
  2711. if (error === 'cancelled') {
  2712. rejectRenderPromise(error);
  2713. return;
  2714. }
  2715. self.renderingState = RenderingStates.FINISHED;
  2716. self._convertCanvasToImage();
  2717. if (!error) {
  2718. resolveRenderPromise(undefined);
  2719. } else {
  2720. rejectRenderPromise(error);
  2721. }
  2722. }
  2723. var ctx = this._getPageDrawContext();
  2724. var drawViewport = this.viewport.clone({ scale: this.scale });
  2725. var renderContinueCallback = function renderContinueCallback(cont) {
  2726. if (!self.renderingQueue.isHighestPriority(self)) {
  2727. self.renderingState = RenderingStates.PAUSED;
  2728. self.resume = function resumeCallback() {
  2729. self.renderingState = RenderingStates.RUNNING;
  2730. cont();
  2731. };
  2732. return;
  2733. }
  2734. cont();
  2735. };
  2736. var renderContext = {
  2737. canvasContext: ctx,
  2738. viewport: drawViewport
  2739. };
  2740. var renderTask = this.renderTask = this.pdfPage.render(renderContext);
  2741. renderTask.onContinue = renderContinueCallback;
  2742. renderTask.promise.then(function pdfPageRenderCallback() {
  2743. thumbnailDrawCallback(null);
  2744. }, function pdfPageRenderError(error) {
  2745. thumbnailDrawCallback(error);
  2746. });
  2747. return promise;
  2748. },
  2749. setImage: function PDFThumbnailView_setImage(pageView) {
  2750. if (this.renderingState !== RenderingStates.INITIAL) {
  2751. return;
  2752. }
  2753. var img = pageView.canvas;
  2754. if (!img) {
  2755. return;
  2756. }
  2757. if (!this.pdfPage) {
  2758. this.setPdfPage(pageView.pdfPage);
  2759. }
  2760. this.renderingState = RenderingStates.FINISHED;
  2761. var ctx = this._getPageDrawContext(true);
  2762. var canvas = ctx.canvas;
  2763. if (img.width <= 2 * canvas.width) {
  2764. ctx.drawImage(img, 0, 0, img.width, img.height, 0, 0, canvas.width, canvas.height);
  2765. this._convertCanvasToImage();
  2766. return;
  2767. }
  2768. var MAX_NUM_SCALING_STEPS = 3;
  2769. var reducedWidth = canvas.width << MAX_NUM_SCALING_STEPS;
  2770. var reducedHeight = canvas.height << MAX_NUM_SCALING_STEPS;
  2771. var reducedImage = getTempCanvas(reducedWidth, reducedHeight);
  2772. var reducedImageCtx = reducedImage.getContext('2d');
  2773. while (reducedWidth > img.width || reducedHeight > img.height) {
  2774. reducedWidth >>= 1;
  2775. reducedHeight >>= 1;
  2776. }
  2777. reducedImageCtx.drawImage(img, 0, 0, img.width, img.height, 0, 0, reducedWidth, reducedHeight);
  2778. while (reducedWidth > 2 * canvas.width) {
  2779. reducedImageCtx.drawImage(reducedImage, 0, 0, reducedWidth, reducedHeight, 0, 0, reducedWidth >> 1, reducedHeight >> 1);
  2780. reducedWidth >>= 1;
  2781. reducedHeight >>= 1;
  2782. }
  2783. ctx.drawImage(reducedImage, 0, 0, reducedWidth, reducedHeight, 0, 0, canvas.width, canvas.height);
  2784. this._convertCanvasToImage();
  2785. },
  2786. get pageId() {
  2787. return this.pageLabel !== null ? this.pageLabel : this.id;
  2788. },
  2789. setPageLabel: function PDFThumbnailView_setPageLabel(label) {
  2790. this.pageLabel = typeof label === 'string' ? label : null;
  2791. this.anchor.title = mozL10n.get('thumb_page_title', { page: this.pageId }, 'Page {{page}}');
  2792. if (this.renderingState !== RenderingStates.FINISHED) {
  2793. return;
  2794. }
  2795. var ariaLabel = mozL10n.get('thumb_page_canvas', { page: this.pageId }, 'Thumbnail of Page {{page}}');
  2796. if (this.image) {
  2797. this.image.setAttribute('aria-label', ariaLabel);
  2798. } else if (this.disableCanvasToImageConversion && this.canvas) {
  2799. this.canvas.setAttribute('aria-label', ariaLabel);
  2800. }
  2801. }
  2802. };
  2803. return PDFThumbnailView;
  2804. }();
  2805. PDFThumbnailView.tempImageCache = null;
  2806. exports.PDFThumbnailView = PDFThumbnailView;
  2807. }));
  2808. (function (root, factory) {
  2809. factory(root.pdfjsWebSecondaryToolbar = {}, root.pdfjsWebUIUtils);
  2810. }(this, function (exports, uiUtils) {
  2811. var SCROLLBAR_PADDING = uiUtils.SCROLLBAR_PADDING;
  2812. var mozL10n = uiUtils.mozL10n;
  2813. var SecondaryToolbar = function SecondaryToolbarClosure() {
  2814. function SecondaryToolbar(options, mainContainer, eventBus) {
  2815. this.toolbar = options.toolbar;
  2816. this.toggleButton = options.toggleButton;
  2817. this.toolbarButtonContainer = options.toolbarButtonContainer;
  2818. this.buttons = [
  2819. {
  2820. element: options.presentationModeButton,
  2821. eventName: 'presentationmode',
  2822. close: true
  2823. },
  2824. {
  2825. element: options.openFileButton,
  2826. eventName: 'openfile',
  2827. close: true
  2828. },
  2829. {
  2830. element: options.printButton,
  2831. eventName: 'print',
  2832. close: true
  2833. },
  2834. {
  2835. element: options.downloadButton,
  2836. eventName: 'download',
  2837. close: true
  2838. },
  2839. {
  2840. element: options.viewBookmarkButton,
  2841. eventName: null,
  2842. close: true
  2843. },
  2844. {
  2845. element: options.firstPageButton,
  2846. eventName: 'firstpage',
  2847. close: true
  2848. },
  2849. {
  2850. element: options.lastPageButton,
  2851. eventName: 'lastpage',
  2852. close: true
  2853. },
  2854. {
  2855. element: options.pageRotateCwButton,
  2856. eventName: 'rotatecw',
  2857. close: false
  2858. },
  2859. {
  2860. element: options.pageRotateCcwButton,
  2861. eventName: 'rotateccw',
  2862. close: false
  2863. },
  2864. {
  2865. element: options.toggleHandToolButton,
  2866. eventName: 'togglehandtool',
  2867. close: true
  2868. },
  2869. {
  2870. element: options.documentPropertiesButton,
  2871. eventName: 'documentproperties',
  2872. close: true
  2873. }
  2874. ];
  2875. this.items = {
  2876. firstPage: options.firstPageButton,
  2877. lastPage: options.lastPageButton,
  2878. pageRotateCw: options.pageRotateCwButton,
  2879. pageRotateCcw: options.pageRotateCcwButton
  2880. };
  2881. this.mainContainer = mainContainer;
  2882. this.eventBus = eventBus;
  2883. this.opened = false;
  2884. this.containerHeight = null;
  2885. this.previousContainerHeight = null;
  2886. this.reset();
  2887. this._bindClickListeners();
  2888. this._bindHandToolListener(options.toggleHandToolButton);
  2889. this.eventBus.on('resize', this._setMaxHeight.bind(this));
  2890. }
  2891. SecondaryToolbar.prototype = {
  2892. get isOpen() {
  2893. return this.opened;
  2894. },
  2895. setPageNumber: function SecondaryToolbar_setPageNumber(pageNumber) {
  2896. this.pageNumber = pageNumber;
  2897. this._updateUIState();
  2898. },
  2899. setPagesCount: function SecondaryToolbar_setPagesCount(pagesCount) {
  2900. this.pagesCount = pagesCount;
  2901. this._updateUIState();
  2902. },
  2903. reset: function SecondaryToolbar_reset() {
  2904. this.pageNumber = 0;
  2905. this.pagesCount = 0;
  2906. this._updateUIState();
  2907. },
  2908. _updateUIState: function SecondaryToolbar_updateUIState() {
  2909. var items = this.items;
  2910. items.firstPage.disabled = this.pageNumber <= 1;
  2911. items.lastPage.disabled = this.pageNumber >= this.pagesCount;
  2912. items.pageRotateCw.disabled = this.pagesCount === 0;
  2913. items.pageRotateCcw.disabled = this.pagesCount === 0;
  2914. },
  2915. _bindClickListeners: function SecondaryToolbar_bindClickListeners() {
  2916. this.toggleButton.addEventListener('click', this.toggle.bind(this));
  2917. for (var button in this.buttons) {
  2918. var element = this.buttons[button].element;
  2919. var eventName = this.buttons[button].eventName;
  2920. var close = this.buttons[button].close;
  2921. element.addEventListener('click', function (eventName, close) {
  2922. if (eventName !== null) {
  2923. this.eventBus.dispatch(eventName, { source: this });
  2924. }
  2925. if (close) {
  2926. this.close();
  2927. }
  2928. }.bind(this, eventName, close));
  2929. }
  2930. },
  2931. _bindHandToolListener: function SecondaryToolbar_bindHandToolListener(toggleHandToolButton) {
  2932. var isHandToolActive = false;
  2933. this.eventBus.on('handtoolchanged', function (e) {
  2934. if (isHandToolActive === e.isActive) {
  2935. return;
  2936. }
  2937. isHandToolActive = e.isActive;
  2938. if (isHandToolActive) {
  2939. toggleHandToolButton.title = mozL10n.get('hand_tool_disable.title', null, 'Disable hand tool');
  2940. toggleHandToolButton.firstElementChild.textContent = mozL10n.get('hand_tool_disable_label', null, 'Disable hand tool');
  2941. } else {
  2942. toggleHandToolButton.title = mozL10n.get('hand_tool_enable.title', null, 'Enable hand tool');
  2943. toggleHandToolButton.firstElementChild.textContent = mozL10n.get('hand_tool_enable_label', null, 'Enable hand tool');
  2944. }
  2945. });
  2946. },
  2947. open: function SecondaryToolbar_open() {
  2948. if (this.opened) {
  2949. return;
  2950. }
  2951. this.opened = true;
  2952. this._setMaxHeight();
  2953. this.toggleButton.classList.add('toggled');
  2954. this.toolbar.classList.remove('hidden');
  2955. },
  2956. close: function SecondaryToolbar_close() {
  2957. if (!this.opened) {
  2958. return;
  2959. }
  2960. this.opened = false;
  2961. this.toolbar.classList.add('hidden');
  2962. this.toggleButton.classList.remove('toggled');
  2963. },
  2964. toggle: function SecondaryToolbar_toggle() {
  2965. if (this.opened) {
  2966. this.close();
  2967. } else {
  2968. this.open();
  2969. }
  2970. },
  2971. _setMaxHeight: function SecondaryToolbar_setMaxHeight() {
  2972. if (!this.opened) {
  2973. return;
  2974. }
  2975. this.containerHeight = this.mainContainer.clientHeight;
  2976. if (this.containerHeight === this.previousContainerHeight) {
  2977. return;
  2978. }
  2979. this.toolbarButtonContainer.setAttribute('style', 'max-height: ' + (this.containerHeight - SCROLLBAR_PADDING) + 'px;');
  2980. this.previousContainerHeight = this.containerHeight;
  2981. }
  2982. };
  2983. return SecondaryToolbar;
  2984. }();
  2985. exports.SecondaryToolbar = SecondaryToolbar;
  2986. }));
  2987. (function (root, factory) {
  2988. factory(root.pdfjsWebToolbar = {}, root.pdfjsWebUIUtils);
  2989. }(this, function (exports, uiUtils) {
  2990. var mozL10n = uiUtils.mozL10n;
  2991. var noContextMenuHandler = uiUtils.noContextMenuHandler;
  2992. var animationStarted = uiUtils.animationStarted;
  2993. var localized = uiUtils.localized;
  2994. var DEFAULT_SCALE_VALUE = uiUtils.DEFAULT_SCALE_VALUE;
  2995. var DEFAULT_SCALE = uiUtils.DEFAULT_SCALE;
  2996. var MIN_SCALE = uiUtils.MIN_SCALE;
  2997. var MAX_SCALE = uiUtils.MAX_SCALE;
  2998. var PAGE_NUMBER_LOADING_INDICATOR = 'visiblePageIsLoading';
  2999. var SCALE_SELECT_CONTAINER_PADDING = 8;
  3000. var SCALE_SELECT_PADDING = 22;
  3001. var Toolbar = function ToolbarClosure() {
  3002. function Toolbar(options, mainContainer, eventBus) {
  3003. this.toolbar = options.container;
  3004. this.mainContainer = mainContainer;
  3005. this.eventBus = eventBus;
  3006. this.items = options;
  3007. this._wasLocalized = false;
  3008. this.reset();
  3009. this._bindListeners();
  3010. }
  3011. Toolbar.prototype = {
  3012. setPageNumber: function (pageNumber, pageLabel) {
  3013. this.pageNumber = pageNumber;
  3014. this.pageLabel = pageLabel;
  3015. this._updateUIState(false);
  3016. },
  3017. setPagesCount: function (pagesCount, hasPageLabels) {
  3018. this.pagesCount = pagesCount;
  3019. this.hasPageLabels = hasPageLabels;
  3020. this._updateUIState(true);
  3021. },
  3022. setPageScale: function (pageScaleValue, pageScale) {
  3023. this.pageScaleValue = pageScaleValue;
  3024. this.pageScale = pageScale;
  3025. this._updateUIState(false);
  3026. },
  3027. reset: function () {
  3028. this.pageNumber = 0;
  3029. this.pageLabel = null;
  3030. this.hasPageLabels = false;
  3031. this.pagesCount = 0;
  3032. this.pageScaleValue = DEFAULT_SCALE_VALUE;
  3033. this.pageScale = DEFAULT_SCALE;
  3034. this._updateUIState(true);
  3035. },
  3036. _bindListeners: function Toolbar_bindClickListeners() {
  3037. var eventBus = this.eventBus;
  3038. var self = this;
  3039. var items = this.items;
  3040. items.previous.addEventListener('click', function () {
  3041. eventBus.dispatch('previouspage');
  3042. });
  3043. items.next.addEventListener('click', function () {
  3044. eventBus.dispatch('nextpage');
  3045. });
  3046. items.zoomIn.addEventListener('click', function () {
  3047. eventBus.dispatch('zoomin');
  3048. });
  3049. items.zoomOut.addEventListener('click', function () {
  3050. eventBus.dispatch('zoomout');
  3051. });
  3052. items.pageNumber.addEventListener('click', function () {
  3053. this.select();
  3054. });
  3055. items.pageNumber.addEventListener('change', function () {
  3056. eventBus.dispatch('pagenumberchanged', {
  3057. source: self,
  3058. value: this.value
  3059. });
  3060. });
  3061. items.scaleSelect.addEventListener('change', function () {
  3062. if (this.value === 'custom') {
  3063. return;
  3064. }
  3065. eventBus.dispatch('scalechanged', {
  3066. source: self,
  3067. value: this.value
  3068. });
  3069. });
  3070. items.presentationModeButton.addEventListener('click', function (e) {
  3071. eventBus.dispatch('presentationmode');
  3072. });
  3073. items.openFile.addEventListener('click', function (e) {
  3074. eventBus.dispatch('openfile');
  3075. });
  3076. items.print.addEventListener('click', function (e) {
  3077. eventBus.dispatch('print');
  3078. });
  3079. items.download.addEventListener('click', function (e) {
  3080. eventBus.dispatch('download');
  3081. });
  3082. items.scaleSelect.oncontextmenu = noContextMenuHandler;
  3083. localized.then(this._localized.bind(this));
  3084. },
  3085. _localized: function Toolbar_localized() {
  3086. this._wasLocalized = true;
  3087. this._adjustScaleWidth();
  3088. this._updateUIState(true);
  3089. },
  3090. _updateUIState: function Toolbar_updateUIState(resetNumPages) {
  3091. function selectScaleOption(value, scale) {
  3092. var options = items.scaleSelect.options;
  3093. var predefinedValueFound = false;
  3094. for (var i = 0, ii = options.length; i < ii; i++) {
  3095. var option = options[i];
  3096. if (option.value !== value) {
  3097. option.selected = false;
  3098. continue;
  3099. }
  3100. option.selected = true;
  3101. predefinedValueFound = true;
  3102. }
  3103. if (!predefinedValueFound) {
  3104. var customScale = Math.round(scale * 10000) / 100;
  3105. items.customScaleOption.textContent = mozL10n.get('page_scale_percent', { scale: customScale }, '{{scale}}%');
  3106. items.customScaleOption.selected = true;
  3107. }
  3108. }
  3109. if (!this._wasLocalized) {
  3110. return;
  3111. }
  3112. var pageNumber = this.pageNumber;
  3113. var scaleValue = (this.pageScaleValue || this.pageScale).toString();
  3114. var scale = this.pageScale;
  3115. var items = this.items;
  3116. var pagesCount = this.pagesCount;
  3117. if (resetNumPages) {
  3118. if (this.hasPageLabels) {
  3119. items.pageNumber.type = 'text';
  3120. } else {
  3121. items.pageNumber.type = 'number';
  3122. items.numPages.textContent = mozL10n.get('of_pages', { pagesCount: pagesCount }, 'of {{pagesCount}}');
  3123. }
  3124. items.pageNumber.max = pagesCount;
  3125. }
  3126. if (this.hasPageLabels) {
  3127. items.pageNumber.value = this.pageLabel;
  3128. items.numPages.textContent = mozL10n.get('page_of_pages', {
  3129. pageNumber: pageNumber,
  3130. pagesCount: pagesCount
  3131. }, '({{pageNumber}} of {{pagesCount}})');
  3132. } else {
  3133. items.pageNumber.value = pageNumber;
  3134. }
  3135. items.previous.disabled = pageNumber <= 1;
  3136. items.next.disabled = pageNumber >= pagesCount;
  3137. items.zoomOut.disabled = scale <= MIN_SCALE;
  3138. items.zoomIn.disabled = scale >= MAX_SCALE;
  3139. selectScaleOption(scaleValue, scale);
  3140. },
  3141. updateLoadingIndicatorState: function Toolbar_updateLoadingIndicatorState(loading) {
  3142. var pageNumberInput = this.items.pageNumber;
  3143. if (loading) {
  3144. pageNumberInput.classList.add(PAGE_NUMBER_LOADING_INDICATOR);
  3145. } else {
  3146. pageNumberInput.classList.remove(PAGE_NUMBER_LOADING_INDICATOR);
  3147. }
  3148. },
  3149. _adjustScaleWidth: function Toolbar_adjustScaleWidth() {
  3150. var container = this.items.scaleSelectContainer;
  3151. var select = this.items.scaleSelect;
  3152. animationStarted.then(function () {
  3153. if (container.clientWidth === 0) {
  3154. container.setAttribute('style', 'display: inherit;');
  3155. }
  3156. if (container.clientWidth > 0) {
  3157. select.setAttribute('style', 'min-width: inherit;');
  3158. var width = select.clientWidth + SCALE_SELECT_CONTAINER_PADDING;
  3159. select.setAttribute('style', 'min-width: ' + (width + SCALE_SELECT_PADDING) + 'px;');
  3160. container.setAttribute('style', 'min-width: ' + width + 'px; ' + 'max-width: ' + width + 'px;');
  3161. }
  3162. });
  3163. }
  3164. };
  3165. return Toolbar;
  3166. }();
  3167. exports.Toolbar = Toolbar;
  3168. }));
  3169. (function (root, factory) {
  3170. factory(root.pdfjsWebPDFFindBar = {}, root.pdfjsWebUIUtils, root.pdfjsWebPDFFindController);
  3171. }(this, function (exports, uiUtils, pdfFindController) {
  3172. var mozL10n = uiUtils.mozL10n;
  3173. var FindStates = pdfFindController.FindStates;
  3174. var PDFFindBar = function PDFFindBarClosure() {
  3175. function PDFFindBar(options) {
  3176. this.opened = false;
  3177. this.bar = options.bar || null;
  3178. this.toggleButton = options.toggleButton || null;
  3179. this.findField = options.findField || null;
  3180. this.highlightAll = options.highlightAllCheckbox || null;
  3181. this.caseSensitive = options.caseSensitiveCheckbox || null;
  3182. this.findMsg = options.findMsg || null;
  3183. this.findResultsCount = options.findResultsCount || null;
  3184. this.findStatusIcon = options.findStatusIcon || null;
  3185. this.findPreviousButton = options.findPreviousButton || null;
  3186. this.findNextButton = options.findNextButton || null;
  3187. this.findController = options.findController || null;
  3188. this.eventBus = options.eventBus;
  3189. if (this.findController === null) {
  3190. throw new Error('PDFFindBar cannot be used without a ' + 'PDFFindController instance.');
  3191. }
  3192. var self = this;
  3193. this.toggleButton.addEventListener('click', function () {
  3194. self.toggle();
  3195. });
  3196. this.findField.addEventListener('input', function () {
  3197. self.dispatchEvent('');
  3198. });
  3199. this.bar.addEventListener('keydown', function (evt) {
  3200. switch (evt.keyCode) {
  3201. case 13:
  3202. if (evt.target === self.findField) {
  3203. self.dispatchEvent('again', evt.shiftKey);
  3204. }
  3205. break;
  3206. case 27:
  3207. self.close();
  3208. break;
  3209. }
  3210. });
  3211. this.findPreviousButton.addEventListener('click', function () {
  3212. self.dispatchEvent('again', true);
  3213. });
  3214. this.findNextButton.addEventListener('click', function () {
  3215. self.dispatchEvent('again', false);
  3216. });
  3217. this.highlightAll.addEventListener('click', function () {
  3218. self.dispatchEvent('highlightallchange');
  3219. });
  3220. this.caseSensitive.addEventListener('click', function () {
  3221. self.dispatchEvent('casesensitivitychange');
  3222. });
  3223. }
  3224. PDFFindBar.prototype = {
  3225. reset: function PDFFindBar_reset() {
  3226. this.updateUIState();
  3227. },
  3228. dispatchEvent: function PDFFindBar_dispatchEvent(type, findPrev) {
  3229. this.eventBus.dispatch('find', {
  3230. source: this,
  3231. type: type,
  3232. query: this.findField.value,
  3233. caseSensitive: this.caseSensitive.checked,
  3234. phraseSearch: true,
  3235. highlightAll: this.highlightAll.checked,
  3236. findPrevious: findPrev
  3237. });
  3238. },
  3239. updateUIState: function PDFFindBar_updateUIState(state, previous, matchCount) {
  3240. var notFound = false;
  3241. var findMsg = '';
  3242. var status = '';
  3243. switch (state) {
  3244. case FindStates.FIND_FOUND:
  3245. break;
  3246. case FindStates.FIND_PENDING:
  3247. status = 'pending';
  3248. break;
  3249. case FindStates.FIND_NOTFOUND:
  3250. findMsg = mozL10n.get('find_not_found', null, 'Phrase not found');
  3251. notFound = true;
  3252. break;
  3253. case FindStates.FIND_WRAPPED:
  3254. if (previous) {
  3255. findMsg = mozL10n.get('find_reached_top', null, 'Reached top of document, continued from bottom');
  3256. } else {
  3257. findMsg = mozL10n.get('find_reached_bottom', null, 'Reached end of document, continued from top');
  3258. }
  3259. break;
  3260. }
  3261. if (notFound) {
  3262. this.findField.classList.add('notFound');
  3263. } else {
  3264. this.findField.classList.remove('notFound');
  3265. }
  3266. this.findField.setAttribute('data-status', status);
  3267. this.findMsg.textContent = findMsg;
  3268. this.updateResultsCount(matchCount);
  3269. },
  3270. updateResultsCount: function (matchCount) {
  3271. if (!this.findResultsCount) {
  3272. return;
  3273. }
  3274. if (!matchCount) {
  3275. this.findResultsCount.classList.add('hidden');
  3276. return;
  3277. }
  3278. this.findResultsCount.textContent = matchCount.toLocaleString();
  3279. this.findResultsCount.classList.remove('hidden');
  3280. },
  3281. open: function PDFFindBar_open() {
  3282. if (!this.opened) {
  3283. this.opened = true;
  3284. this.toggleButton.classList.add('toggled');
  3285. this.bar.classList.remove('hidden');
  3286. }
  3287. this.findField.select();
  3288. this.findField.focus();
  3289. },
  3290. close: function PDFFindBar_close() {
  3291. if (!this.opened) {
  3292. return;
  3293. }
  3294. this.opened = false;
  3295. this.toggleButton.classList.remove('toggled');
  3296. this.bar.classList.add('hidden');
  3297. this.findController.active = false;
  3298. },
  3299. toggle: function PDFFindBar_toggle() {
  3300. if (this.opened) {
  3301. this.close();
  3302. } else {
  3303. this.open();
  3304. }
  3305. }
  3306. };
  3307. return PDFFindBar;
  3308. }();
  3309. exports.PDFFindBar = PDFFindBar;
  3310. }));
  3311. (function (root, factory) {
  3312. factory(root.pdfjsWebPDFHistory = {}, root.pdfjsWebDOMEvents);
  3313. }(this, function (exports, domEvents) {
  3314. function PDFHistory(options) {
  3315. this.linkService = options.linkService;
  3316. this.eventBus = options.eventBus || domEvents.getGlobalEventBus();
  3317. this.initialized = false;
  3318. this.initialDestination = null;
  3319. this.initialBookmark = null;
  3320. }
  3321. PDFHistory.prototype = {
  3322. initialize: function pdfHistoryInitialize(fingerprint) {
  3323. this.initialized = true;
  3324. this.reInitialized = false;
  3325. this.allowHashChange = true;
  3326. this.historyUnlocked = true;
  3327. this.isViewerInPresentationMode = false;
  3328. this.previousHash = window.location.hash.substring(1);
  3329. this.currentBookmark = '';
  3330. this.currentPage = 0;
  3331. this.updatePreviousBookmark = false;
  3332. this.previousBookmark = '';
  3333. this.previousPage = 0;
  3334. this.nextHashParam = '';
  3335. this.fingerprint = fingerprint;
  3336. this.currentUid = this.uid = 0;
  3337. this.current = {};
  3338. var state = window.history.state;
  3339. if (this._isStateObjectDefined(state)) {
  3340. if (state.target.dest) {
  3341. this.initialDestination = state.target.dest;
  3342. } else {
  3343. this.initialBookmark = state.target.hash;
  3344. }
  3345. this.currentUid = state.uid;
  3346. this.uid = state.uid + 1;
  3347. this.current = state.target;
  3348. } else {
  3349. if (state && state.fingerprint && this.fingerprint !== state.fingerprint) {
  3350. this.reInitialized = true;
  3351. }
  3352. this._pushOrReplaceState({ fingerprint: this.fingerprint }, true);
  3353. }
  3354. var self = this;
  3355. window.addEventListener('popstate', function pdfHistoryPopstate(evt) {
  3356. if (!self.historyUnlocked) {
  3357. return;
  3358. }
  3359. if (evt.state) {
  3360. self._goTo(evt.state);
  3361. return;
  3362. }
  3363. if (self.uid === 0) {
  3364. var previousParams = self.previousHash && self.currentBookmark && self.previousHash !== self.currentBookmark ? {
  3365. hash: self.currentBookmark,
  3366. page: self.currentPage
  3367. } : { page: 1 };
  3368. replacePreviousHistoryState(previousParams, function () {
  3369. updateHistoryWithCurrentHash();
  3370. });
  3371. } else {
  3372. updateHistoryWithCurrentHash();
  3373. }
  3374. });
  3375. function updateHistoryWithCurrentHash() {
  3376. self.previousHash = window.location.hash.slice(1);
  3377. self._pushToHistory({ hash: self.previousHash }, false, true);
  3378. self._updatePreviousBookmark();
  3379. }
  3380. function replacePreviousHistoryState(params, callback) {
  3381. self.historyUnlocked = false;
  3382. self.allowHashChange = false;
  3383. window.addEventListener('popstate', rewriteHistoryAfterBack);
  3384. history.back();
  3385. function rewriteHistoryAfterBack() {
  3386. window.removeEventListener('popstate', rewriteHistoryAfterBack);
  3387. window.addEventListener('popstate', rewriteHistoryAfterForward);
  3388. self._pushToHistory(params, false, true);
  3389. history.forward();
  3390. }
  3391. function rewriteHistoryAfterForward() {
  3392. window.removeEventListener('popstate', rewriteHistoryAfterForward);
  3393. self.allowHashChange = true;
  3394. self.historyUnlocked = true;
  3395. callback();
  3396. }
  3397. }
  3398. function pdfHistoryBeforeUnload() {
  3399. var previousParams = self._getPreviousParams(null, true);
  3400. if (previousParams) {
  3401. var replacePrevious = !self.current.dest && self.current.hash !== self.previousHash;
  3402. self._pushToHistory(previousParams, false, replacePrevious);
  3403. self._updatePreviousBookmark();
  3404. }
  3405. window.removeEventListener('beforeunload', pdfHistoryBeforeUnload);
  3406. }
  3407. window.addEventListener('beforeunload', pdfHistoryBeforeUnload);
  3408. window.addEventListener('pageshow', function pdfHistoryPageShow(evt) {
  3409. window.addEventListener('beforeunload', pdfHistoryBeforeUnload);
  3410. });
  3411. self.eventBus.on('presentationmodechanged', function (e) {
  3412. self.isViewerInPresentationMode = e.active;
  3413. });
  3414. },
  3415. clearHistoryState: function pdfHistory_clearHistoryState() {
  3416. this._pushOrReplaceState(null, true);
  3417. },
  3418. _isStateObjectDefined: function pdfHistory_isStateObjectDefined(state) {
  3419. return state && state.uid >= 0 && state.fingerprint && this.fingerprint === state.fingerprint && state.target && state.target.hash ? true : false;
  3420. },
  3421. _pushOrReplaceState: function pdfHistory_pushOrReplaceState(stateObj, replace) {
  3422. if (replace) {
  3423. window.history.replaceState(stateObj, '', document.URL);
  3424. } else {
  3425. window.history.pushState(stateObj, '', document.URL);
  3426. }
  3427. },
  3428. get isHashChangeUnlocked() {
  3429. if (!this.initialized) {
  3430. return true;
  3431. }
  3432. return this.allowHashChange;
  3433. },
  3434. _updatePreviousBookmark: function pdfHistory_updatePreviousBookmark() {
  3435. if (this.updatePreviousBookmark && this.currentBookmark && this.currentPage) {
  3436. this.previousBookmark = this.currentBookmark;
  3437. this.previousPage = this.currentPage;
  3438. this.updatePreviousBookmark = false;
  3439. }
  3440. },
  3441. updateCurrentBookmark: function pdfHistoryUpdateCurrentBookmark(bookmark, pageNum) {
  3442. if (this.initialized) {
  3443. this.currentBookmark = bookmark.substring(1);
  3444. this.currentPage = pageNum | 0;
  3445. this._updatePreviousBookmark();
  3446. }
  3447. },
  3448. updateNextHashParam: function pdfHistoryUpdateNextHashParam(param) {
  3449. if (this.initialized) {
  3450. this.nextHashParam = param;
  3451. }
  3452. },
  3453. push: function pdfHistoryPush(params, isInitialBookmark) {
  3454. if (!(this.initialized && this.historyUnlocked)) {
  3455. return;
  3456. }
  3457. if (params.dest && !params.hash) {
  3458. params.hash = this.current.hash && this.current.dest && this.current.dest === params.dest ? this.current.hash : this.linkService.getDestinationHash(params.dest).split('#')[1];
  3459. }
  3460. if (params.page) {
  3461. params.page |= 0;
  3462. }
  3463. if (isInitialBookmark) {
  3464. var target = window.history.state.target;
  3465. if (!target) {
  3466. this._pushToHistory(params, false);
  3467. this.previousHash = window.location.hash.substring(1);
  3468. }
  3469. this.updatePreviousBookmark = this.nextHashParam ? false : true;
  3470. if (target) {
  3471. this._updatePreviousBookmark();
  3472. }
  3473. return;
  3474. }
  3475. if (this.nextHashParam) {
  3476. if (this.nextHashParam === params.hash) {
  3477. this.nextHashParam = null;
  3478. this.updatePreviousBookmark = true;
  3479. return;
  3480. }
  3481. this.nextHashParam = null;
  3482. }
  3483. if (params.hash) {
  3484. if (this.current.hash) {
  3485. if (this.current.hash !== params.hash) {
  3486. this._pushToHistory(params, true);
  3487. } else {
  3488. if (!this.current.page && params.page) {
  3489. this._pushToHistory(params, false, true);
  3490. }
  3491. this.updatePreviousBookmark = true;
  3492. }
  3493. } else {
  3494. this._pushToHistory(params, true);
  3495. }
  3496. } else if (this.current.page && params.page && this.current.page !== params.page) {
  3497. this._pushToHistory(params, true);
  3498. }
  3499. },
  3500. _getPreviousParams: function pdfHistory_getPreviousParams(onlyCheckPage, beforeUnload) {
  3501. if (!(this.currentBookmark && this.currentPage)) {
  3502. return null;
  3503. } else if (this.updatePreviousBookmark) {
  3504. this.updatePreviousBookmark = false;
  3505. }
  3506. if (this.uid > 0 && !(this.previousBookmark && this.previousPage)) {
  3507. return null;
  3508. }
  3509. if (!this.current.dest && !onlyCheckPage || beforeUnload) {
  3510. if (this.previousBookmark === this.currentBookmark) {
  3511. return null;
  3512. }
  3513. } else if (this.current.page || onlyCheckPage) {
  3514. if (this.previousPage === this.currentPage) {
  3515. return null;
  3516. }
  3517. } else {
  3518. return null;
  3519. }
  3520. var params = {
  3521. hash: this.currentBookmark,
  3522. page: this.currentPage
  3523. };
  3524. if (this.isViewerInPresentationMode) {
  3525. params.hash = null;
  3526. }
  3527. return params;
  3528. },
  3529. _stateObj: function pdfHistory_stateObj(params) {
  3530. return {
  3531. fingerprint: this.fingerprint,
  3532. uid: this.uid,
  3533. target: params
  3534. };
  3535. },
  3536. _pushToHistory: function pdfHistory_pushToHistory(params, addPrevious, overwrite) {
  3537. if (!this.initialized) {
  3538. return;
  3539. }
  3540. if (!params.hash && params.page) {
  3541. params.hash = 'page=' + params.page;
  3542. }
  3543. if (addPrevious && !overwrite) {
  3544. var previousParams = this._getPreviousParams();
  3545. if (previousParams) {
  3546. var replacePrevious = !this.current.dest && this.current.hash !== this.previousHash;
  3547. this._pushToHistory(previousParams, false, replacePrevious);
  3548. }
  3549. }
  3550. this._pushOrReplaceState(this._stateObj(params), overwrite || this.uid === 0);
  3551. this.currentUid = this.uid++;
  3552. this.current = params;
  3553. this.updatePreviousBookmark = true;
  3554. },
  3555. _goTo: function pdfHistory_goTo(state) {
  3556. if (!(this.initialized && this.historyUnlocked && this._isStateObjectDefined(state))) {
  3557. return;
  3558. }
  3559. if (!this.reInitialized && state.uid < this.currentUid) {
  3560. var previousParams = this._getPreviousParams(true);
  3561. if (previousParams) {
  3562. this._pushToHistory(this.current, false);
  3563. this._pushToHistory(previousParams, false);
  3564. this.currentUid = state.uid;
  3565. window.history.back();
  3566. return;
  3567. }
  3568. }
  3569. this.historyUnlocked = false;
  3570. if (state.target.dest) {
  3571. this.linkService.navigateTo(state.target.dest);
  3572. } else {
  3573. this.linkService.setHash(state.target.hash);
  3574. }
  3575. this.currentUid = state.uid;
  3576. if (state.uid > this.uid) {
  3577. this.uid = state.uid;
  3578. }
  3579. this.current = state.target;
  3580. this.updatePreviousBookmark = true;
  3581. var currentHash = window.location.hash.substring(1);
  3582. if (this.previousHash !== currentHash) {
  3583. this.allowHashChange = false;
  3584. }
  3585. this.previousHash = currentHash;
  3586. this.historyUnlocked = true;
  3587. },
  3588. back: function pdfHistoryBack() {
  3589. this.go(-1);
  3590. },
  3591. forward: function pdfHistoryForward() {
  3592. this.go(1);
  3593. },
  3594. go: function pdfHistoryGo(direction) {
  3595. if (this.initialized && this.historyUnlocked) {
  3596. var state = window.history.state;
  3597. if (direction === -1 && state && state.uid > 0) {
  3598. window.history.back();
  3599. } else if (direction === 1 && state && state.uid < this.uid - 1) {
  3600. window.history.forward();
  3601. }
  3602. }
  3603. }
  3604. };
  3605. exports.PDFHistory = PDFHistory;
  3606. }));
  3607. (function (root, factory) {
  3608. factory(root.pdfjsWebPDFLinkService = {}, root.pdfjsWebUIUtils, root.pdfjsWebDOMEvents);
  3609. }(this, function (exports, uiUtils, domEvents) {
  3610. var parseQueryString = uiUtils.parseQueryString;
  3611. var PageNumberRegExp = /^\d+$/;
  3612. function isPageNumber(str) {
  3613. return PageNumberRegExp.test(str);
  3614. }
  3615. var PDFLinkService = function PDFLinkServiceClosure() {
  3616. function PDFLinkService(options) {
  3617. options = options || {};
  3618. this.eventBus = options.eventBus || domEvents.getGlobalEventBus();
  3619. this.baseUrl = null;
  3620. this.pdfDocument = null;
  3621. this.pdfViewer = null;
  3622. this.pdfHistory = null;
  3623. this._pagesRefCache = null;
  3624. }
  3625. PDFLinkService.prototype = {
  3626. setDocument: function PDFLinkService_setDocument(pdfDocument, baseUrl) {
  3627. this.baseUrl = baseUrl;
  3628. this.pdfDocument = pdfDocument;
  3629. this._pagesRefCache = Object.create(null);
  3630. },
  3631. setViewer: function PDFLinkService_setViewer(pdfViewer) {
  3632. this.pdfViewer = pdfViewer;
  3633. },
  3634. setHistory: function PDFLinkService_setHistory(pdfHistory) {
  3635. this.pdfHistory = pdfHistory;
  3636. },
  3637. get pagesCount() {
  3638. return this.pdfDocument ? this.pdfDocument.numPages : 0;
  3639. },
  3640. get page() {
  3641. return this.pdfViewer.currentPageNumber;
  3642. },
  3643. set page(value) {
  3644. this.pdfViewer.currentPageNumber = value;
  3645. },
  3646. navigateTo: function PDFLinkService_navigateTo(dest) {
  3647. var destString = '';
  3648. var self = this;
  3649. var goToDestination = function (destRef) {
  3650. var pageNumber;
  3651. if (destRef instanceof Object) {
  3652. pageNumber = self._cachedPageNumber(destRef);
  3653. } else if ((destRef | 0) === destRef) {
  3654. pageNumber = destRef + 1;
  3655. } else {
  3656. console.error('PDFLinkService_navigateTo: "' + destRef + '" is not a valid destination reference.');
  3657. return;
  3658. }
  3659. if (pageNumber) {
  3660. if (pageNumber < 1 || pageNumber > self.pagesCount) {
  3661. console.error('PDFLinkService_navigateTo: "' + pageNumber + '" is a non-existent page number.');
  3662. return;
  3663. }
  3664. self.pdfViewer.scrollPageIntoView({
  3665. pageNumber: pageNumber,
  3666. destArray: dest
  3667. });
  3668. if (self.pdfHistory) {
  3669. self.pdfHistory.push({
  3670. dest: dest,
  3671. hash: destString,
  3672. page: pageNumber
  3673. });
  3674. }
  3675. } else {
  3676. self.pdfDocument.getPageIndex(destRef).then(function (pageIndex) {
  3677. self.cachePageRef(pageIndex + 1, destRef);
  3678. goToDestination(destRef);
  3679. }).catch(function () {
  3680. console.error('PDFLinkService_navigateTo: "' + destRef + '" is not a valid page reference.');
  3681. });
  3682. }
  3683. };
  3684. var destinationPromise;
  3685. if (typeof dest === 'string') {
  3686. destString = dest;
  3687. destinationPromise = this.pdfDocument.getDestination(dest);
  3688. } else {
  3689. destinationPromise = Promise.resolve(dest);
  3690. }
  3691. destinationPromise.then(function (destination) {
  3692. dest = destination;
  3693. if (!(destination instanceof Array)) {
  3694. console.error('PDFLinkService_navigateTo: "' + destination + '" is not a valid destination array.');
  3695. return;
  3696. }
  3697. goToDestination(destination[0]);
  3698. });
  3699. },
  3700. getDestinationHash: function PDFLinkService_getDestinationHash(dest) {
  3701. if (typeof dest === 'string') {
  3702. return this.getAnchorUrl('#' + (isPageNumber(dest) ? 'nameddest=' : '') + escape(dest));
  3703. }
  3704. if (dest instanceof Array) {
  3705. var str = JSON.stringify(dest);
  3706. return this.getAnchorUrl('#' + escape(str));
  3707. }
  3708. return this.getAnchorUrl('');
  3709. },
  3710. getAnchorUrl: function PDFLinkService_getAnchorUrl(anchor) {
  3711. return (this.baseUrl || '') + anchor;
  3712. },
  3713. setHash: function PDFLinkService_setHash(hash) {
  3714. var pageNumber, dest;
  3715. if (hash.indexOf('=') >= 0) {
  3716. var params = parseQueryString(hash);
  3717. if ('search' in params) {
  3718. this.eventBus.dispatch('findfromurlhash', {
  3719. source: this,
  3720. query: params['search'].replace(/"/g, ''),
  3721. phraseSearch: params['phrase'] === 'true'
  3722. });
  3723. }
  3724. if ('nameddest' in params) {
  3725. if (this.pdfHistory) {
  3726. this.pdfHistory.updateNextHashParam(params.nameddest);
  3727. }
  3728. this.navigateTo(params.nameddest);
  3729. return;
  3730. }
  3731. if ('page' in params) {
  3732. pageNumber = params.page | 0 || 1;
  3733. }
  3734. if ('zoom' in params) {
  3735. var zoomArgs = params.zoom.split(',');
  3736. var zoomArg = zoomArgs[0];
  3737. var zoomArgNumber = parseFloat(zoomArg);
  3738. if (zoomArg.indexOf('Fit') === -1) {
  3739. dest = [
  3740. null,
  3741. { name: 'XYZ' },
  3742. zoomArgs.length > 1 ? zoomArgs[1] | 0 : null,
  3743. zoomArgs.length > 2 ? zoomArgs[2] | 0 : null,
  3744. zoomArgNumber ? zoomArgNumber / 100 : zoomArg
  3745. ];
  3746. } else {
  3747. if (zoomArg === 'Fit' || zoomArg === 'FitB') {
  3748. dest = [
  3749. null,
  3750. { name: zoomArg }
  3751. ];
  3752. } else if (zoomArg === 'FitH' || zoomArg === 'FitBH' || (zoomArg === 'FitV' || zoomArg === 'FitBV')) {
  3753. dest = [
  3754. null,
  3755. { name: zoomArg },
  3756. zoomArgs.length > 1 ? zoomArgs[1] | 0 : null
  3757. ];
  3758. } else if (zoomArg === 'FitR') {
  3759. if (zoomArgs.length !== 5) {
  3760. console.error('PDFLinkService_setHash: ' + 'Not enough parameters for \'FitR\'.');
  3761. } else {
  3762. dest = [
  3763. null,
  3764. { name: zoomArg },
  3765. zoomArgs[1] | 0,
  3766. zoomArgs[2] | 0,
  3767. zoomArgs[3] | 0,
  3768. zoomArgs[4] | 0
  3769. ];
  3770. }
  3771. } else {
  3772. console.error('PDFLinkService_setHash: \'' + zoomArg + '\' is not a valid zoom value.');
  3773. }
  3774. }
  3775. }
  3776. if (dest) {
  3777. this.pdfViewer.scrollPageIntoView({
  3778. pageNumber: pageNumber || this.page,
  3779. destArray: dest,
  3780. allowNegativeOffset: true
  3781. });
  3782. } else if (pageNumber) {
  3783. this.page = pageNumber;
  3784. }
  3785. if ('pagemode' in params) {
  3786. this.eventBus.dispatch('pagemode', {
  3787. source: this,
  3788. mode: params.pagemode
  3789. });
  3790. }
  3791. } else {
  3792. if (isPageNumber(hash) && hash <= this.pagesCount) {
  3793. console.warn('PDFLinkService_setHash: specifying a page number ' + 'directly after the hash symbol (#) is deprecated, ' + 'please use the "#page=' + hash + '" form instead.');
  3794. this.page = hash | 0;
  3795. }
  3796. dest = unescape(hash);
  3797. try {
  3798. dest = JSON.parse(dest);
  3799. if (!(dest instanceof Array)) {
  3800. dest = dest.toString();
  3801. }
  3802. } catch (ex) {
  3803. }
  3804. if (typeof dest === 'string' || isValidExplicitDestination(dest)) {
  3805. if (this.pdfHistory) {
  3806. this.pdfHistory.updateNextHashParam(dest);
  3807. }
  3808. this.navigateTo(dest);
  3809. return;
  3810. }
  3811. console.error('PDFLinkService_setHash: \'' + unescape(hash) + '\' is not a valid destination.');
  3812. }
  3813. },
  3814. executeNamedAction: function PDFLinkService_executeNamedAction(action) {
  3815. switch (action) {
  3816. case 'GoBack':
  3817. if (this.pdfHistory) {
  3818. this.pdfHistory.back();
  3819. }
  3820. break;
  3821. case 'GoForward':
  3822. if (this.pdfHistory) {
  3823. this.pdfHistory.forward();
  3824. }
  3825. break;
  3826. case 'NextPage':
  3827. if (this.page < this.pagesCount) {
  3828. this.page++;
  3829. }
  3830. break;
  3831. case 'PrevPage':
  3832. if (this.page > 1) {
  3833. this.page--;
  3834. }
  3835. break;
  3836. case 'LastPage':
  3837. this.page = this.pagesCount;
  3838. break;
  3839. case 'FirstPage':
  3840. this.page = 1;
  3841. break;
  3842. default:
  3843. break;
  3844. }
  3845. this.eventBus.dispatch('namedaction', {
  3846. source: this,
  3847. action: action
  3848. });
  3849. },
  3850. cachePageRef: function PDFLinkService_cachePageRef(pageNum, pageRef) {
  3851. var refStr = pageRef.num + ' ' + pageRef.gen + ' R';
  3852. this._pagesRefCache[refStr] = pageNum;
  3853. },
  3854. _cachedPageNumber: function PDFLinkService_cachedPageNumber(pageRef) {
  3855. var refStr = pageRef.num + ' ' + pageRef.gen + ' R';
  3856. return this._pagesRefCache && this._pagesRefCache[refStr] || null;
  3857. }
  3858. };
  3859. function isValidExplicitDestination(dest) {
  3860. if (!(dest instanceof Array)) {
  3861. return false;
  3862. }
  3863. var destLength = dest.length, allowNull = true;
  3864. if (destLength < 2) {
  3865. return false;
  3866. }
  3867. var page = dest[0];
  3868. if (!(typeof page === 'object' && typeof page.num === 'number' && (page.num | 0) === page.num && typeof page.gen === 'number' && (page.gen | 0) === page.gen) && !(typeof page === 'number' && (page | 0) === page && page >= 0)) {
  3869. return false;
  3870. }
  3871. var zoom = dest[1];
  3872. if (!(typeof zoom === 'object' && typeof zoom.name === 'string')) {
  3873. return false;
  3874. }
  3875. switch (zoom.name) {
  3876. case 'XYZ':
  3877. if (destLength !== 5) {
  3878. return false;
  3879. }
  3880. break;
  3881. case 'Fit':
  3882. case 'FitB':
  3883. return destLength === 2;
  3884. case 'FitH':
  3885. case 'FitBH':
  3886. case 'FitV':
  3887. case 'FitBV':
  3888. if (destLength !== 3) {
  3889. return false;
  3890. }
  3891. break;
  3892. case 'FitR':
  3893. if (destLength !== 6) {
  3894. return false;
  3895. }
  3896. allowNull = false;
  3897. break;
  3898. default:
  3899. return false;
  3900. }
  3901. for (var i = 2; i < destLength; i++) {
  3902. var param = dest[i];
  3903. if (!(typeof param === 'number' || allowNull && param === null)) {
  3904. return false;
  3905. }
  3906. }
  3907. return true;
  3908. }
  3909. return PDFLinkService;
  3910. }();
  3911. var SimpleLinkService = function SimpleLinkServiceClosure() {
  3912. function SimpleLinkService() {
  3913. }
  3914. SimpleLinkService.prototype = {
  3915. get page() {
  3916. return 0;
  3917. },
  3918. set page(value) {
  3919. },
  3920. navigateTo: function (dest) {
  3921. },
  3922. getDestinationHash: function (dest) {
  3923. return '#';
  3924. },
  3925. getAnchorUrl: function (hash) {
  3926. return '#';
  3927. },
  3928. setHash: function (hash) {
  3929. },
  3930. executeNamedAction: function (action) {
  3931. },
  3932. cachePageRef: function (pageNum, pageRef) {
  3933. }
  3934. };
  3935. return SimpleLinkService;
  3936. }();
  3937. exports.PDFLinkService = PDFLinkService;
  3938. exports.SimpleLinkService = SimpleLinkService;
  3939. }));
  3940. (function (root, factory) {
  3941. factory(root.pdfjsWebPDFPageView = {}, root.pdfjsWebUIUtils, root.pdfjsWebPDFRenderingQueue, root.pdfjsWebDOMEvents, root.pdfjsWebPDFJS);
  3942. }(this, function (exports, uiUtils, pdfRenderingQueue, domEvents, pdfjsLib) {
  3943. var CSS_UNITS = uiUtils.CSS_UNITS;
  3944. var DEFAULT_SCALE = uiUtils.DEFAULT_SCALE;
  3945. var getOutputScale = uiUtils.getOutputScale;
  3946. var approximateFraction = uiUtils.approximateFraction;
  3947. var roundToDivide = uiUtils.roundToDivide;
  3948. var RendererType = uiUtils.RendererType;
  3949. var RenderingStates = pdfRenderingQueue.RenderingStates;
  3950. var TEXT_LAYER_RENDER_DELAY = 200;
  3951. var PDFPageView = function PDFPageViewClosure() {
  3952. function PDFPageView(options) {
  3953. var container = options.container;
  3954. var id = options.id;
  3955. var scale = options.scale;
  3956. var defaultViewport = options.defaultViewport;
  3957. var renderingQueue = options.renderingQueue;
  3958. var textLayerFactory = options.textLayerFactory;
  3959. var annotationLayerFactory = options.annotationLayerFactory;
  3960. var enhanceTextSelection = options.enhanceTextSelection || false;
  3961. var renderInteractiveForms = options.renderInteractiveForms || false;
  3962. this.id = id;
  3963. this.renderingId = 'page' + id;
  3964. this.pageLabel = null;
  3965. this.rotation = 0;
  3966. this.scale = scale || DEFAULT_SCALE;
  3967. this.viewport = defaultViewport;
  3968. this.pdfPageRotate = defaultViewport.rotation;
  3969. this.hasRestrictedScaling = false;
  3970. this.enhanceTextSelection = enhanceTextSelection;
  3971. this.renderInteractiveForms = renderInteractiveForms;
  3972. this.eventBus = options.eventBus || domEvents.getGlobalEventBus();
  3973. this.renderingQueue = renderingQueue;
  3974. this.textLayerFactory = textLayerFactory;
  3975. this.annotationLayerFactory = annotationLayerFactory;
  3976. this.renderer = options.renderer || RendererType.CANVAS;
  3977. this.paintTask = null;
  3978. this.paintedViewportMap = new WeakMap();
  3979. this.renderingState = RenderingStates.INITIAL;
  3980. this.resume = null;
  3981. this.error = null;
  3982. this.onBeforeDraw = null;
  3983. this.onAfterDraw = null;
  3984. this.textLayer = null;
  3985. this.zoomLayer = null;
  3986. this.annotationLayer = null;
  3987. var div = document.createElement('div');
  3988. div.className = 'page';
  3989. div.style.width = Math.floor(this.viewport.width) + 'px';
  3990. div.style.height = Math.floor(this.viewport.height) + 'px';
  3991. div.setAttribute('data-page-number', this.id);
  3992. this.div = div;
  3993. container.appendChild(div);
  3994. }
  3995. PDFPageView.prototype = {
  3996. setPdfPage: function PDFPageView_setPdfPage(pdfPage) {
  3997. this.pdfPage = pdfPage;
  3998. this.pdfPageRotate = pdfPage.rotate;
  3999. var totalRotation = (this.rotation + this.pdfPageRotate) % 360;
  4000. this.viewport = pdfPage.getViewport(this.scale * CSS_UNITS, totalRotation);
  4001. this.stats = pdfPage.stats;
  4002. this.reset();
  4003. },
  4004. destroy: function PDFPageView_destroy() {
  4005. this.zoomLayer = null;
  4006. this.reset();
  4007. if (this.pdfPage) {
  4008. this.pdfPage.cleanup();
  4009. }
  4010. },
  4011. reset: function PDFPageView_reset(keepZoomLayer, keepAnnotations) {
  4012. this.cancelRendering();
  4013. var div = this.div;
  4014. div.style.width = Math.floor(this.viewport.width) + 'px';
  4015. div.style.height = Math.floor(this.viewport.height) + 'px';
  4016. var childNodes = div.childNodes;
  4017. var currentZoomLayerNode = keepZoomLayer && this.zoomLayer || null;
  4018. var currentAnnotationNode = keepAnnotations && this.annotationLayer && this.annotationLayer.div || null;
  4019. for (var i = childNodes.length - 1; i >= 0; i--) {
  4020. var node = childNodes[i];
  4021. if (currentZoomLayerNode === node || currentAnnotationNode === node) {
  4022. continue;
  4023. }
  4024. div.removeChild(node);
  4025. }
  4026. div.removeAttribute('data-loaded');
  4027. if (currentAnnotationNode) {
  4028. this.annotationLayer.hide();
  4029. } else {
  4030. this.annotationLayer = null;
  4031. }
  4032. if (this.canvas && !currentZoomLayerNode) {
  4033. this.paintedViewportMap.delete(this.canvas);
  4034. this.canvas.width = 0;
  4035. this.canvas.height = 0;
  4036. delete this.canvas;
  4037. }
  4038. if (this.svg) {
  4039. this.paintedViewportMap.delete(this.svg);
  4040. delete this.svg;
  4041. }
  4042. this.loadingIconDiv = document.createElement('div');
  4043. this.loadingIconDiv.className = 'loadingIcon';
  4044. div.appendChild(this.loadingIconDiv);
  4045. },
  4046. update: function PDFPageView_update(scale, rotation) {
  4047. this.scale = scale || this.scale;
  4048. if (typeof rotation !== 'undefined') {
  4049. this.rotation = rotation;
  4050. }
  4051. var totalRotation = (this.rotation + this.pdfPageRotate) % 360;
  4052. this.viewport = this.viewport.clone({
  4053. scale: this.scale * CSS_UNITS,
  4054. rotation: totalRotation
  4055. });
  4056. if (this.svg) {
  4057. this.cssTransform(this.svg, true);
  4058. this.eventBus.dispatch('pagerendered', {
  4059. source: this,
  4060. pageNumber: this.id,
  4061. cssTransform: true
  4062. });
  4063. return;
  4064. }
  4065. var isScalingRestricted = false;
  4066. if (this.canvas && pdfjsLib.PDFJS.maxCanvasPixels > 0) {
  4067. var outputScale = this.outputScale;
  4068. if ((Math.floor(this.viewport.width) * outputScale.sx | 0) * (Math.floor(this.viewport.height) * outputScale.sy | 0) > pdfjsLib.PDFJS.maxCanvasPixels) {
  4069. isScalingRestricted = true;
  4070. }
  4071. }
  4072. if (this.canvas) {
  4073. if (pdfjsLib.PDFJS.useOnlyCssZoom || this.hasRestrictedScaling && isScalingRestricted) {
  4074. this.cssTransform(this.canvas, true);
  4075. this.eventBus.dispatch('pagerendered', {
  4076. source: this,
  4077. pageNumber: this.id,
  4078. cssTransform: true
  4079. });
  4080. return;
  4081. }
  4082. if (!this.zoomLayer) {
  4083. this.zoomLayer = this.canvas.parentNode;
  4084. this.zoomLayer.style.position = 'absolute';
  4085. }
  4086. }
  4087. if (this.zoomLayer) {
  4088. this.cssTransform(this.zoomLayer.firstChild);
  4089. }
  4090. this.reset(true, true);
  4091. },
  4092. cancelRendering: function PDFPageView_cancelRendering() {
  4093. if (this.paintTask) {
  4094. this.paintTask.cancel();
  4095. this.paintTask = null;
  4096. }
  4097. this.renderingState = RenderingStates.INITIAL;
  4098. this.resume = null;
  4099. if (this.textLayer) {
  4100. this.textLayer.cancel();
  4101. this.textLayer = null;
  4102. }
  4103. },
  4104. updatePosition: function PDFPageView_updatePosition() {
  4105. if (this.textLayer) {
  4106. this.textLayer.render(TEXT_LAYER_RENDER_DELAY);
  4107. }
  4108. },
  4109. cssTransform: function PDFPageView_transform(target, redrawAnnotations) {
  4110. var CustomStyle = pdfjsLib.CustomStyle;
  4111. var width = this.viewport.width;
  4112. var height = this.viewport.height;
  4113. var div = this.div;
  4114. target.style.width = target.parentNode.style.width = div.style.width = Math.floor(width) + 'px';
  4115. target.style.height = target.parentNode.style.height = div.style.height = Math.floor(height) + 'px';
  4116. var relativeRotation = this.viewport.rotation - this.paintedViewportMap.get(target).rotation;
  4117. var absRotation = Math.abs(relativeRotation);
  4118. var scaleX = 1, scaleY = 1;
  4119. if (absRotation === 90 || absRotation === 270) {
  4120. scaleX = height / width;
  4121. scaleY = width / height;
  4122. }
  4123. var cssTransform = 'rotate(' + relativeRotation + 'deg) ' + 'scale(' + scaleX + ',' + scaleY + ')';
  4124. CustomStyle.setProp('transform', target, cssTransform);
  4125. if (this.textLayer) {
  4126. var textLayerViewport = this.textLayer.viewport;
  4127. var textRelativeRotation = this.viewport.rotation - textLayerViewport.rotation;
  4128. var textAbsRotation = Math.abs(textRelativeRotation);
  4129. var scale = width / textLayerViewport.width;
  4130. if (textAbsRotation === 90 || textAbsRotation === 270) {
  4131. scale = width / textLayerViewport.height;
  4132. }
  4133. var textLayerDiv = this.textLayer.textLayerDiv;
  4134. var transX, transY;
  4135. switch (textAbsRotation) {
  4136. case 0:
  4137. transX = transY = 0;
  4138. break;
  4139. case 90:
  4140. transX = 0;
  4141. transY = '-' + textLayerDiv.style.height;
  4142. break;
  4143. case 180:
  4144. transX = '-' + textLayerDiv.style.width;
  4145. transY = '-' + textLayerDiv.style.height;
  4146. break;
  4147. case 270:
  4148. transX = '-' + textLayerDiv.style.width;
  4149. transY = 0;
  4150. break;
  4151. default:
  4152. console.error('Bad rotation value.');
  4153. break;
  4154. }
  4155. CustomStyle.setProp('transform', textLayerDiv, 'rotate(' + textAbsRotation + 'deg) ' + 'scale(' + scale + ', ' + scale + ') ' + 'translate(' + transX + ', ' + transY + ')');
  4156. CustomStyle.setProp('transformOrigin', textLayerDiv, '0% 0%');
  4157. }
  4158. if (redrawAnnotations && this.annotationLayer) {
  4159. this.annotationLayer.render(this.viewport, 'display');
  4160. }
  4161. },
  4162. get width() {
  4163. return this.viewport.width;
  4164. },
  4165. get height() {
  4166. return this.viewport.height;
  4167. },
  4168. getPagePoint: function PDFPageView_getPagePoint(x, y) {
  4169. return this.viewport.convertToPdfPoint(x, y);
  4170. },
  4171. draw: function PDFPageView_draw() {
  4172. if (this.renderingState !== RenderingStates.INITIAL) {
  4173. console.error('Must be in new state before drawing');
  4174. this.reset();
  4175. }
  4176. this.renderingState = RenderingStates.RUNNING;
  4177. var self = this;
  4178. var pdfPage = this.pdfPage;
  4179. var viewport = this.viewport;
  4180. var div = this.div;
  4181. var canvasWrapper = document.createElement('div');
  4182. canvasWrapper.style.width = div.style.width;
  4183. canvasWrapper.style.height = div.style.height;
  4184. canvasWrapper.classList.add('canvasWrapper');
  4185. if (this.annotationLayer && this.annotationLayer.div) {
  4186. div.insertBefore(canvasWrapper, this.annotationLayer.div);
  4187. } else {
  4188. div.appendChild(canvasWrapper);
  4189. }
  4190. var textLayerDiv = null;
  4191. var textLayer = null;
  4192. if (this.textLayerFactory) {
  4193. textLayerDiv = document.createElement('div');
  4194. textLayerDiv.className = 'textLayer';
  4195. textLayerDiv.style.width = canvasWrapper.style.width;
  4196. textLayerDiv.style.height = canvasWrapper.style.height;
  4197. if (this.annotationLayer && this.annotationLayer.div) {
  4198. div.insertBefore(textLayerDiv, this.annotationLayer.div);
  4199. } else {
  4200. div.appendChild(textLayerDiv);
  4201. }
  4202. textLayer = this.textLayerFactory.createTextLayerBuilder(textLayerDiv, this.id - 1, this.viewport, this.enhanceTextSelection);
  4203. }
  4204. this.textLayer = textLayer;
  4205. var renderContinueCallback = null;
  4206. if (this.renderingQueue) {
  4207. renderContinueCallback = function renderContinueCallback(cont) {
  4208. if (!self.renderingQueue.isHighestPriority(self)) {
  4209. self.renderingState = RenderingStates.PAUSED;
  4210. self.resume = function resumeCallback() {
  4211. self.renderingState = RenderingStates.RUNNING;
  4212. cont();
  4213. };
  4214. return;
  4215. }
  4216. cont();
  4217. };
  4218. }
  4219. var finishPaintTask = function finishPaintTask(error) {
  4220. if (paintTask === self.paintTask) {
  4221. self.paintTask = null;
  4222. }
  4223. if (error === 'cancelled') {
  4224. self.error = null;
  4225. return Promise.resolve(undefined);
  4226. }
  4227. self.renderingState = RenderingStates.FINISHED;
  4228. if (self.loadingIconDiv) {
  4229. div.removeChild(self.loadingIconDiv);
  4230. delete self.loadingIconDiv;
  4231. }
  4232. if (self.zoomLayer) {
  4233. var zoomLayerCanvas = self.zoomLayer.firstChild;
  4234. self.paintedViewportMap.delete(zoomLayerCanvas);
  4235. zoomLayerCanvas.width = 0;
  4236. zoomLayerCanvas.height = 0;
  4237. if (div.contains(self.zoomLayer)) {
  4238. div.removeChild(self.zoomLayer);
  4239. }
  4240. self.zoomLayer = null;
  4241. }
  4242. self.error = error;
  4243. self.stats = pdfPage.stats;
  4244. if (self.onAfterDraw) {
  4245. self.onAfterDraw();
  4246. }
  4247. self.eventBus.dispatch('pagerendered', {
  4248. source: self,
  4249. pageNumber: self.id,
  4250. cssTransform: false
  4251. });
  4252. if (error) {
  4253. return Promise.reject(error);
  4254. }
  4255. return Promise.resolve(undefined);
  4256. };
  4257. var paintTask = this.renderer === RendererType.SVG ? this.paintOnSvg(canvasWrapper) : this.paintOnCanvas(canvasWrapper);
  4258. paintTask.onRenderContinue = renderContinueCallback;
  4259. this.paintTask = paintTask;
  4260. var resultPromise = paintTask.promise.then(function () {
  4261. return finishPaintTask(null).then(function () {
  4262. if (textLayer) {
  4263. pdfPage.getTextContent({ normalizeWhitespace: true }).then(function textContentResolved(textContent) {
  4264. textLayer.setTextContent(textContent);
  4265. textLayer.render(TEXT_LAYER_RENDER_DELAY);
  4266. });
  4267. }
  4268. });
  4269. }, function (reason) {
  4270. return finishPaintTask(reason);
  4271. });
  4272. if (this.annotationLayerFactory) {
  4273. if (!this.annotationLayer) {
  4274. this.annotationLayer = this.annotationLayerFactory.createAnnotationLayerBuilder(div, pdfPage, this.renderInteractiveForms);
  4275. }
  4276. this.annotationLayer.render(this.viewport, 'display');
  4277. }
  4278. div.setAttribute('data-loaded', true);
  4279. if (this.onBeforeDraw) {
  4280. this.onBeforeDraw();
  4281. }
  4282. return resultPromise;
  4283. },
  4284. paintOnCanvas: function (canvasWrapper) {
  4285. var resolveRenderPromise, rejectRenderPromise;
  4286. var promise = new Promise(function (resolve, reject) {
  4287. resolveRenderPromise = resolve;
  4288. rejectRenderPromise = reject;
  4289. });
  4290. var result = {
  4291. promise: promise,
  4292. onRenderContinue: function (cont) {
  4293. cont();
  4294. },
  4295. cancel: function () {
  4296. renderTask.cancel();
  4297. }
  4298. };
  4299. var self = this;
  4300. var pdfPage = this.pdfPage;
  4301. var viewport = this.viewport;
  4302. var canvas = document.createElement('canvas');
  4303. canvas.id = 'page' + this.id;
  4304. canvas.setAttribute('hidden', 'hidden');
  4305. var isCanvasHidden = true;
  4306. var showCanvas = function () {
  4307. if (isCanvasHidden) {
  4308. canvas.removeAttribute('hidden');
  4309. isCanvasHidden = false;
  4310. }
  4311. };
  4312. canvasWrapper.appendChild(canvas);
  4313. this.canvas = canvas;
  4314. canvas.mozOpaque = true;
  4315. var ctx = canvas.getContext('2d', { alpha: false });
  4316. var outputScale = getOutputScale(ctx);
  4317. this.outputScale = outputScale;
  4318. if (pdfjsLib.PDFJS.useOnlyCssZoom) {
  4319. var actualSizeViewport = viewport.clone({ scale: CSS_UNITS });
  4320. outputScale.sx *= actualSizeViewport.width / viewport.width;
  4321. outputScale.sy *= actualSizeViewport.height / viewport.height;
  4322. outputScale.scaled = true;
  4323. }
  4324. if (pdfjsLib.PDFJS.maxCanvasPixels > 0) {
  4325. var pixelsInViewport = viewport.width * viewport.height;
  4326. var maxScale = Math.sqrt(pdfjsLib.PDFJS.maxCanvasPixels / pixelsInViewport);
  4327. if (outputScale.sx > maxScale || outputScale.sy > maxScale) {
  4328. outputScale.sx = maxScale;
  4329. outputScale.sy = maxScale;
  4330. outputScale.scaled = true;
  4331. this.hasRestrictedScaling = true;
  4332. } else {
  4333. this.hasRestrictedScaling = false;
  4334. }
  4335. }
  4336. var sfx = approximateFraction(outputScale.sx);
  4337. var sfy = approximateFraction(outputScale.sy);
  4338. canvas.width = roundToDivide(viewport.width * outputScale.sx, sfx[0]);
  4339. canvas.height = roundToDivide(viewport.height * outputScale.sy, sfy[0]);
  4340. canvas.style.width = roundToDivide(viewport.width, sfx[1]) + 'px';
  4341. canvas.style.height = roundToDivide(viewport.height, sfy[1]) + 'px';
  4342. this.paintedViewportMap.set(canvas, viewport);
  4343. var transform = !outputScale.scaled ? null : [
  4344. outputScale.sx,
  4345. 0,
  4346. 0,
  4347. outputScale.sy,
  4348. 0,
  4349. 0
  4350. ];
  4351. var renderContext = {
  4352. canvasContext: ctx,
  4353. transform: transform,
  4354. viewport: this.viewport,
  4355. renderInteractiveForms: this.renderInteractiveForms
  4356. };
  4357. var renderTask = this.pdfPage.render(renderContext);
  4358. renderTask.onContinue = function (cont) {
  4359. showCanvas();
  4360. if (result.onRenderContinue) {
  4361. result.onRenderContinue(cont);
  4362. } else {
  4363. cont();
  4364. }
  4365. };
  4366. renderTask.promise.then(function pdfPageRenderCallback() {
  4367. showCanvas();
  4368. resolveRenderPromise(undefined);
  4369. }, function pdfPageRenderError(error) {
  4370. showCanvas();
  4371. rejectRenderPromise(error);
  4372. });
  4373. return result;
  4374. },
  4375. paintOnSvg: function PDFPageView_paintOnSvg(wrapper) {
  4376. var cancelled = false;
  4377. var ensureNotCancelled = function () {
  4378. if (cancelled) {
  4379. throw 'cancelled';
  4380. }
  4381. };
  4382. var self = this;
  4383. var pdfPage = this.pdfPage;
  4384. var SVGGraphics = pdfjsLib.SVGGraphics;
  4385. var actualSizeViewport = this.viewport.clone({ scale: CSS_UNITS });
  4386. var promise = pdfPage.getOperatorList().then(function (opList) {
  4387. ensureNotCancelled();
  4388. var svgGfx = new SVGGraphics(pdfPage.commonObjs, pdfPage.objs);
  4389. return svgGfx.getSVG(opList, actualSizeViewport).then(function (svg) {
  4390. ensureNotCancelled();
  4391. self.svg = svg;
  4392. self.paintedViewportMap.set(svg, actualSizeViewport);
  4393. svg.style.width = wrapper.style.width;
  4394. svg.style.height = wrapper.style.height;
  4395. self.renderingState = RenderingStates.FINISHED;
  4396. wrapper.appendChild(svg);
  4397. });
  4398. });
  4399. return {
  4400. promise: promise,
  4401. onRenderContinue: function (cont) {
  4402. cont();
  4403. },
  4404. cancel: function () {
  4405. cancelled = true;
  4406. }
  4407. };
  4408. },
  4409. setPageLabel: function PDFView_setPageLabel(label) {
  4410. this.pageLabel = typeof label === 'string' ? label : null;
  4411. if (this.pageLabel !== null) {
  4412. this.div.setAttribute('data-page-label', this.pageLabel);
  4413. } else {
  4414. this.div.removeAttribute('data-page-label');
  4415. }
  4416. }
  4417. };
  4418. return PDFPageView;
  4419. }();
  4420. exports.PDFPageView = PDFPageView;
  4421. }));
  4422. (function (root, factory) {
  4423. factory(root.pdfjsWebPDFThumbnailViewer = {}, root.pdfjsWebUIUtils, root.pdfjsWebPDFThumbnailView);
  4424. }(this, function (exports, uiUtils, pdfThumbnailView) {
  4425. var watchScroll = uiUtils.watchScroll;
  4426. var getVisibleElements = uiUtils.getVisibleElements;
  4427. var scrollIntoView = uiUtils.scrollIntoView;
  4428. var PDFThumbnailView = pdfThumbnailView.PDFThumbnailView;
  4429. var THUMBNAIL_SCROLL_MARGIN = -19;
  4430. var PDFThumbnailViewer = function PDFThumbnailViewerClosure() {
  4431. function PDFThumbnailViewer(options) {
  4432. this.container = options.container;
  4433. this.renderingQueue = options.renderingQueue;
  4434. this.linkService = options.linkService;
  4435. this.scroll = watchScroll(this.container, this._scrollUpdated.bind(this));
  4436. this._resetView();
  4437. }
  4438. PDFThumbnailViewer.prototype = {
  4439. _scrollUpdated: function PDFThumbnailViewer_scrollUpdated() {
  4440. this.renderingQueue.renderHighestPriority();
  4441. },
  4442. getThumbnail: function PDFThumbnailViewer_getThumbnail(index) {
  4443. return this.thumbnails[index];
  4444. },
  4445. _getVisibleThumbs: function PDFThumbnailViewer_getVisibleThumbs() {
  4446. return getVisibleElements(this.container, this.thumbnails);
  4447. },
  4448. scrollThumbnailIntoView: function PDFThumbnailViewer_scrollThumbnailIntoView(page) {
  4449. var selected = document.querySelector('.thumbnail.selected');
  4450. if (selected) {
  4451. selected.classList.remove('selected');
  4452. }
  4453. var thumbnail = document.querySelector('div.thumbnail[data-page-number="' + page + '"]');
  4454. if (thumbnail) {
  4455. thumbnail.classList.add('selected');
  4456. }
  4457. var visibleThumbs = this._getVisibleThumbs();
  4458. var numVisibleThumbs = visibleThumbs.views.length;
  4459. if (numVisibleThumbs > 0) {
  4460. var first = visibleThumbs.first.id;
  4461. var last = numVisibleThumbs > 1 ? visibleThumbs.last.id : first;
  4462. if (page <= first || page >= last) {
  4463. scrollIntoView(thumbnail, { top: THUMBNAIL_SCROLL_MARGIN });
  4464. }
  4465. }
  4466. },
  4467. get pagesRotation() {
  4468. return this._pagesRotation;
  4469. },
  4470. set pagesRotation(rotation) {
  4471. this._pagesRotation = rotation;
  4472. for (var i = 0, l = this.thumbnails.length; i < l; i++) {
  4473. var thumb = this.thumbnails[i];
  4474. thumb.update(rotation);
  4475. }
  4476. },
  4477. cleanup: function PDFThumbnailViewer_cleanup() {
  4478. var tempCanvas = PDFThumbnailView.tempImageCache;
  4479. if (tempCanvas) {
  4480. tempCanvas.width = 0;
  4481. tempCanvas.height = 0;
  4482. }
  4483. PDFThumbnailView.tempImageCache = null;
  4484. },
  4485. _resetView: function PDFThumbnailViewer_resetView() {
  4486. this.thumbnails = [];
  4487. this._pageLabels = null;
  4488. this._pagesRotation = 0;
  4489. this._pagesRequests = [];
  4490. this.container.textContent = '';
  4491. },
  4492. setDocument: function PDFThumbnailViewer_setDocument(pdfDocument) {
  4493. if (this.pdfDocument) {
  4494. this._cancelRendering();
  4495. this._resetView();
  4496. }
  4497. this.pdfDocument = pdfDocument;
  4498. if (!pdfDocument) {
  4499. return Promise.resolve();
  4500. }
  4501. return pdfDocument.getPage(1).then(function (firstPage) {
  4502. var pagesCount = pdfDocument.numPages;
  4503. var viewport = firstPage.getViewport(1.0);
  4504. for (var pageNum = 1; pageNum <= pagesCount; ++pageNum) {
  4505. var thumbnail = new PDFThumbnailView({
  4506. container: this.container,
  4507. id: pageNum,
  4508. defaultViewport: viewport.clone(),
  4509. linkService: this.linkService,
  4510. renderingQueue: this.renderingQueue,
  4511. disableCanvasToImageConversion: false
  4512. });
  4513. this.thumbnails.push(thumbnail);
  4514. }
  4515. }.bind(this));
  4516. },
  4517. _cancelRendering: function PDFThumbnailViewer_cancelRendering() {
  4518. for (var i = 0, ii = this.thumbnails.length; i < ii; i++) {
  4519. if (this.thumbnails[i]) {
  4520. this.thumbnails[i].cancelRendering();
  4521. }
  4522. }
  4523. },
  4524. setPageLabels: function PDFThumbnailViewer_setPageLabels(labels) {
  4525. if (!this.pdfDocument) {
  4526. return;
  4527. }
  4528. if (!labels) {
  4529. this._pageLabels = null;
  4530. } else if (!(labels instanceof Array && this.pdfDocument.numPages === labels.length)) {
  4531. this._pageLabels = null;
  4532. console.error('PDFThumbnailViewer_setPageLabels: Invalid page labels.');
  4533. } else {
  4534. this._pageLabels = labels;
  4535. }
  4536. for (var i = 0, ii = this.thumbnails.length; i < ii; i++) {
  4537. var thumbnailView = this.thumbnails[i];
  4538. var label = this._pageLabels && this._pageLabels[i];
  4539. thumbnailView.setPageLabel(label);
  4540. }
  4541. },
  4542. _ensurePdfPageLoaded: function PDFThumbnailViewer_ensurePdfPageLoaded(thumbView) {
  4543. if (thumbView.pdfPage) {
  4544. return Promise.resolve(thumbView.pdfPage);
  4545. }
  4546. var pageNumber = thumbView.id;
  4547. if (this._pagesRequests[pageNumber]) {
  4548. return this._pagesRequests[pageNumber];
  4549. }
  4550. var promise = this.pdfDocument.getPage(pageNumber).then(function (pdfPage) {
  4551. thumbView.setPdfPage(pdfPage);
  4552. this._pagesRequests[pageNumber] = null;
  4553. return pdfPage;
  4554. }.bind(this));
  4555. this._pagesRequests[pageNumber] = promise;
  4556. return promise;
  4557. },
  4558. forceRendering: function () {
  4559. var visibleThumbs = this._getVisibleThumbs();
  4560. var thumbView = this.renderingQueue.getHighestPriority(visibleThumbs, this.thumbnails, this.scroll.down);
  4561. if (thumbView) {
  4562. this._ensurePdfPageLoaded(thumbView).then(function () {
  4563. this.renderingQueue.renderView(thumbView);
  4564. }.bind(this));
  4565. return true;
  4566. }
  4567. return false;
  4568. }
  4569. };
  4570. return PDFThumbnailViewer;
  4571. }();
  4572. exports.PDFThumbnailViewer = PDFThumbnailViewer;
  4573. }));
  4574. (function (root, factory) {
  4575. factory(root.pdfjsWebTextLayerBuilder = {}, root.pdfjsWebDOMEvents, root.pdfjsWebPDFJS);
  4576. }(this, function (exports, domEvents, pdfjsLib) {
  4577. var EXPAND_DIVS_TIMEOUT = 300;
  4578. var TextLayerBuilder = function TextLayerBuilderClosure() {
  4579. function TextLayerBuilder(options) {
  4580. this.textLayerDiv = options.textLayerDiv;
  4581. this.eventBus = options.eventBus || domEvents.getGlobalEventBus();
  4582. this.textContent = null;
  4583. this.renderingDone = false;
  4584. this.pageIdx = options.pageIndex;
  4585. this.pageNumber = this.pageIdx + 1;
  4586. this.matches = [];
  4587. this.viewport = options.viewport;
  4588. this.textDivs = [];
  4589. this.findController = options.findController || null;
  4590. this.textLayerRenderTask = null;
  4591. this.enhanceTextSelection = options.enhanceTextSelection;
  4592. this._bindMouse();
  4593. }
  4594. TextLayerBuilder.prototype = {
  4595. _finishRendering: function TextLayerBuilder_finishRendering() {
  4596. this.renderingDone = true;
  4597. if (!this.enhanceTextSelection) {
  4598. var endOfContent = document.createElement('div');
  4599. endOfContent.className = 'endOfContent';
  4600. this.textLayerDiv.appendChild(endOfContent);
  4601. }
  4602. this.eventBus.dispatch('textlayerrendered', {
  4603. source: this,
  4604. pageNumber: this.pageNumber,
  4605. numTextDivs: this.textDivs.length
  4606. });
  4607. },
  4608. render: function TextLayerBuilder_render(timeout) {
  4609. if (!this.textContent || this.renderingDone) {
  4610. return;
  4611. }
  4612. this.cancel();
  4613. this.textDivs = [];
  4614. var textLayerFrag = document.createDocumentFragment();
  4615. this.textLayerRenderTask = pdfjsLib.renderTextLayer({
  4616. textContent: this.textContent,
  4617. container: textLayerFrag,
  4618. viewport: this.viewport,
  4619. textDivs: this.textDivs,
  4620. timeout: timeout,
  4621. enhanceTextSelection: this.enhanceTextSelection
  4622. });
  4623. this.textLayerRenderTask.promise.then(function () {
  4624. this.textLayerDiv.appendChild(textLayerFrag);
  4625. this._finishRendering();
  4626. this.updateMatches();
  4627. }.bind(this), function (reason) {
  4628. });
  4629. },
  4630. cancel: function TextLayerBuilder_cancel() {
  4631. if (this.textLayerRenderTask) {
  4632. this.textLayerRenderTask.cancel();
  4633. this.textLayerRenderTask = null;
  4634. }
  4635. },
  4636. setTextContent: function TextLayerBuilder_setTextContent(textContent) {
  4637. this.cancel();
  4638. this.textContent = textContent;
  4639. },
  4640. convertMatches: function TextLayerBuilder_convertMatches(matches, matchesLength) {
  4641. var i = 0;
  4642. var iIndex = 0;
  4643. var bidiTexts = this.textContent.items;
  4644. var end = bidiTexts.length - 1;
  4645. var queryLen = this.findController === null ? 0 : this.findController.state.query.length;
  4646. var ret = [];
  4647. if (!matches) {
  4648. return ret;
  4649. }
  4650. for (var m = 0, len = matches.length; m < len; m++) {
  4651. var matchIdx = matches[m];
  4652. while (i !== end && matchIdx >= iIndex + bidiTexts[i].str.length) {
  4653. iIndex += bidiTexts[i].str.length;
  4654. i++;
  4655. }
  4656. if (i === bidiTexts.length) {
  4657. console.error('Could not find a matching mapping');
  4658. }
  4659. var match = {
  4660. begin: {
  4661. divIdx: i,
  4662. offset: matchIdx - iIndex
  4663. }
  4664. };
  4665. if (matchesLength) {
  4666. matchIdx += matchesLength[m];
  4667. } else {
  4668. matchIdx += queryLen;
  4669. }
  4670. while (i !== end && matchIdx > iIndex + bidiTexts[i].str.length) {
  4671. iIndex += bidiTexts[i].str.length;
  4672. i++;
  4673. }
  4674. match.end = {
  4675. divIdx: i,
  4676. offset: matchIdx - iIndex
  4677. };
  4678. ret.push(match);
  4679. }
  4680. return ret;
  4681. },
  4682. renderMatches: function TextLayerBuilder_renderMatches(matches) {
  4683. if (matches.length === 0) {
  4684. return;
  4685. }
  4686. var bidiTexts = this.textContent.items;
  4687. var textDivs = this.textDivs;
  4688. var prevEnd = null;
  4689. var pageIdx = this.pageIdx;
  4690. var isSelectedPage = this.findController === null ? false : pageIdx === this.findController.selected.pageIdx;
  4691. var selectedMatchIdx = this.findController === null ? -1 : this.findController.selected.matchIdx;
  4692. var highlightAll = this.findController === null ? false : this.findController.state.highlightAll;
  4693. var infinity = {
  4694. divIdx: -1,
  4695. offset: undefined
  4696. };
  4697. function beginText(begin, className) {
  4698. var divIdx = begin.divIdx;
  4699. textDivs[divIdx].textContent = '';
  4700. appendTextToDiv(divIdx, 0, begin.offset, className);
  4701. }
  4702. function appendTextToDiv(divIdx, fromOffset, toOffset, className) {
  4703. var div = textDivs[divIdx];
  4704. var content = bidiTexts[divIdx].str.substring(fromOffset, toOffset);
  4705. var node = document.createTextNode(content);
  4706. if (className) {
  4707. var span = document.createElement('span');
  4708. span.className = className;
  4709. span.appendChild(node);
  4710. div.appendChild(span);
  4711. return;
  4712. }
  4713. div.appendChild(node);
  4714. }
  4715. var i0 = selectedMatchIdx, i1 = i0 + 1;
  4716. if (highlightAll) {
  4717. i0 = 0;
  4718. i1 = matches.length;
  4719. } else if (!isSelectedPage) {
  4720. return;
  4721. }
  4722. for (var i = i0; i < i1; i++) {
  4723. var match = matches[i];
  4724. var begin = match.begin;
  4725. var end = match.end;
  4726. var isSelected = isSelectedPage && i === selectedMatchIdx;
  4727. var highlightSuffix = isSelected ? ' selected' : '';
  4728. if (this.findController) {
  4729. this.findController.updateMatchPosition(pageIdx, i, textDivs, begin.divIdx);
  4730. }
  4731. if (!prevEnd || begin.divIdx !== prevEnd.divIdx) {
  4732. if (prevEnd !== null) {
  4733. appendTextToDiv(prevEnd.divIdx, prevEnd.offset, infinity.offset);
  4734. }
  4735. beginText(begin);
  4736. } else {
  4737. appendTextToDiv(prevEnd.divIdx, prevEnd.offset, begin.offset);
  4738. }
  4739. if (begin.divIdx === end.divIdx) {
  4740. appendTextToDiv(begin.divIdx, begin.offset, end.offset, 'highlight' + highlightSuffix);
  4741. } else {
  4742. appendTextToDiv(begin.divIdx, begin.offset, infinity.offset, 'highlight begin' + highlightSuffix);
  4743. for (var n0 = begin.divIdx + 1, n1 = end.divIdx; n0 < n1; n0++) {
  4744. textDivs[n0].className = 'highlight middle' + highlightSuffix;
  4745. }
  4746. beginText(end, 'highlight end' + highlightSuffix);
  4747. }
  4748. prevEnd = end;
  4749. }
  4750. if (prevEnd) {
  4751. appendTextToDiv(prevEnd.divIdx, prevEnd.offset, infinity.offset);
  4752. }
  4753. },
  4754. updateMatches: function TextLayerBuilder_updateMatches() {
  4755. if (!this.renderingDone) {
  4756. return;
  4757. }
  4758. var matches = this.matches;
  4759. var textDivs = this.textDivs;
  4760. var bidiTexts = this.textContent.items;
  4761. var clearedUntilDivIdx = -1;
  4762. for (var i = 0, len = matches.length; i < len; i++) {
  4763. var match = matches[i];
  4764. var begin = Math.max(clearedUntilDivIdx, match.begin.divIdx);
  4765. for (var n = begin, end = match.end.divIdx; n <= end; n++) {
  4766. var div = textDivs[n];
  4767. div.textContent = bidiTexts[n].str;
  4768. div.className = '';
  4769. }
  4770. clearedUntilDivIdx = match.end.divIdx + 1;
  4771. }
  4772. if (this.findController === null || !this.findController.active) {
  4773. return;
  4774. }
  4775. var pageMatches, pageMatchesLength;
  4776. if (this.findController !== null) {
  4777. pageMatches = this.findController.pageMatches[this.pageIdx] || null;
  4778. pageMatchesLength = this.findController.pageMatchesLength ? this.findController.pageMatchesLength[this.pageIdx] || null : null;
  4779. }
  4780. this.matches = this.convertMatches(pageMatches, pageMatchesLength);
  4781. this.renderMatches(this.matches);
  4782. },
  4783. _bindMouse: function TextLayerBuilder_bindMouse() {
  4784. var div = this.textLayerDiv;
  4785. var self = this;
  4786. var expandDivsTimer = null;
  4787. div.addEventListener('mousedown', function (e) {
  4788. if (self.enhanceTextSelection && self.textLayerRenderTask) {
  4789. self.textLayerRenderTask.expandTextDivs(true);
  4790. if (expandDivsTimer) {
  4791. clearTimeout(expandDivsTimer);
  4792. expandDivsTimer = null;
  4793. }
  4794. return;
  4795. }
  4796. var end = div.querySelector('.endOfContent');
  4797. if (!end) {
  4798. return;
  4799. }
  4800. var adjustTop = e.target !== div;
  4801. adjustTop = adjustTop && window.getComputedStyle(end).getPropertyValue('-moz-user-select') !== 'none';
  4802. if (adjustTop) {
  4803. var divBounds = div.getBoundingClientRect();
  4804. var r = Math.max(0, (e.pageY - divBounds.top) / divBounds.height);
  4805. end.style.top = (r * 100).toFixed(2) + '%';
  4806. }
  4807. end.classList.add('active');
  4808. });
  4809. div.addEventListener('mouseup', function (e) {
  4810. if (self.enhanceTextSelection && self.textLayerRenderTask) {
  4811. expandDivsTimer = setTimeout(function () {
  4812. if (self.textLayerRenderTask) {
  4813. self.textLayerRenderTask.expandTextDivs(false);
  4814. }
  4815. expandDivsTimer = null;
  4816. }, EXPAND_DIVS_TIMEOUT);
  4817. return;
  4818. }
  4819. var end = div.querySelector('.endOfContent');
  4820. if (!end) {
  4821. return;
  4822. }
  4823. end.style.top = '';
  4824. end.classList.remove('active');
  4825. });
  4826. }
  4827. };
  4828. return TextLayerBuilder;
  4829. }();
  4830. function DefaultTextLayerFactory() {
  4831. }
  4832. DefaultTextLayerFactory.prototype = {
  4833. createTextLayerBuilder: function (textLayerDiv, pageIndex, viewport, enhanceTextSelection) {
  4834. return new TextLayerBuilder({
  4835. textLayerDiv: textLayerDiv,
  4836. pageIndex: pageIndex,
  4837. viewport: viewport,
  4838. enhanceTextSelection: enhanceTextSelection
  4839. });
  4840. }
  4841. };
  4842. exports.TextLayerBuilder = TextLayerBuilder;
  4843. exports.DefaultTextLayerFactory = DefaultTextLayerFactory;
  4844. }));
  4845. (function (root, factory) {
  4846. factory(root.pdfjsWebAnnotationLayerBuilder = {}, root.pdfjsWebUIUtils, root.pdfjsWebPDFLinkService, root.pdfjsWebPDFJS);
  4847. }(this, function (exports, uiUtils, pdfLinkService, pdfjsLib) {
  4848. var mozL10n = uiUtils.mozL10n;
  4849. var SimpleLinkService = pdfLinkService.SimpleLinkService;
  4850. var AnnotationLayerBuilder = function AnnotationLayerBuilderClosure() {
  4851. function AnnotationLayerBuilder(options) {
  4852. this.pageDiv = options.pageDiv;
  4853. this.pdfPage = options.pdfPage;
  4854. this.renderInteractiveForms = options.renderInteractiveForms;
  4855. this.linkService = options.linkService;
  4856. this.downloadManager = options.downloadManager;
  4857. this.div = null;
  4858. }
  4859. AnnotationLayerBuilder.prototype = {
  4860. render: function AnnotationLayerBuilder_render(viewport, intent) {
  4861. var self = this;
  4862. var parameters = { intent: intent === undefined ? 'display' : intent };
  4863. this.pdfPage.getAnnotations(parameters).then(function (annotations) {
  4864. viewport = viewport.clone({ dontFlip: true });
  4865. parameters = {
  4866. viewport: viewport,
  4867. div: self.div,
  4868. annotations: annotations,
  4869. page: self.pdfPage,
  4870. renderInteractiveForms: self.renderInteractiveForms,
  4871. linkService: self.linkService,
  4872. downloadManager: self.downloadManager
  4873. };
  4874. if (self.div) {
  4875. pdfjsLib.AnnotationLayer.update(parameters);
  4876. } else {
  4877. if (annotations.length === 0) {
  4878. return;
  4879. }
  4880. self.div = document.createElement('div');
  4881. self.div.className = 'annotationLayer';
  4882. self.pageDiv.appendChild(self.div);
  4883. parameters.div = self.div;
  4884. pdfjsLib.AnnotationLayer.render(parameters);
  4885. if (typeof mozL10n !== 'undefined') {
  4886. mozL10n.translate(self.div);
  4887. }
  4888. }
  4889. });
  4890. },
  4891. hide: function AnnotationLayerBuilder_hide() {
  4892. if (!this.div) {
  4893. return;
  4894. }
  4895. this.div.setAttribute('hidden', 'true');
  4896. }
  4897. };
  4898. return AnnotationLayerBuilder;
  4899. }();
  4900. function DefaultAnnotationLayerFactory() {
  4901. }
  4902. DefaultAnnotationLayerFactory.prototype = {
  4903. createAnnotationLayerBuilder: function (pageDiv, pdfPage, renderInteractiveForms) {
  4904. return new AnnotationLayerBuilder({
  4905. pageDiv: pageDiv,
  4906. pdfPage: pdfPage,
  4907. renderInteractiveForms: renderInteractiveForms,
  4908. linkService: new SimpleLinkService()
  4909. });
  4910. }
  4911. };
  4912. exports.AnnotationLayerBuilder = AnnotationLayerBuilder;
  4913. exports.DefaultAnnotationLayerFactory = DefaultAnnotationLayerFactory;
  4914. }));
  4915. (function (root, factory) {
  4916. factory(root.pdfjsWebPDFViewer = {}, root.pdfjsWebUIUtils, root.pdfjsWebPDFPageView, root.pdfjsWebPDFRenderingQueue, root.pdfjsWebTextLayerBuilder, root.pdfjsWebAnnotationLayerBuilder, root.pdfjsWebPDFLinkService, root.pdfjsWebDOMEvents, root.pdfjsWebPDFJS);
  4917. }(this, function (exports, uiUtils, pdfPageView, pdfRenderingQueue, textLayerBuilder, annotationLayerBuilder, pdfLinkService, domEvents, pdfjsLib) {
  4918. var UNKNOWN_SCALE = uiUtils.UNKNOWN_SCALE;
  4919. var SCROLLBAR_PADDING = uiUtils.SCROLLBAR_PADDING;
  4920. var VERTICAL_PADDING = uiUtils.VERTICAL_PADDING;
  4921. var MAX_AUTO_SCALE = uiUtils.MAX_AUTO_SCALE;
  4922. var CSS_UNITS = uiUtils.CSS_UNITS;
  4923. var DEFAULT_SCALE = uiUtils.DEFAULT_SCALE;
  4924. var DEFAULT_SCALE_VALUE = uiUtils.DEFAULT_SCALE_VALUE;
  4925. var RendererType = uiUtils.RendererType;
  4926. var scrollIntoView = uiUtils.scrollIntoView;
  4927. var watchScroll = uiUtils.watchScroll;
  4928. var getVisibleElements = uiUtils.getVisibleElements;
  4929. var PDFPageView = pdfPageView.PDFPageView;
  4930. var RenderingStates = pdfRenderingQueue.RenderingStates;
  4931. var PDFRenderingQueue = pdfRenderingQueue.PDFRenderingQueue;
  4932. var TextLayerBuilder = textLayerBuilder.TextLayerBuilder;
  4933. var AnnotationLayerBuilder = annotationLayerBuilder.AnnotationLayerBuilder;
  4934. var SimpleLinkService = pdfLinkService.SimpleLinkService;
  4935. var PresentationModeState = {
  4936. UNKNOWN: 0,
  4937. NORMAL: 1,
  4938. CHANGING: 2,
  4939. FULLSCREEN: 3
  4940. };
  4941. var DEFAULT_CACHE_SIZE = 10;
  4942. var PDFViewer = function pdfViewer() {
  4943. function PDFPageViewBuffer(size) {
  4944. var data = [];
  4945. this.push = function cachePush(view) {
  4946. var i = data.indexOf(view);
  4947. if (i >= 0) {
  4948. data.splice(i, 1);
  4949. }
  4950. data.push(view);
  4951. if (data.length > size) {
  4952. data.shift().destroy();
  4953. }
  4954. };
  4955. this.resize = function (newSize) {
  4956. size = newSize;
  4957. while (data.length > size) {
  4958. data.shift().destroy();
  4959. }
  4960. };
  4961. }
  4962. function isSameScale(oldScale, newScale) {
  4963. if (newScale === oldScale) {
  4964. return true;
  4965. }
  4966. if (Math.abs(newScale - oldScale) < 1e-15) {
  4967. return true;
  4968. }
  4969. return false;
  4970. }
  4971. function PDFViewer(options) {
  4972. this.container = options.container;
  4973. this.viewer = options.viewer || options.container.firstElementChild;
  4974. this.eventBus = options.eventBus || domEvents.getGlobalEventBus();
  4975. this.linkService = options.linkService || new SimpleLinkService();
  4976. this.downloadManager = options.downloadManager || null;
  4977. this.removePageBorders = options.removePageBorders || false;
  4978. this.enhanceTextSelection = options.enhanceTextSelection || false;
  4979. this.renderInteractiveForms = options.renderInteractiveForms || false;
  4980. this.renderer = options.renderer || RendererType.CANVAS;
  4981. this.defaultRenderingQueue = !options.renderingQueue;
  4982. if (this.defaultRenderingQueue) {
  4983. this.renderingQueue = new PDFRenderingQueue();
  4984. this.renderingQueue.setViewer(this);
  4985. } else {
  4986. this.renderingQueue = options.renderingQueue;
  4987. }
  4988. this.scroll = watchScroll(this.container, this._scrollUpdate.bind(this));
  4989. this.presentationModeState = PresentationModeState.UNKNOWN;
  4990. this._resetView();
  4991. if (this.removePageBorders) {
  4992. this.viewer.classList.add('removePageBorders');
  4993. }
  4994. }
  4995. PDFViewer.prototype = {
  4996. get pagesCount() {
  4997. return this._pages.length;
  4998. },
  4999. getPageView: function (index) {
  5000. return this._pages[index];
  5001. },
  5002. get pageViewsReady() {
  5003. return this._pageViewsReady;
  5004. },
  5005. get currentPageNumber() {
  5006. return this._currentPageNumber;
  5007. },
  5008. set currentPageNumber(val) {
  5009. if ((val | 0) !== val) {
  5010. throw new Error('Invalid page number.');
  5011. }
  5012. if (!this.pdfDocument) {
  5013. this._currentPageNumber = val;
  5014. return;
  5015. }
  5016. this._setCurrentPageNumber(val, true);
  5017. },
  5018. _setCurrentPageNumber: function PDFViewer_setCurrentPageNumber(val, resetCurrentPageView) {
  5019. if (this._currentPageNumber === val) {
  5020. if (resetCurrentPageView) {
  5021. this._resetCurrentPageView();
  5022. }
  5023. return;
  5024. }
  5025. if (!(0 < val && val <= this.pagesCount)) {
  5026. console.error('PDFViewer_setCurrentPageNumber: "' + val + '" is out of bounds.');
  5027. return;
  5028. }
  5029. var arg = {
  5030. source: this,
  5031. pageNumber: val,
  5032. pageLabel: this._pageLabels && this._pageLabels[val - 1]
  5033. };
  5034. this._currentPageNumber = val;
  5035. this.eventBus.dispatch('pagechanging', arg);
  5036. this.eventBus.dispatch('pagechange', arg);
  5037. if (resetCurrentPageView) {
  5038. this._resetCurrentPageView();
  5039. }
  5040. },
  5041. get currentPageLabel() {
  5042. return this._pageLabels && this._pageLabels[this._currentPageNumber - 1];
  5043. },
  5044. set currentPageLabel(val) {
  5045. var pageNumber = val | 0;
  5046. if (this._pageLabels) {
  5047. var i = this._pageLabels.indexOf(val);
  5048. if (i >= 0) {
  5049. pageNumber = i + 1;
  5050. }
  5051. }
  5052. this.currentPageNumber = pageNumber;
  5053. },
  5054. get currentScale() {
  5055. return this._currentScale !== UNKNOWN_SCALE ? this._currentScale : DEFAULT_SCALE;
  5056. },
  5057. set currentScale(val) {
  5058. if (isNaN(val)) {
  5059. throw new Error('Invalid numeric scale');
  5060. }
  5061. if (!this.pdfDocument) {
  5062. this._currentScale = val;
  5063. this._currentScaleValue = val !== UNKNOWN_SCALE ? val.toString() : null;
  5064. return;
  5065. }
  5066. this._setScale(val, false);
  5067. },
  5068. get currentScaleValue() {
  5069. return this._currentScaleValue;
  5070. },
  5071. set currentScaleValue(val) {
  5072. if (!this.pdfDocument) {
  5073. this._currentScale = isNaN(val) ? UNKNOWN_SCALE : val;
  5074. this._currentScaleValue = val.toString();
  5075. return;
  5076. }
  5077. this._setScale(val, false);
  5078. },
  5079. get pagesRotation() {
  5080. return this._pagesRotation;
  5081. },
  5082. set pagesRotation(rotation) {
  5083. if (!(typeof rotation === 'number' && rotation % 90 === 0)) {
  5084. throw new Error('Invalid pages rotation angle.');
  5085. }
  5086. this._pagesRotation = rotation;
  5087. if (!this.pdfDocument) {
  5088. return;
  5089. }
  5090. for (var i = 0, l = this._pages.length; i < l; i++) {
  5091. var pageView = this._pages[i];
  5092. pageView.update(pageView.scale, rotation);
  5093. }
  5094. this._setScale(this._currentScaleValue, true);
  5095. if (this.defaultRenderingQueue) {
  5096. this.update();
  5097. }
  5098. },
  5099. setDocument: function (pdfDocument) {
  5100. if (this.pdfDocument) {
  5101. this._cancelRendering();
  5102. this._resetView();
  5103. }
  5104. this.pdfDocument = pdfDocument;
  5105. if (!pdfDocument) {
  5106. return;
  5107. }
  5108. var pagesCount = pdfDocument.numPages;
  5109. var self = this;
  5110. var resolvePagesPromise;
  5111. var pagesPromise = new Promise(function (resolve) {
  5112. resolvePagesPromise = resolve;
  5113. });
  5114. this.pagesPromise = pagesPromise;
  5115. pagesPromise.then(function () {
  5116. self._pageViewsReady = true;
  5117. self.eventBus.dispatch('pagesloaded', {
  5118. source: self,
  5119. pagesCount: pagesCount
  5120. });
  5121. });
  5122. var isOnePageRenderedResolved = false;
  5123. var resolveOnePageRendered = null;
  5124. var onePageRendered = new Promise(function (resolve) {
  5125. resolveOnePageRendered = resolve;
  5126. });
  5127. this.onePageRendered = onePageRendered;
  5128. var bindOnAfterAndBeforeDraw = function (pageView) {
  5129. pageView.onBeforeDraw = function pdfViewLoadOnBeforeDraw() {
  5130. self._buffer.push(this);
  5131. };
  5132. pageView.onAfterDraw = function pdfViewLoadOnAfterDraw() {
  5133. if (!isOnePageRenderedResolved) {
  5134. isOnePageRenderedResolved = true;
  5135. resolveOnePageRendered();
  5136. }
  5137. };
  5138. };
  5139. var firstPagePromise = pdfDocument.getPage(1);
  5140. this.firstPagePromise = firstPagePromise;
  5141. return firstPagePromise.then(function (pdfPage) {
  5142. var scale = this.currentScale;
  5143. var viewport = pdfPage.getViewport(scale * CSS_UNITS);
  5144. for (var pageNum = 1; pageNum <= pagesCount; ++pageNum) {
  5145. var textLayerFactory = null;
  5146. if (!pdfjsLib.PDFJS.disableTextLayer) {
  5147. textLayerFactory = this;
  5148. }
  5149. var pageView = new PDFPageView({
  5150. container: this.viewer,
  5151. eventBus: this.eventBus,
  5152. id: pageNum,
  5153. scale: scale,
  5154. defaultViewport: viewport.clone(),
  5155. renderingQueue: this.renderingQueue,
  5156. textLayerFactory: textLayerFactory,
  5157. annotationLayerFactory: this,
  5158. enhanceTextSelection: this.enhanceTextSelection,
  5159. renderInteractiveForms: this.renderInteractiveForms,
  5160. renderer: this.renderer
  5161. });
  5162. bindOnAfterAndBeforeDraw(pageView);
  5163. this._pages.push(pageView);
  5164. }
  5165. var linkService = this.linkService;
  5166. onePageRendered.then(function () {
  5167. if (!pdfjsLib.PDFJS.disableAutoFetch) {
  5168. var getPagesLeft = pagesCount;
  5169. for (var pageNum = 1; pageNum <= pagesCount; ++pageNum) {
  5170. pdfDocument.getPage(pageNum).then(function (pageNum, pdfPage) {
  5171. var pageView = self._pages[pageNum - 1];
  5172. if (!pageView.pdfPage) {
  5173. pageView.setPdfPage(pdfPage);
  5174. }
  5175. linkService.cachePageRef(pageNum, pdfPage.ref);
  5176. getPagesLeft--;
  5177. if (!getPagesLeft) {
  5178. resolvePagesPromise();
  5179. }
  5180. }.bind(null, pageNum));
  5181. }
  5182. } else {
  5183. resolvePagesPromise();
  5184. }
  5185. });
  5186. self.eventBus.dispatch('pagesinit', { source: self });
  5187. if (this.defaultRenderingQueue) {
  5188. this.update();
  5189. }
  5190. if (this.findController) {
  5191. this.findController.resolveFirstPage();
  5192. }
  5193. }.bind(this));
  5194. },
  5195. setPageLabels: function PDFViewer_setPageLabels(labels) {
  5196. if (!this.pdfDocument) {
  5197. return;
  5198. }
  5199. if (!labels) {
  5200. this._pageLabels = null;
  5201. } else if (!(labels instanceof Array && this.pdfDocument.numPages === labels.length)) {
  5202. this._pageLabels = null;
  5203. console.error('PDFViewer_setPageLabels: Invalid page labels.');
  5204. } else {
  5205. this._pageLabels = labels;
  5206. }
  5207. for (var i = 0, ii = this._pages.length; i < ii; i++) {
  5208. var pageView = this._pages[i];
  5209. var label = this._pageLabels && this._pageLabels[i];
  5210. pageView.setPageLabel(label);
  5211. }
  5212. },
  5213. _resetView: function () {
  5214. this._pages = [];
  5215. this._currentPageNumber = 1;
  5216. this._currentScale = UNKNOWN_SCALE;
  5217. this._currentScaleValue = null;
  5218. this._pageLabels = null;
  5219. this._buffer = new PDFPageViewBuffer(DEFAULT_CACHE_SIZE);
  5220. this._location = null;
  5221. this._pagesRotation = 0;
  5222. this._pagesRequests = [];
  5223. this._pageViewsReady = false;
  5224. this.viewer.textContent = '';
  5225. },
  5226. _scrollUpdate: function PDFViewer_scrollUpdate() {
  5227. if (this.pagesCount === 0) {
  5228. return;
  5229. }
  5230. this.update();
  5231. for (var i = 0, ii = this._pages.length; i < ii; i++) {
  5232. this._pages[i].updatePosition();
  5233. }
  5234. },
  5235. _setScaleDispatchEvent: function pdfViewer_setScaleDispatchEvent(newScale, newValue, preset) {
  5236. var arg = {
  5237. source: this,
  5238. scale: newScale,
  5239. presetValue: preset ? newValue : undefined
  5240. };
  5241. this.eventBus.dispatch('scalechanging', arg);
  5242. this.eventBus.dispatch('scalechange', arg);
  5243. },
  5244. _setScaleUpdatePages: function pdfViewer_setScaleUpdatePages(newScale, newValue, noScroll, preset) {
  5245. this._currentScaleValue = newValue.toString();
  5246. if (isSameScale(this._currentScale, newScale)) {
  5247. if (preset) {
  5248. this._setScaleDispatchEvent(newScale, newValue, true);
  5249. }
  5250. return;
  5251. }
  5252. for (var i = 0, ii = this._pages.length; i < ii; i++) {
  5253. this._pages[i].update(newScale);
  5254. }
  5255. this._currentScale = newScale;
  5256. if (!noScroll) {
  5257. var page = this._currentPageNumber, dest;
  5258. if (this._location && !pdfjsLib.PDFJS.ignoreCurrentPositionOnZoom && !(this.isInPresentationMode || this.isChangingPresentationMode)) {
  5259. page = this._location.pageNumber;
  5260. dest = [
  5261. null,
  5262. { name: 'XYZ' },
  5263. this._location.left,
  5264. this._location.top,
  5265. null
  5266. ];
  5267. }
  5268. this.scrollPageIntoView({
  5269. pageNumber: page,
  5270. destArray: dest,
  5271. allowNegativeOffset: true
  5272. });
  5273. }
  5274. this._setScaleDispatchEvent(newScale, newValue, preset);
  5275. if (this.defaultRenderingQueue) {
  5276. this.update();
  5277. }
  5278. },
  5279. _setScale: function PDFViewer_setScale(value, noScroll) {
  5280. var scale = parseFloat(value);
  5281. if (scale > 0) {
  5282. this._setScaleUpdatePages(scale, value, noScroll, false);
  5283. } else {
  5284. var currentPage = this._pages[this._currentPageNumber - 1];
  5285. if (!currentPage) {
  5286. return;
  5287. }
  5288. var hPadding = this.isInPresentationMode || this.removePageBorders ? 0 : SCROLLBAR_PADDING;
  5289. var vPadding = this.isInPresentationMode || this.removePageBorders ? 0 : VERTICAL_PADDING;
  5290. var pageWidthScale = (this.container.clientWidth - hPadding) / currentPage.width * currentPage.scale;
  5291. var pageHeightScale = (this.container.clientHeight - vPadding) / currentPage.height * currentPage.scale;
  5292. switch (value) {
  5293. case 'page-actual':
  5294. scale = 1;
  5295. break;
  5296. case 'page-width':
  5297. scale = pageWidthScale;
  5298. break;
  5299. case 'page-height':
  5300. scale = pageHeightScale;
  5301. break;
  5302. case 'page-fit':
  5303. scale = Math.min(pageWidthScale, pageHeightScale);
  5304. break;
  5305. case 'auto':
  5306. var isLandscape = currentPage.width > currentPage.height;
  5307. var horizontalScale = isLandscape ? Math.min(pageHeightScale, pageWidthScale) : pageWidthScale;
  5308. scale = Math.min(MAX_AUTO_SCALE, horizontalScale);
  5309. break;
  5310. default:
  5311. console.error('PDFViewer_setScale: "' + value + '" is an unknown zoom value.');
  5312. return;
  5313. }
  5314. this._setScaleUpdatePages(scale, value, noScroll, true);
  5315. }
  5316. },
  5317. _resetCurrentPageView: function () {
  5318. if (this.isInPresentationMode) {
  5319. this._setScale(this._currentScaleValue, true);
  5320. }
  5321. var pageView = this._pages[this._currentPageNumber - 1];
  5322. scrollIntoView(pageView.div);
  5323. },
  5324. scrollPageIntoView: function PDFViewer_scrollPageIntoView(params) {
  5325. if (!this.pdfDocument) {
  5326. return;
  5327. }
  5328. if (arguments.length > 1 || typeof params === 'number') {
  5329. console.warn('Call of scrollPageIntoView() with obsolete signature.');
  5330. var paramObj = {};
  5331. if (typeof params === 'number') {
  5332. paramObj.pageNumber = params;
  5333. }
  5334. if (arguments[1] instanceof Array) {
  5335. paramObj.destArray = arguments[1];
  5336. }
  5337. params = paramObj;
  5338. }
  5339. var pageNumber = params.pageNumber || 0;
  5340. var dest = params.destArray || null;
  5341. var allowNegativeOffset = params.allowNegativeOffset || false;
  5342. if (this.isInPresentationMode || !dest) {
  5343. this._setCurrentPageNumber(pageNumber, true);
  5344. return;
  5345. }
  5346. var pageView = this._pages[pageNumber - 1];
  5347. if (!pageView) {
  5348. console.error('PDFViewer_scrollPageIntoView: ' + 'Invalid "pageNumber" parameter.');
  5349. return;
  5350. }
  5351. var x = 0, y = 0;
  5352. var width = 0, height = 0, widthScale, heightScale;
  5353. var changeOrientation = pageView.rotation % 180 === 0 ? false : true;
  5354. var pageWidth = (changeOrientation ? pageView.height : pageView.width) / pageView.scale / CSS_UNITS;
  5355. var pageHeight = (changeOrientation ? pageView.width : pageView.height) / pageView.scale / CSS_UNITS;
  5356. var scale = 0;
  5357. switch (dest[1].name) {
  5358. case 'XYZ':
  5359. x = dest[2];
  5360. y = dest[3];
  5361. scale = dest[4];
  5362. x = x !== null ? x : 0;
  5363. y = y !== null ? y : pageHeight;
  5364. break;
  5365. case 'Fit':
  5366. case 'FitB':
  5367. scale = 'page-fit';
  5368. break;
  5369. case 'FitH':
  5370. case 'FitBH':
  5371. y = dest[2];
  5372. scale = 'page-width';
  5373. if (y === null && this._location) {
  5374. x = this._location.left;
  5375. y = this._location.top;
  5376. }
  5377. break;
  5378. case 'FitV':
  5379. case 'FitBV':
  5380. x = dest[2];
  5381. width = pageWidth;
  5382. height = pageHeight;
  5383. scale = 'page-height';
  5384. break;
  5385. case 'FitR':
  5386. x = dest[2];
  5387. y = dest[3];
  5388. width = dest[4] - x;
  5389. height = dest[5] - y;
  5390. var hPadding = this.removePageBorders ? 0 : SCROLLBAR_PADDING;
  5391. var vPadding = this.removePageBorders ? 0 : VERTICAL_PADDING;
  5392. widthScale = (this.container.clientWidth - hPadding) / width / CSS_UNITS;
  5393. heightScale = (this.container.clientHeight - vPadding) / height / CSS_UNITS;
  5394. scale = Math.min(Math.abs(widthScale), Math.abs(heightScale));
  5395. break;
  5396. default:
  5397. console.error('PDFViewer_scrollPageIntoView: \'' + dest[1].name + '\' is not a valid destination type.');
  5398. return;
  5399. }
  5400. if (scale && scale !== this._currentScale) {
  5401. this.currentScaleValue = scale;
  5402. } else if (this._currentScale === UNKNOWN_SCALE) {
  5403. this.currentScaleValue = DEFAULT_SCALE_VALUE;
  5404. }
  5405. if (scale === 'page-fit' && !dest[4]) {
  5406. scrollIntoView(pageView.div);
  5407. return;
  5408. }
  5409. var boundingRect = [
  5410. pageView.viewport.convertToViewportPoint(x, y),
  5411. pageView.viewport.convertToViewportPoint(x + width, y + height)
  5412. ];
  5413. var left = Math.min(boundingRect[0][0], boundingRect[1][0]);
  5414. var top = Math.min(boundingRect[0][1], boundingRect[1][1]);
  5415. if (!allowNegativeOffset) {
  5416. left = Math.max(left, 0);
  5417. top = Math.max(top, 0);
  5418. }
  5419. scrollIntoView(pageView.div, {
  5420. left: left,
  5421. top: top
  5422. });
  5423. },
  5424. _updateLocation: function (firstPage) {
  5425. var currentScale = this._currentScale;
  5426. var currentScaleValue = this._currentScaleValue;
  5427. var normalizedScaleValue = parseFloat(currentScaleValue) === currentScale ? Math.round(currentScale * 10000) / 100 : currentScaleValue;
  5428. var pageNumber = firstPage.id;
  5429. var pdfOpenParams = '#page=' + pageNumber;
  5430. pdfOpenParams += '&zoom=' + normalizedScaleValue;
  5431. var currentPageView = this._pages[pageNumber - 1];
  5432. var container = this.container;
  5433. var topLeft = currentPageView.getPagePoint(container.scrollLeft - firstPage.x, container.scrollTop - firstPage.y);
  5434. var intLeft = Math.round(topLeft[0]);
  5435. var intTop = Math.round(topLeft[1]);
  5436. pdfOpenParams += ',' + intLeft + ',' + intTop;
  5437. this._location = {
  5438. pageNumber: pageNumber,
  5439. scale: normalizedScaleValue,
  5440. top: intTop,
  5441. left: intLeft,
  5442. pdfOpenParams: pdfOpenParams
  5443. };
  5444. },
  5445. update: function PDFViewer_update() {
  5446. var visible = this._getVisiblePages();
  5447. var visiblePages = visible.views;
  5448. if (visiblePages.length === 0) {
  5449. return;
  5450. }
  5451. var suggestedCacheSize = Math.max(DEFAULT_CACHE_SIZE, 2 * visiblePages.length + 1);
  5452. this._buffer.resize(suggestedCacheSize);
  5453. this.renderingQueue.renderHighestPriority(visible);
  5454. var currentId = this._currentPageNumber;
  5455. var firstPage = visible.first;
  5456. for (var i = 0, ii = visiblePages.length, stillFullyVisible = false; i < ii; ++i) {
  5457. var page = visiblePages[i];
  5458. if (page.percent < 100) {
  5459. break;
  5460. }
  5461. if (page.id === currentId) {
  5462. stillFullyVisible = true;
  5463. break;
  5464. }
  5465. }
  5466. if (!stillFullyVisible) {
  5467. currentId = visiblePages[0].id;
  5468. }
  5469. if (!this.isInPresentationMode) {
  5470. this._setCurrentPageNumber(currentId);
  5471. }
  5472. this._updateLocation(firstPage);
  5473. this.eventBus.dispatch('updateviewarea', {
  5474. source: this,
  5475. location: this._location
  5476. });
  5477. },
  5478. containsElement: function (element) {
  5479. return this.container.contains(element);
  5480. },
  5481. focus: function () {
  5482. this.container.focus();
  5483. },
  5484. get isInPresentationMode() {
  5485. return this.presentationModeState === PresentationModeState.FULLSCREEN;
  5486. },
  5487. get isChangingPresentationMode() {
  5488. return this.presentationModeState === PresentationModeState.CHANGING;
  5489. },
  5490. get isHorizontalScrollbarEnabled() {
  5491. return this.isInPresentationMode ? false : this.container.scrollWidth > this.container.clientWidth;
  5492. },
  5493. _getVisiblePages: function () {
  5494. if (!this.isInPresentationMode) {
  5495. return getVisibleElements(this.container, this._pages, true);
  5496. }
  5497. var visible = [];
  5498. var currentPage = this._pages[this._currentPageNumber - 1];
  5499. visible.push({
  5500. id: currentPage.id,
  5501. view: currentPage
  5502. });
  5503. return {
  5504. first: currentPage,
  5505. last: currentPage,
  5506. views: visible
  5507. };
  5508. },
  5509. cleanup: function () {
  5510. for (var i = 0, ii = this._pages.length; i < ii; i++) {
  5511. if (this._pages[i] && this._pages[i].renderingState !== RenderingStates.FINISHED) {
  5512. this._pages[i].reset();
  5513. }
  5514. }
  5515. },
  5516. _cancelRendering: function PDFViewer_cancelRendering() {
  5517. for (var i = 0, ii = this._pages.length; i < ii; i++) {
  5518. if (this._pages[i]) {
  5519. this._pages[i].cancelRendering();
  5520. }
  5521. }
  5522. },
  5523. _ensurePdfPageLoaded: function (pageView) {
  5524. if (pageView.pdfPage) {
  5525. return Promise.resolve(pageView.pdfPage);
  5526. }
  5527. var pageNumber = pageView.id;
  5528. if (this._pagesRequests[pageNumber]) {
  5529. return this._pagesRequests[pageNumber];
  5530. }
  5531. var promise = this.pdfDocument.getPage(pageNumber).then(function (pdfPage) {
  5532. pageView.setPdfPage(pdfPage);
  5533. this._pagesRequests[pageNumber] = null;
  5534. return pdfPage;
  5535. }.bind(this));
  5536. this._pagesRequests[pageNumber] = promise;
  5537. return promise;
  5538. },
  5539. forceRendering: function (currentlyVisiblePages) {
  5540. var visiblePages = currentlyVisiblePages || this._getVisiblePages();
  5541. var pageView = this.renderingQueue.getHighestPriority(visiblePages, this._pages, this.scroll.down);
  5542. if (pageView) {
  5543. this._ensurePdfPageLoaded(pageView).then(function () {
  5544. this.renderingQueue.renderView(pageView);
  5545. }.bind(this));
  5546. return true;
  5547. }
  5548. return false;
  5549. },
  5550. getPageTextContent: function (pageIndex) {
  5551. return this.pdfDocument.getPage(pageIndex + 1).then(function (page) {
  5552. return page.getTextContent({ normalizeWhitespace: true });
  5553. });
  5554. },
  5555. createTextLayerBuilder: function (textLayerDiv, pageIndex, viewport, enhanceTextSelection) {
  5556. return new TextLayerBuilder({
  5557. textLayerDiv: textLayerDiv,
  5558. eventBus: this.eventBus,
  5559. pageIndex: pageIndex,
  5560. viewport: viewport,
  5561. findController: this.isInPresentationMode ? null : this.findController,
  5562. enhanceTextSelection: this.isInPresentationMode ? false : enhanceTextSelection
  5563. });
  5564. },
  5565. createAnnotationLayerBuilder: function (pageDiv, pdfPage, renderInteractiveForms) {
  5566. return new AnnotationLayerBuilder({
  5567. pageDiv: pageDiv,
  5568. pdfPage: pdfPage,
  5569. renderInteractiveForms: renderInteractiveForms,
  5570. linkService: this.linkService,
  5571. downloadManager: this.downloadManager
  5572. });
  5573. },
  5574. setFindController: function (findController) {
  5575. this.findController = findController;
  5576. },
  5577. getPagesOverview: function () {
  5578. return this._pages.map(function (pageView) {
  5579. var viewport = pageView.pdfPage.getViewport(1);
  5580. return {
  5581. width: viewport.width,
  5582. height: viewport.height
  5583. };
  5584. });
  5585. }
  5586. };
  5587. return PDFViewer;
  5588. }();
  5589. exports.PresentationModeState = PresentationModeState;
  5590. exports.PDFViewer = PDFViewer;
  5591. }));
  5592. (function (root, factory) {
  5593. factory(root.pdfjsWebApp = {}, root.pdfjsWebUIUtils, root.pdfjsWebDownloadManager, root.pdfjsWebPDFHistory, root.pdfjsWebPreferences, root.pdfjsWebPDFSidebar, root.pdfjsWebViewHistory, root.pdfjsWebPDFThumbnailViewer, root.pdfjsWebToolbar, root.pdfjsWebSecondaryToolbar, root.pdfjsWebPasswordPrompt, root.pdfjsWebPDFPresentationMode, root.pdfjsWebPDFDocumentProperties, root.pdfjsWebHandTool, root.pdfjsWebPDFViewer, root.pdfjsWebPDFRenderingQueue, root.pdfjsWebPDFLinkService, root.pdfjsWebPDFOutlineViewer, root.pdfjsWebOverlayManager, root.pdfjsWebPDFAttachmentViewer, root.pdfjsWebPDFFindController, root.pdfjsWebPDFFindBar, root.pdfjsWebDOMEvents, root.pdfjsWebPDFJS);
  5594. }(this, function (exports, uiUtilsLib, downloadManagerLib, pdfHistoryLib, preferencesLib, pdfSidebarLib, viewHistoryLib, pdfThumbnailViewerLib, toolbarLib, secondaryToolbarLib, passwordPromptLib, pdfPresentationModeLib, pdfDocumentPropertiesLib, handToolLib, pdfViewerLib, pdfRenderingQueueLib, pdfLinkServiceLib, pdfOutlineViewerLib, overlayManagerLib, pdfAttachmentViewerLib, pdfFindControllerLib, pdfFindBarLib, domEventsLib, pdfjsLib) {
  5595. var UNKNOWN_SCALE = uiUtilsLib.UNKNOWN_SCALE;
  5596. var DEFAULT_SCALE_VALUE = uiUtilsLib.DEFAULT_SCALE_VALUE;
  5597. var MIN_SCALE = uiUtilsLib.MIN_SCALE;
  5598. var MAX_SCALE = uiUtilsLib.MAX_SCALE;
  5599. var ProgressBar = uiUtilsLib.ProgressBar;
  5600. var getPDFFileNameFromURL = uiUtilsLib.getPDFFileNameFromURL;
  5601. var noContextMenuHandler = uiUtilsLib.noContextMenuHandler;
  5602. var mozL10n = uiUtilsLib.mozL10n;
  5603. var parseQueryString = uiUtilsLib.parseQueryString;
  5604. var PDFHistory = pdfHistoryLib.PDFHistory;
  5605. var Preferences = preferencesLib.Preferences;
  5606. var SidebarView = pdfSidebarLib.SidebarView;
  5607. var PDFSidebar = pdfSidebarLib.PDFSidebar;
  5608. var ViewHistory = viewHistoryLib.ViewHistory;
  5609. var PDFThumbnailViewer = pdfThumbnailViewerLib.PDFThumbnailViewer;
  5610. var Toolbar = toolbarLib.Toolbar;
  5611. var SecondaryToolbar = secondaryToolbarLib.SecondaryToolbar;
  5612. var PasswordPrompt = passwordPromptLib.PasswordPrompt;
  5613. var PDFPresentationMode = pdfPresentationModeLib.PDFPresentationMode;
  5614. var PDFDocumentProperties = pdfDocumentPropertiesLib.PDFDocumentProperties;
  5615. var HandTool = handToolLib.HandTool;
  5616. var PresentationModeState = pdfViewerLib.PresentationModeState;
  5617. var PDFViewer = pdfViewerLib.PDFViewer;
  5618. var RenderingStates = pdfRenderingQueueLib.RenderingStates;
  5619. var PDFRenderingQueue = pdfRenderingQueueLib.PDFRenderingQueue;
  5620. var PDFLinkService = pdfLinkServiceLib.PDFLinkService;
  5621. var PDFOutlineViewer = pdfOutlineViewerLib.PDFOutlineViewer;
  5622. var OverlayManager = overlayManagerLib.OverlayManager;
  5623. var PDFAttachmentViewer = pdfAttachmentViewerLib.PDFAttachmentViewer;
  5624. var PDFFindController = pdfFindControllerLib.PDFFindController;
  5625. var PDFFindBar = pdfFindBarLib.PDFFindBar;
  5626. var getGlobalEventBus = domEventsLib.getGlobalEventBus;
  5627. var normalizeWheelEventDelta = uiUtilsLib.normalizeWheelEventDelta;
  5628. var animationStarted = uiUtilsLib.animationStarted;
  5629. var localized = uiUtilsLib.localized;
  5630. var RendererType = uiUtilsLib.RendererType;
  5631. var DEFAULT_SCALE_DELTA = 1.1;
  5632. var DISABLE_AUTO_FETCH_LOADING_BAR_TIMEOUT = 5000;
  5633. function configure(PDFJS) {
  5634. PDFJS.imageResourcesPath = './images/';
  5635. PDFJS.workerSrc = '../build/pdf.worker.js';
  5636. PDFJS.cMapUrl = '../web/cmaps/';
  5637. PDFJS.cMapPacked = true;
  5638. }
  5639. var DefaultExernalServices = {
  5640. updateFindControlState: function (data) {
  5641. },
  5642. initPassiveLoading: function (callbacks) {
  5643. },
  5644. fallback: function (data, callback) {
  5645. },
  5646. reportTelemetry: function (data) {
  5647. },
  5648. createDownloadManager: function () {
  5649. return new downloadManagerLib.DownloadManager();
  5650. },
  5651. supportsIntegratedFind: false,
  5652. supportsDocumentFonts: true,
  5653. supportsDocumentColors: true,
  5654. supportedMouseWheelZoomModifierKeys: {
  5655. ctrlKey: true,
  5656. metaKey: true
  5657. }
  5658. };
  5659. var PDFViewerApplication = {
  5660. initialBookmark: document.location.hash.substring(1),
  5661. initialDestination: null,
  5662. initialized: false,
  5663. fellback: false,
  5664. appConfig: null,
  5665. pdfDocument: null,
  5666. pdfLoadingTask: null,
  5667. printService: null,
  5668. pdfViewer: null,
  5669. pdfThumbnailViewer: null,
  5670. pdfRenderingQueue: null,
  5671. pdfPresentationMode: null,
  5672. pdfDocumentProperties: null,
  5673. pdfLinkService: null,
  5674. pdfHistory: null,
  5675. pdfSidebar: null,
  5676. pdfOutlineViewer: null,
  5677. pdfAttachmentViewer: null,
  5678. store: null,
  5679. downloadManager: null,
  5680. toolbar: null,
  5681. secondaryToolbar: null,
  5682. eventBus: null,
  5683. pageRotation: 0,
  5684. isInitialViewSet: false,
  5685. viewerPrefs: {
  5686. sidebarViewOnLoad: SidebarView.NONE,
  5687. pdfBugEnabled: false,
  5688. showPreviousViewOnLoad: true,
  5689. defaultZoomValue: '',
  5690. disablePageLabels: false,
  5691. renderer: 'canvas',
  5692. enhanceTextSelection: false,
  5693. renderInteractiveForms: false
  5694. },
  5695. isViewerEmbedded: window.parent !== window,
  5696. url: '',
  5697. baseUrl: '',
  5698. externalServices: DefaultExernalServices,
  5699. initialize: function pdfViewInitialize(appConfig) {
  5700. var self = this;
  5701. var PDFJS = pdfjsLib.PDFJS;
  5702. Preferences.initialize();
  5703. this.preferences = Preferences;
  5704. configure(PDFJS);
  5705. this.appConfig = appConfig;
  5706. return this._readPreferences().then(function () {
  5707. return self._initializeViewerComponents();
  5708. }).then(function () {
  5709. self.bindEvents();
  5710. self.bindWindowEvents();
  5711. localized.then(function () {
  5712. self.eventBus.dispatch('localized');
  5713. });
  5714. if (self.isViewerEmbedded && !PDFJS.isExternalLinkTargetSet()) {
  5715. PDFJS.externalLinkTarget = PDFJS.LinkTarget.TOP;
  5716. }
  5717. self.initialized = true;
  5718. });
  5719. },
  5720. _readPreferences: function () {
  5721. var self = this;
  5722. var PDFJS = pdfjsLib.PDFJS;
  5723. return Promise.all([
  5724. Preferences.get('enableWebGL').then(function resolved(value) {
  5725. PDFJS.disableWebGL = !value;
  5726. }),
  5727. Preferences.get('sidebarViewOnLoad').then(function resolved(value) {
  5728. self.viewerPrefs['sidebarViewOnLoad'] = value;
  5729. }),
  5730. Preferences.get('pdfBugEnabled').then(function resolved(value) {
  5731. self.viewerPrefs['pdfBugEnabled'] = value;
  5732. }),
  5733. Preferences.get('showPreviousViewOnLoad').then(function resolved(value) {
  5734. self.viewerPrefs['showPreviousViewOnLoad'] = value;
  5735. }),
  5736. Preferences.get('defaultZoomValue').then(function resolved(value) {
  5737. self.viewerPrefs['defaultZoomValue'] = value;
  5738. }),
  5739. Preferences.get('enhanceTextSelection').then(function resolved(value) {
  5740. self.viewerPrefs['enhanceTextSelection'] = value;
  5741. }),
  5742. Preferences.get('disableTextLayer').then(function resolved(value) {
  5743. if (PDFJS.disableTextLayer === true) {
  5744. return;
  5745. }
  5746. PDFJS.disableTextLayer = value;
  5747. }),
  5748. Preferences.get('disableRange').then(function resolved(value) {
  5749. if (PDFJS.disableRange === true) {
  5750. return;
  5751. }
  5752. PDFJS.disableRange = value;
  5753. }),
  5754. Preferences.get('disableStream').then(function resolved(value) {
  5755. if (PDFJS.disableStream === true) {
  5756. return;
  5757. }
  5758. PDFJS.disableStream = value;
  5759. }),
  5760. Preferences.get('disableAutoFetch').then(function resolved(value) {
  5761. PDFJS.disableAutoFetch = value;
  5762. }),
  5763. Preferences.get('disableFontFace').then(function resolved(value) {
  5764. if (PDFJS.disableFontFace === true) {
  5765. return;
  5766. }
  5767. PDFJS.disableFontFace = value;
  5768. }),
  5769. Preferences.get('useOnlyCssZoom').then(function resolved(value) {
  5770. PDFJS.useOnlyCssZoom = value;
  5771. }),
  5772. Preferences.get('externalLinkTarget').then(function resolved(value) {
  5773. if (PDFJS.isExternalLinkTargetSet()) {
  5774. return;
  5775. }
  5776. PDFJS.externalLinkTarget = value;
  5777. }),
  5778. Preferences.get('renderer').then(function resolved(value) {
  5779. self.viewerPrefs['renderer'] = value;
  5780. }),
  5781. Preferences.get('renderInteractiveForms').then(function resolved(value) {
  5782. self.viewerPrefs['renderInteractiveForms'] = value;
  5783. }),
  5784. Preferences.get('disablePageLabels').then(function resolved(value) {
  5785. self.viewerPrefs['disablePageLabels'] = value;
  5786. })
  5787. ]).catch(function (reason) {
  5788. });
  5789. },
  5790. _initializeViewerComponents: function () {
  5791. var self = this;
  5792. var appConfig = this.appConfig;
  5793. return new Promise(function (resolve, reject) {
  5794. var eventBus = appConfig.eventBus || getGlobalEventBus();
  5795. self.eventBus = eventBus;
  5796. var pdfRenderingQueue = new PDFRenderingQueue();
  5797. pdfRenderingQueue.onIdle = self.cleanup.bind(self);
  5798. self.pdfRenderingQueue = pdfRenderingQueue;
  5799. var pdfLinkService = new PDFLinkService({ eventBus: eventBus });
  5800. self.pdfLinkService = pdfLinkService;
  5801. var downloadManager = self.externalServices.createDownloadManager();
  5802. self.downloadManager = downloadManager;
  5803. var container = appConfig.mainContainer;
  5804. var viewer = appConfig.viewerContainer;
  5805. self.pdfViewer = new PDFViewer({
  5806. container: container,
  5807. viewer: viewer,
  5808. eventBus: eventBus,
  5809. renderingQueue: pdfRenderingQueue,
  5810. linkService: pdfLinkService,
  5811. downloadManager: downloadManager,
  5812. renderer: self.viewerPrefs['renderer'],
  5813. enhanceTextSelection: self.viewerPrefs['enhanceTextSelection'],
  5814. renderInteractiveForms: self.viewerPrefs['renderInteractiveForms']
  5815. });
  5816. pdfRenderingQueue.setViewer(self.pdfViewer);
  5817. pdfLinkService.setViewer(self.pdfViewer);
  5818. var thumbnailContainer = appConfig.sidebar.thumbnailView;
  5819. self.pdfThumbnailViewer = new PDFThumbnailViewer({
  5820. container: thumbnailContainer,
  5821. renderingQueue: pdfRenderingQueue,
  5822. linkService: pdfLinkService
  5823. });
  5824. pdfRenderingQueue.setThumbnailViewer(self.pdfThumbnailViewer);
  5825. self.pdfHistory = new PDFHistory({
  5826. linkService: pdfLinkService,
  5827. eventBus: eventBus
  5828. });
  5829. pdfLinkService.setHistory(self.pdfHistory);
  5830. self.findController = new PDFFindController({ pdfViewer: self.pdfViewer });
  5831. self.findController.onUpdateResultsCount = function (matchCount) {
  5832. if (self.supportsIntegratedFind) {
  5833. return;
  5834. }
  5835. self.findBar.updateResultsCount(matchCount);
  5836. };
  5837. self.findController.onUpdateState = function (state, previous, matchCount) {
  5838. if (self.supportsIntegratedFind) {
  5839. self.externalServices.updateFindControlState({
  5840. result: state,
  5841. findPrevious: previous
  5842. });
  5843. } else {
  5844. self.findBar.updateUIState(state, previous, matchCount);
  5845. }
  5846. };
  5847. self.pdfViewer.setFindController(self.findController);
  5848. var findBarConfig = Object.create(appConfig.findBar);
  5849. findBarConfig.findController = self.findController;
  5850. findBarConfig.eventBus = eventBus;
  5851. self.findBar = new PDFFindBar(findBarConfig);
  5852. self.overlayManager = OverlayManager;
  5853. self.handTool = new HandTool({
  5854. container: container,
  5855. eventBus: eventBus
  5856. });
  5857. self.pdfDocumentProperties = new PDFDocumentProperties(appConfig.documentProperties);
  5858. self.toolbar = new Toolbar(appConfig.toolbar, container, eventBus);
  5859. self.secondaryToolbar = new SecondaryToolbar(appConfig.secondaryToolbar, container, eventBus);
  5860. if (self.supportsFullscreen) {
  5861. self.pdfPresentationMode = new PDFPresentationMode({
  5862. container: container,
  5863. viewer: viewer,
  5864. pdfViewer: self.pdfViewer,
  5865. eventBus: eventBus,
  5866. contextMenuItems: appConfig.fullscreen
  5867. });
  5868. }
  5869. self.passwordPrompt = new PasswordPrompt(appConfig.passwordOverlay);
  5870. self.pdfOutlineViewer = new PDFOutlineViewer({
  5871. container: appConfig.sidebar.outlineView,
  5872. eventBus: eventBus,
  5873. linkService: pdfLinkService
  5874. });
  5875. self.pdfAttachmentViewer = new PDFAttachmentViewer({
  5876. container: appConfig.sidebar.attachmentsView,
  5877. eventBus: eventBus,
  5878. downloadManager: downloadManager
  5879. });
  5880. var sidebarConfig = Object.create(appConfig.sidebar);
  5881. sidebarConfig.pdfViewer = self.pdfViewer;
  5882. sidebarConfig.pdfThumbnailViewer = self.pdfThumbnailViewer;
  5883. sidebarConfig.pdfOutlineViewer = self.pdfOutlineViewer;
  5884. sidebarConfig.eventBus = eventBus;
  5885. self.pdfSidebar = new PDFSidebar(sidebarConfig);
  5886. self.pdfSidebar.onToggled = self.forceRendering.bind(self);
  5887. resolve(undefined);
  5888. });
  5889. },
  5890. run: function pdfViewRun(config) {
  5891. this.initialize(config).then(webViewerInitialized);
  5892. },
  5893. zoomIn: function pdfViewZoomIn(ticks) {
  5894. var newScale = this.pdfViewer.currentScale;
  5895. do {
  5896. newScale = (newScale * DEFAULT_SCALE_DELTA).toFixed(2);
  5897. newScale = Math.ceil(newScale * 10) / 10;
  5898. newScale = Math.min(MAX_SCALE, newScale);
  5899. } while (--ticks > 0 && newScale < MAX_SCALE);
  5900. this.pdfViewer.currentScaleValue = newScale;
  5901. },
  5902. zoomOut: function pdfViewZoomOut(ticks) {
  5903. var newScale = this.pdfViewer.currentScale;
  5904. do {
  5905. newScale = (newScale / DEFAULT_SCALE_DELTA).toFixed(2);
  5906. newScale = Math.floor(newScale * 10) / 10;
  5907. newScale = Math.max(MIN_SCALE, newScale);
  5908. } while (--ticks > 0 && newScale > MIN_SCALE);
  5909. this.pdfViewer.currentScaleValue = newScale;
  5910. },
  5911. get pagesCount() {
  5912. return this.pdfDocument ? this.pdfDocument.numPages : 0;
  5913. },
  5914. set page(val) {
  5915. this.pdfViewer.currentPageNumber = val;
  5916. },
  5917. get page() {
  5918. return this.pdfViewer.currentPageNumber;
  5919. },
  5920. get printing() {
  5921. return !!this.printService;
  5922. },
  5923. get supportsPrinting() {
  5924. return PDFPrintServiceFactory.instance.supportsPrinting;
  5925. },
  5926. get supportsFullscreen() {
  5927. var support;
  5928. var doc = document.documentElement;
  5929. support = !!(doc.requestFullscreen || doc.mozRequestFullScreen || doc.webkitRequestFullScreen || doc.msRequestFullscreen);
  5930. if (document.fullscreenEnabled === false || document.mozFullScreenEnabled === false || document.webkitFullscreenEnabled === false || document.msFullscreenEnabled === false) {
  5931. support = false;
  5932. }
  5933. if (support && pdfjsLib.PDFJS.disableFullscreen === true) {
  5934. support = false;
  5935. }
  5936. return pdfjsLib.shadow(this, 'supportsFullscreen', support);
  5937. },
  5938. get supportsIntegratedFind() {
  5939. return this.externalServices.supportsIntegratedFind;
  5940. },
  5941. get supportsDocumentFonts() {
  5942. return this.externalServices.supportsDocumentFonts;
  5943. },
  5944. get supportsDocumentColors() {
  5945. return this.externalServices.supportsDocumentColors;
  5946. },
  5947. get loadingBar() {
  5948. var bar = new ProgressBar('#loadingBar', {});
  5949. return pdfjsLib.shadow(this, 'loadingBar', bar);
  5950. },
  5951. get supportedMouseWheelZoomModifierKeys() {
  5952. return this.externalServices.supportedMouseWheelZoomModifierKeys;
  5953. },
  5954. initPassiveLoading: function pdfViewInitPassiveLoading() {
  5955. throw new Error('Not implemented: initPassiveLoading');
  5956. },
  5957. setTitleUsingUrl: function pdfViewSetTitleUsingUrl(url) {
  5958. this.url = url;
  5959. this.baseUrl = url.split('#')[0];
  5960. try {
  5961. this.setTitle(decodeURIComponent(pdfjsLib.getFilenameFromUrl(url)) || url);
  5962. } catch (e) {
  5963. this.setTitle(url);
  5964. }
  5965. },
  5966. setTitle: function pdfViewSetTitle(title) {
  5967. if (this.isViewerEmbedded) {
  5968. return;
  5969. }
  5970. document.title = title;
  5971. },
  5972. close: function pdfViewClose() {
  5973. var errorWrapper = this.appConfig.errorWrapper.container;
  5974. errorWrapper.setAttribute('hidden', 'true');
  5975. if (!this.pdfLoadingTask) {
  5976. return Promise.resolve();
  5977. }
  5978. var promise = this.pdfLoadingTask.destroy();
  5979. this.pdfLoadingTask = null;
  5980. if (this.pdfDocument) {
  5981. this.pdfDocument = null;
  5982. this.pdfThumbnailViewer.setDocument(null);
  5983. this.pdfViewer.setDocument(null);
  5984. this.pdfLinkService.setDocument(null, null);
  5985. }
  5986. this.store = null;
  5987. this.isInitialViewSet = false;
  5988. this.pdfSidebar.reset();
  5989. this.pdfOutlineViewer.reset();
  5990. this.pdfAttachmentViewer.reset();
  5991. this.findController.reset();
  5992. this.findBar.reset();
  5993. this.toolbar.reset();
  5994. this.secondaryToolbar.reset();
  5995. if (typeof PDFBug !== 'undefined') {
  5996. PDFBug.cleanup();
  5997. }
  5998. return promise;
  5999. },
  6000. open: function pdfViewOpen(file, args) {
  6001. if (arguments.length > 2 || typeof args === 'number') {
  6002. return Promise.reject(new Error('Call of open() with obsolete signature.'));
  6003. }
  6004. if (this.pdfLoadingTask) {
  6005. return this.close().then(function () {
  6006. Preferences.reload();
  6007. return this.open(file, args);
  6008. }.bind(this));
  6009. }
  6010. var parameters = Object.create(null), scale;
  6011. if (typeof file === 'string') {
  6012. this.setTitleUsingUrl(file);
  6013. parameters.url = file;
  6014. } else if (file && 'byteLength' in file) {
  6015. parameters.data = file;
  6016. } else if (file.url && file.originalUrl) {
  6017. this.setTitleUsingUrl(file.originalUrl);
  6018. parameters.url = file.url;
  6019. }
  6020. if (args) {
  6021. for (var prop in args) {
  6022. parameters[prop] = args[prop];
  6023. }
  6024. if (args.scale) {
  6025. scale = args.scale;
  6026. }
  6027. if (args.length) {
  6028. this.pdfDocumentProperties.setFileSize(args.length);
  6029. }
  6030. }
  6031. var self = this;
  6032. self.downloadComplete = false;
  6033. var loadingTask = pdfjsLib.getDocument(parameters);
  6034. this.pdfLoadingTask = loadingTask;
  6035. loadingTask.onPassword = function passwordNeeded(updateCallback, reason) {
  6036. self.passwordPrompt.setUpdateCallback(updateCallback, reason);
  6037. self.passwordPrompt.open();
  6038. };
  6039. loadingTask.onProgress = function getDocumentProgress(progressData) {
  6040. self.progress(progressData.loaded / progressData.total);
  6041. };
  6042. loadingTask.onUnsupportedFeature = this.fallback.bind(this);
  6043. return loadingTask.promise.then(function getDocumentCallback(pdfDocument) {
  6044. self.load(pdfDocument, scale);
  6045. }, function getDocumentError(exception) {
  6046. var message = exception && exception.message;
  6047. var loadingErrorMessage = mozL10n.get('loading_error', null, 'An error occurred while loading the PDF.');
  6048. if (exception instanceof pdfjsLib.InvalidPDFException) {
  6049. loadingErrorMessage = mozL10n.get('invalid_file_error', null, 'Invalid or corrupted PDF file.');
  6050. } else if (exception instanceof pdfjsLib.MissingPDFException) {
  6051. loadingErrorMessage = mozL10n.get('missing_file_error', null, 'Missing PDF file.');
  6052. } else if (exception instanceof pdfjsLib.UnexpectedResponseException) {
  6053. loadingErrorMessage = mozL10n.get('unexpected_response_error', null, 'Unexpected server response.');
  6054. }
  6055. var moreInfo = { message: message };
  6056. self.error(loadingErrorMessage, moreInfo);
  6057. throw new Error(loadingErrorMessage);
  6058. });
  6059. },
  6060. download: function pdfViewDownload() {
  6061. function downloadByUrl() {
  6062. downloadManager.downloadUrl(url, filename);
  6063. }
  6064. var url = this.baseUrl;
  6065. var filename = getPDFFileNameFromURL(url);
  6066. var downloadManager = this.downloadManager;
  6067. downloadManager.onerror = function (err) {
  6068. PDFViewerApplication.error('PDF failed to download.');
  6069. };
  6070. if (!this.pdfDocument) {
  6071. downloadByUrl();
  6072. return;
  6073. }
  6074. if (!this.downloadComplete) {
  6075. downloadByUrl();
  6076. return;
  6077. }
  6078. this.pdfDocument.getData().then(function getDataSuccess(data) {
  6079. var blob = pdfjsLib.createBlob(data, 'application/pdf');
  6080. downloadManager.download(blob, url, filename);
  6081. }, downloadByUrl).then(null, downloadByUrl);
  6082. },
  6083. fallback: function pdfViewFallback(featureId) {
  6084. },
  6085. error: function pdfViewError(message, moreInfo) {
  6086. var moreInfoText = mozL10n.get('error_version_info', {
  6087. version: pdfjsLib.version || '?',
  6088. build: pdfjsLib.build || '?'
  6089. }, 'PDF.js v{{version}} (build: {{build}})') + '\n';
  6090. if (moreInfo) {
  6091. moreInfoText += mozL10n.get('error_message', { message: moreInfo.message }, 'Message: {{message}}');
  6092. if (moreInfo.stack) {
  6093. moreInfoText += '\n' + mozL10n.get('error_stack', { stack: moreInfo.stack }, 'Stack: {{stack}}');
  6094. } else {
  6095. if (moreInfo.filename) {
  6096. moreInfoText += '\n' + mozL10n.get('error_file', { file: moreInfo.filename }, 'File: {{file}}');
  6097. }
  6098. if (moreInfo.lineNumber) {
  6099. moreInfoText += '\n' + mozL10n.get('error_line', { line: moreInfo.lineNumber }, 'Line: {{line}}');
  6100. }
  6101. }
  6102. }
  6103. var errorWrapperConfig = this.appConfig.errorWrapper;
  6104. var errorWrapper = errorWrapperConfig.container;
  6105. errorWrapper.removeAttribute('hidden');
  6106. var errorMessage = errorWrapperConfig.errorMessage;
  6107. errorMessage.textContent = message;
  6108. var closeButton = errorWrapperConfig.closeButton;
  6109. closeButton.onclick = function () {
  6110. errorWrapper.setAttribute('hidden', 'true');
  6111. };
  6112. var errorMoreInfo = errorWrapperConfig.errorMoreInfo;
  6113. var moreInfoButton = errorWrapperConfig.moreInfoButton;
  6114. var lessInfoButton = errorWrapperConfig.lessInfoButton;
  6115. moreInfoButton.onclick = function () {
  6116. errorMoreInfo.removeAttribute('hidden');
  6117. moreInfoButton.setAttribute('hidden', 'true');
  6118. lessInfoButton.removeAttribute('hidden');
  6119. errorMoreInfo.style.height = errorMoreInfo.scrollHeight + 'px';
  6120. };
  6121. lessInfoButton.onclick = function () {
  6122. errorMoreInfo.setAttribute('hidden', 'true');
  6123. moreInfoButton.removeAttribute('hidden');
  6124. lessInfoButton.setAttribute('hidden', 'true');
  6125. };
  6126. moreInfoButton.oncontextmenu = noContextMenuHandler;
  6127. lessInfoButton.oncontextmenu = noContextMenuHandler;
  6128. closeButton.oncontextmenu = noContextMenuHandler;
  6129. moreInfoButton.removeAttribute('hidden');
  6130. lessInfoButton.setAttribute('hidden', 'true');
  6131. errorMoreInfo.value = moreInfoText;
  6132. },
  6133. progress: function pdfViewProgress(level) {
  6134. var percent = Math.round(level * 100);
  6135. if (percent > this.loadingBar.percent || isNaN(percent)) {
  6136. this.loadingBar.percent = percent;
  6137. if (pdfjsLib.PDFJS.disableAutoFetch && percent) {
  6138. if (this.disableAutoFetchLoadingBarTimeout) {
  6139. clearTimeout(this.disableAutoFetchLoadingBarTimeout);
  6140. this.disableAutoFetchLoadingBarTimeout = null;
  6141. }
  6142. this.loadingBar.show();
  6143. this.disableAutoFetchLoadingBarTimeout = setTimeout(function () {
  6144. this.loadingBar.hide();
  6145. this.disableAutoFetchLoadingBarTimeout = null;
  6146. }.bind(this), DISABLE_AUTO_FETCH_LOADING_BAR_TIMEOUT);
  6147. }
  6148. }
  6149. },
  6150. load: function pdfViewLoad(pdfDocument, scale) {
  6151. var self = this;
  6152. scale = scale || UNKNOWN_SCALE;
  6153. this.pdfDocument = pdfDocument;
  6154. this.pdfDocumentProperties.setDocumentAndUrl(pdfDocument, this.url);
  6155. var downloadedPromise = pdfDocument.getDownloadInfo().then(function () {
  6156. self.downloadComplete = true;
  6157. self.loadingBar.hide();
  6158. });
  6159. this.toolbar.setPagesCount(pdfDocument.numPages, false);
  6160. this.secondaryToolbar.setPagesCount(pdfDocument.numPages);
  6161. var id = this.documentFingerprint = pdfDocument.fingerprint;
  6162. var store = this.store = new ViewHistory(id);
  6163. var baseDocumentUrl;
  6164. baseDocumentUrl = null;
  6165. this.pdfLinkService.setDocument(pdfDocument, baseDocumentUrl);
  6166. var pdfViewer = this.pdfViewer;
  6167. pdfViewer.currentScale = scale;
  6168. pdfViewer.setDocument(pdfDocument);
  6169. var firstPagePromise = pdfViewer.firstPagePromise;
  6170. var pagesPromise = pdfViewer.pagesPromise;
  6171. var onePageRendered = pdfViewer.onePageRendered;
  6172. this.pageRotation = 0;
  6173. var pdfThumbnailViewer = this.pdfThumbnailViewer;
  6174. pdfThumbnailViewer.setDocument(pdfDocument);
  6175. firstPagePromise.then(function (pdfPage) {
  6176. downloadedPromise.then(function () {
  6177. self.eventBus.dispatch('documentload', { source: self });
  6178. });
  6179. self.loadingBar.setWidth(self.appConfig.viewerContainer);
  6180. if (!pdfjsLib.PDFJS.disableHistory && !self.isViewerEmbedded) {
  6181. if (!self.viewerPrefs['showPreviousViewOnLoad']) {
  6182. self.pdfHistory.clearHistoryState();
  6183. }
  6184. self.pdfHistory.initialize(self.documentFingerprint);
  6185. if (self.pdfHistory.initialDestination) {
  6186. self.initialDestination = self.pdfHistory.initialDestination;
  6187. } else if (self.pdfHistory.initialBookmark) {
  6188. self.initialBookmark = self.pdfHistory.initialBookmark;
  6189. }
  6190. }
  6191. var initialParams = {
  6192. destination: self.initialDestination,
  6193. bookmark: self.initialBookmark,
  6194. hash: null
  6195. };
  6196. store.initializedPromise.then(function resolved() {
  6197. var storedHash = null, sidebarView = null;
  6198. if (self.viewerPrefs['showPreviousViewOnLoad'] && store.get('exists', false)) {
  6199. var pageNum = store.get('page', '1');
  6200. var zoom = self.viewerPrefs['defaultZoomValue'] || store.get('zoom', DEFAULT_SCALE_VALUE);
  6201. var left = store.get('scrollLeft', '0');
  6202. var top = store.get('scrollTop', '0');
  6203. storedHash = 'page=' + pageNum + '&zoom=' + zoom + ',' + left + ',' + top;
  6204. sidebarView = store.get('sidebarView', SidebarView.NONE);
  6205. } else if (self.viewerPrefs['defaultZoomValue']) {
  6206. storedHash = 'page=1&zoom=' + self.viewerPrefs['defaultZoomValue'];
  6207. }
  6208. self.setInitialView(storedHash, {
  6209. scale: scale,
  6210. sidebarView: sidebarView
  6211. });
  6212. initialParams.hash = storedHash;
  6213. if (!self.isViewerEmbedded) {
  6214. self.pdfViewer.focus();
  6215. }
  6216. }, function rejected(reason) {
  6217. console.error(reason);
  6218. self.setInitialView(null, { scale: scale });
  6219. });
  6220. pagesPromise.then(function resolved() {
  6221. if (!initialParams.destination && !initialParams.bookmark && !initialParams.hash) {
  6222. return;
  6223. }
  6224. if (self.hasEqualPageSizes) {
  6225. return;
  6226. }
  6227. self.initialDestination = initialParams.destination;
  6228. self.initialBookmark = initialParams.bookmark;
  6229. self.pdfViewer.currentScaleValue = self.pdfViewer.currentScaleValue;
  6230. self.setInitialView(initialParams.hash);
  6231. });
  6232. });
  6233. pdfDocument.getPageLabels().then(function (labels) {
  6234. if (!labels || self.viewerPrefs['disablePageLabels']) {
  6235. return;
  6236. }
  6237. var i = 0, numLabels = labels.length;
  6238. if (numLabels !== self.pagesCount) {
  6239. console.error('The number of Page Labels does not match ' + 'the number of pages in the document.');
  6240. return;
  6241. }
  6242. while (i < numLabels && labels[i] === (i + 1).toString()) {
  6243. i++;
  6244. }
  6245. if (i === numLabels) {
  6246. return;
  6247. }
  6248. pdfViewer.setPageLabels(labels);
  6249. pdfThumbnailViewer.setPageLabels(labels);
  6250. self.toolbar.setPagesCount(pdfDocument.numPages, true);
  6251. self.toolbar.setPageNumber(pdfViewer.currentPageNumber, pdfViewer.currentPageLabel);
  6252. });
  6253. pagesPromise.then(function () {
  6254. if (self.supportsPrinting) {
  6255. pdfDocument.getJavaScript().then(function (javaScript) {
  6256. if (javaScript.length) {
  6257. console.warn('Warning: JavaScript is not supported');
  6258. self.fallback(pdfjsLib.UNSUPPORTED_FEATURES.javaScript);
  6259. }
  6260. var regex = /\bprint\s*\(/;
  6261. for (var i = 0, ii = javaScript.length; i < ii; i++) {
  6262. var js = javaScript[i];
  6263. if (js && regex.test(js)) {
  6264. setTimeout(function () {
  6265. window.print();
  6266. });
  6267. return;
  6268. }
  6269. }
  6270. });
  6271. }
  6272. });
  6273. Promise.all([
  6274. onePageRendered,
  6275. animationStarted
  6276. ]).then(function () {
  6277. pdfDocument.getOutline().then(function (outline) {
  6278. self.pdfOutlineViewer.render({ outline: outline });
  6279. });
  6280. pdfDocument.getAttachments().then(function (attachments) {
  6281. self.pdfAttachmentViewer.render({ attachments: attachments });
  6282. });
  6283. });
  6284. pdfDocument.getMetadata().then(function (data) {
  6285. var info = data.info, metadata = data.metadata;
  6286. self.documentInfo = info;
  6287. self.metadata = metadata;
  6288. // console.log('PDF ' + pdfDocument.fingerprint + ' [' +
  6289. // info.PDFFormatVersion + ' ' + (info.Producer || '-').trim() + ' / ' +
  6290. // (info.Creator || '-').trim() + ']' + ' (PDF.js: ' + (pdfjsLib.version
  6291. // || '-') + (!pdfjsLib.PDFJS.disableWebGL ? ' [WebGL]' : '') + ')');
  6292. var pdfTitle;
  6293. if (metadata && metadata.has('dc:title')) {
  6294. var title = metadata.get('dc:title');
  6295. if (title !== 'Untitled') {
  6296. pdfTitle = title;
  6297. }
  6298. }
  6299. if (!pdfTitle && info && info['Title']) {
  6300. pdfTitle = info['Title'];
  6301. }
  6302. if (pdfTitle) {
  6303. self.setTitle(pdfTitle + ' - ' + document.title);
  6304. }
  6305. if (info.IsAcroFormPresent) {
  6306. console.warn('Warning: AcroForm/XFA is not supported');
  6307. self.fallback(pdfjsLib.UNSUPPORTED_FEATURES.forms);
  6308. }
  6309. });
  6310. },
  6311. setInitialView: function pdfViewSetInitialView(storedHash, options) {
  6312. var scale = options && options.scale;
  6313. var sidebarView = options && options.sidebarView;
  6314. this.isInitialViewSet = true;
  6315. this.pdfSidebar.setInitialView(this.viewerPrefs['sidebarViewOnLoad'] || sidebarView | 0);
  6316. if (this.initialDestination) {
  6317. this.pdfLinkService.navigateTo(this.initialDestination);
  6318. this.initialDestination = null;
  6319. } else if (this.initialBookmark) {
  6320. this.pdfLinkService.setHash(this.initialBookmark);
  6321. this.pdfHistory.push({ hash: this.initialBookmark }, true);
  6322. this.initialBookmark = null;
  6323. } else if (storedHash) {
  6324. this.pdfLinkService.setHash(storedHash);
  6325. } else if (scale) {
  6326. this.pdfViewer.currentScaleValue = scale;
  6327. this.page = 1;
  6328. }
  6329. this.toolbar.setPageNumber(this.pdfViewer.currentPageNumber, this.pdfViewer.currentPageLabel);
  6330. this.secondaryToolbar.setPageNumber(this.pdfViewer.currentPageNumber);
  6331. if (!this.pdfViewer.currentScaleValue) {
  6332. this.pdfViewer.currentScaleValue = DEFAULT_SCALE_VALUE;
  6333. }
  6334. },
  6335. cleanup: function pdfViewCleanup() {
  6336. if (!this.pdfDocument) {
  6337. return;
  6338. }
  6339. this.pdfViewer.cleanup();
  6340. this.pdfThumbnailViewer.cleanup();
  6341. if (this.pdfViewer.renderer !== RendererType.SVG) {
  6342. this.pdfDocument.cleanup();
  6343. }
  6344. },
  6345. forceRendering: function pdfViewForceRendering() {
  6346. this.pdfRenderingQueue.printing = this.printing;
  6347. this.pdfRenderingQueue.isThumbnailViewEnabled = this.pdfSidebar.isThumbnailViewVisible;
  6348. this.pdfRenderingQueue.renderHighestPriority();
  6349. },
  6350. beforePrint: function pdfViewSetupBeforePrint() {
  6351. if (this.printService) {
  6352. return;
  6353. }
  6354. if (!this.supportsPrinting) {
  6355. var printMessage = mozL10n.get('printing_not_supported', null, 'Warning: Printing is not fully supported by this browser.');
  6356. this.error(printMessage);
  6357. return;
  6358. }
  6359. if (!this.pdfViewer.pageViewsReady) {
  6360. var notReadyMessage = mozL10n.get('printing_not_ready', null, 'Warning: The PDF is not fully loaded for printing.');
  6361. window.alert(notReadyMessage);
  6362. return;
  6363. }
  6364. var pagesOverview = this.pdfViewer.getPagesOverview();
  6365. var printContainer = this.appConfig.printContainer;
  6366. var printService = PDFPrintServiceFactory.instance.createPrintService(this.pdfDocument, pagesOverview, printContainer);
  6367. this.printService = printService;
  6368. this.forceRendering();
  6369. printService.layout();
  6370. },
  6371. get hasEqualPageSizes() {
  6372. var firstPage = this.pdfViewer.getPageView(0);
  6373. for (var i = 1, ii = this.pagesCount; i < ii; ++i) {
  6374. var pageView = this.pdfViewer.getPageView(i);
  6375. if (pageView.width !== firstPage.width || pageView.height !== firstPage.height) {
  6376. return false;
  6377. }
  6378. }
  6379. return true;
  6380. },
  6381. afterPrint: function pdfViewSetupAfterPrint() {
  6382. if (this.printService) {
  6383. this.printService.destroy();
  6384. this.printService = null;
  6385. }
  6386. this.forceRendering();
  6387. },
  6388. rotatePages: function pdfViewRotatePages(delta) {
  6389. var pageNumber = this.page;
  6390. this.pageRotation = (this.pageRotation + 360 + delta) % 360;
  6391. this.pdfViewer.pagesRotation = this.pageRotation;
  6392. this.pdfThumbnailViewer.pagesRotation = this.pageRotation;
  6393. this.forceRendering();
  6394. this.pdfViewer.currentPageNumber = pageNumber;
  6395. },
  6396. requestPresentationMode: function pdfViewRequestPresentationMode() {
  6397. if (!this.pdfPresentationMode) {
  6398. return;
  6399. }
  6400. this.pdfPresentationMode.request();
  6401. },
  6402. bindEvents: function pdfViewBindEvents() {
  6403. var eventBus = this.eventBus;
  6404. eventBus.on('resize', webViewerResize);
  6405. eventBus.on('hashchange', webViewerHashchange);
  6406. eventBus.on('beforeprint', this.beforePrint.bind(this));
  6407. eventBus.on('afterprint', this.afterPrint.bind(this));
  6408. eventBus.on('pagerendered', webViewerPageRendered);
  6409. eventBus.on('textlayerrendered', webViewerTextLayerRendered);
  6410. eventBus.on('updateviewarea', webViewerUpdateViewarea);
  6411. eventBus.on('pagechanging', webViewerPageChanging);
  6412. eventBus.on('scalechanging', webViewerScaleChanging);
  6413. eventBus.on('sidebarviewchanged', webViewerSidebarViewChanged);
  6414. eventBus.on('pagemode', webViewerPageMode);
  6415. eventBus.on('namedaction', webViewerNamedAction);
  6416. eventBus.on('presentationmodechanged', webViewerPresentationModeChanged);
  6417. eventBus.on('presentationmode', webViewerPresentationMode);
  6418. eventBus.on('openfile', webViewerOpenFile);
  6419. eventBus.on('print', webViewerPrint);
  6420. eventBus.on('download', webViewerDownload);
  6421. eventBus.on('firstpage', webViewerFirstPage);
  6422. eventBus.on('lastpage', webViewerLastPage);
  6423. eventBus.on('nextpage', webViewerNextPage);
  6424. eventBus.on('previouspage', webViewerPreviousPage);
  6425. eventBus.on('zoomin', webViewerZoomIn);
  6426. eventBus.on('zoomout', webViewerZoomOut);
  6427. eventBus.on('pagenumberchanged', webViewerPageNumberChanged);
  6428. eventBus.on('scalechanged', webViewerScaleChanged);
  6429. eventBus.on('rotatecw', webViewerRotateCw);
  6430. eventBus.on('rotateccw', webViewerRotateCcw);
  6431. eventBus.on('documentproperties', webViewerDocumentProperties);
  6432. eventBus.on('find', webViewerFind);
  6433. eventBus.on('findfromurlhash', webViewerFindFromUrlHash);
  6434. eventBus.on('fileinputchange', webViewerFileInputChange);
  6435. },
  6436. bindWindowEvents: function pdfViewBindWindowEvents() {
  6437. var eventBus = this.eventBus;
  6438. window.addEventListener('wheel', webViewerWheel);
  6439. window.addEventListener('click', webViewerClick);
  6440. window.addEventListener('keydown', webViewerKeyDown);
  6441. window.addEventListener('resize', function windowResize() {
  6442. eventBus.dispatch('resize');
  6443. });
  6444. window.addEventListener('hashchange', function windowHashChange() {
  6445. eventBus.dispatch('hashchange', { hash: document.location.hash.substring(1) });
  6446. });
  6447. window.addEventListener('beforeprint', function windowBeforePrint() {
  6448. eventBus.dispatch('beforeprint');
  6449. });
  6450. window.addEventListener('afterprint', function windowAfterPrint() {
  6451. eventBus.dispatch('afterprint');
  6452. });
  6453. window.addEventListener('change', function windowChange(evt) {
  6454. var files = evt.target.files;
  6455. if (!files || files.length === 0) {
  6456. return;
  6457. }
  6458. eventBus.dispatch('fileinputchange', { fileInput: evt.target });
  6459. });
  6460. }
  6461. };
  6462. var validateFileURL;
  6463. var HOSTED_VIEWER_ORIGINS = [
  6464. 'null',
  6465. 'http://mozilla.github.io',
  6466. 'https://mozilla.github.io'
  6467. ];
  6468. validateFileURL = function validateFileURL(file) {
  6469. try {
  6470. var viewerOrigin = new URL(window.location.href).origin || 'null';
  6471. if (HOSTED_VIEWER_ORIGINS.indexOf(viewerOrigin) >= 0) {
  6472. return;
  6473. }
  6474. var fileOrigin = new URL(file, window.location.href).origin;
  6475. if (fileOrigin !== viewerOrigin) {
  6476. throw new Error('file origin does not match viewer\'s');
  6477. }
  6478. } catch (e) {
  6479. var message = e && e.message;
  6480. var loadingErrorMessage = mozL10n.get('loading_error', null, 'An error occurred while loading the PDF.');
  6481. var moreInfo = { message: message };
  6482. PDFViewerApplication.error(loadingErrorMessage, moreInfo);
  6483. throw e;
  6484. }
  6485. };
  6486. function loadAndEnablePDFBug(enabledTabs) {
  6487. return new Promise(function (resolve, reject) {
  6488. var appConfig = PDFViewerApplication.appConfig;
  6489. var script = document.createElement('script');
  6490. script.src = appConfig.debuggerScriptPath;
  6491. script.onload = function () {
  6492. PDFBug.enable(enabledTabs);
  6493. PDFBug.init(pdfjsLib, appConfig.mainContainer);
  6494. resolve();
  6495. };
  6496. script.onerror = function () {
  6497. reject(new Error('Cannot load debugger at ' + script.src));
  6498. };
  6499. (document.getElementsByTagName('head')[0] || document.body).appendChild(script);
  6500. });
  6501. }
  6502. function webViewerInitialized() {
  6503. var file;
  6504. var queryString = document.location.search.substring(1);
  6505. var params = parseQueryString(queryString);
  6506. if('file' in params) {
  6507. file = params.file;
  6508. } else {
  6509. return;
  6510. }
  6511. validateFileURL(file);
  6512. var waitForBeforeOpening = [];
  6513. var appConfig = PDFViewerApplication.appConfig;
  6514. var fileInput = document.createElement('input');
  6515. fileInput.id = appConfig.openFileInputName;
  6516. fileInput.className = 'fileInput';
  6517. fileInput.setAttribute('type', 'file');
  6518. fileInput.oncontextmenu = noContextMenuHandler;
  6519. document.body.appendChild(fileInput);
  6520. if (!window.File || !window.FileReader || !window.FileList || !window.Blob) {
  6521. appConfig.toolbar.openFile.setAttribute('hidden', 'true');
  6522. appConfig.secondaryToolbar.openFileButton.setAttribute('hidden', 'true');
  6523. } else {
  6524. fileInput.value = null;
  6525. }
  6526. var PDFJS = pdfjsLib.PDFJS;
  6527. if (PDFViewerApplication.viewerPrefs['pdfBugEnabled']) {
  6528. var hash = document.location.hash.substring(1);
  6529. var hashParams = parseQueryString(hash);
  6530. if ('disableworker' in hashParams) {
  6531. PDFJS.disableWorker = hashParams['disableworker'] === 'true';
  6532. }
  6533. if ('disablerange' in hashParams) {
  6534. PDFJS.disableRange = hashParams['disablerange'] === 'true';
  6535. }
  6536. if ('disablestream' in hashParams) {
  6537. PDFJS.disableStream = hashParams['disablestream'] === 'true';
  6538. }
  6539. if ('disableautofetch' in hashParams) {
  6540. PDFJS.disableAutoFetch = hashParams['disableautofetch'] === 'true';
  6541. }
  6542. if ('disablefontface' in hashParams) {
  6543. PDFJS.disableFontFace = hashParams['disablefontface'] === 'true';
  6544. }
  6545. if ('disablehistory' in hashParams) {
  6546. PDFJS.disableHistory = hashParams['disablehistory'] === 'true';
  6547. }
  6548. if ('webgl' in hashParams) {
  6549. PDFJS.disableWebGL = hashParams['webgl'] !== 'true';
  6550. }
  6551. if ('useonlycsszoom' in hashParams) {
  6552. PDFJS.useOnlyCssZoom = hashParams['useonlycsszoom'] === 'true';
  6553. }
  6554. if ('verbosity' in hashParams) {
  6555. PDFJS.verbosity = hashParams['verbosity'] | 0;
  6556. }
  6557. if ('ignorecurrentpositiononzoom' in hashParams) {
  6558. PDFJS.ignoreCurrentPositionOnZoom = hashParams['ignorecurrentpositiononzoom'] === 'true';
  6559. }
  6560. if ('locale' in hashParams) {
  6561. PDFJS.locale = hashParams['locale'];
  6562. }
  6563. if ('textlayer' in hashParams) {
  6564. switch (hashParams['textlayer']) {
  6565. case 'off':
  6566. PDFJS.disableTextLayer = true;
  6567. break;
  6568. case 'visible':
  6569. case 'shadow':
  6570. case 'hover':
  6571. var viewer = appConfig.viewerContainer;
  6572. viewer.classList.add('textLayer-' + hashParams['textlayer']);
  6573. break;
  6574. }
  6575. }
  6576. if ('pdfbug' in hashParams) {
  6577. PDFJS.pdfBug = true;
  6578. var pdfBug = hashParams['pdfbug'];
  6579. var enabled = pdfBug.split(',');
  6580. waitForBeforeOpening.push(loadAndEnablePDFBug(enabled));
  6581. }
  6582. }
  6583. mozL10n.setLanguage(PDFJS.locale);
  6584. if (!PDFViewerApplication.supportsPrinting) {
  6585. appConfig.toolbar.print.classList.add('hidden');
  6586. appConfig.secondaryToolbar.printButton.classList.add('hidden');
  6587. }
  6588. if (!PDFViewerApplication.supportsFullscreen) {
  6589. appConfig.toolbar.presentationModeButton.classList.add('hidden');
  6590. appConfig.secondaryToolbar.presentationModeButton.classList.add('hidden');
  6591. }
  6592. if (PDFViewerApplication.supportsIntegratedFind) {
  6593. appConfig.toolbar.viewFind.classList.add('hidden');
  6594. }
  6595. appConfig.sidebar.mainContainer.addEventListener('transitionend', function (e) {
  6596. if (e.target === this) {
  6597. PDFViewerApplication.eventBus.dispatch('resize');
  6598. }
  6599. }, true);
  6600. appConfig.sidebar.toggleButton.addEventListener('click', function () {
  6601. PDFViewerApplication.pdfSidebar.toggle();
  6602. });
  6603. Promise.all(waitForBeforeOpening).then(function () {
  6604. webViewerOpenFileViaURL(file);
  6605. }).catch(function (reason) {
  6606. PDFViewerApplication.error(mozL10n.get('loading_error', null, 'An error occurred while opening.'), reason);
  6607. });
  6608. }
  6609. var webViewerOpenFileViaURL;
  6610. webViewerOpenFileViaURL = function webViewerOpenFileViaURL(file) {
  6611. if (file && file.lastIndexOf('file:', 0) === 0) {
  6612. PDFViewerApplication.setTitleUsingUrl(file);
  6613. var xhr = new XMLHttpRequest();
  6614. xhr.onload = function () {
  6615. PDFViewerApplication.open(new Uint8Array(xhr.response));
  6616. };
  6617. try {
  6618. xhr.open('GET', file);
  6619. xhr.responseType = 'arraybuffer';
  6620. xhr.send();
  6621. } catch (e) {
  6622. PDFViewerApplication.error(mozL10n.get('loading_error', null, 'An error occurred while loading the PDF.'), e);
  6623. }
  6624. return;
  6625. }
  6626. if (file) {
  6627. PDFViewerApplication.open(file);
  6628. }
  6629. };
  6630. function webViewerPageRendered(e) {
  6631. var pageNumber = e.pageNumber;
  6632. var pageIndex = pageNumber - 1;
  6633. var pageView = PDFViewerApplication.pdfViewer.getPageView(pageIndex);
  6634. if (pageNumber === PDFViewerApplication.page) {
  6635. PDFViewerApplication.toolbar.updateLoadingIndicatorState(false);
  6636. }
  6637. if (!pageView) {
  6638. return;
  6639. }
  6640. if (PDFViewerApplication.pdfSidebar.isThumbnailViewVisible) {
  6641. var thumbnailView = PDFViewerApplication.pdfThumbnailViewer.getThumbnail(pageIndex);
  6642. thumbnailView.setImage(pageView);
  6643. }
  6644. if (pdfjsLib.PDFJS.pdfBug && Stats.enabled && pageView.stats) {
  6645. Stats.add(pageNumber, pageView.stats);
  6646. }
  6647. if (pageView.error) {
  6648. PDFViewerApplication.error(mozL10n.get('rendering_error', null, 'An error occurred while rendering the page.'), pageView.error);
  6649. }
  6650. }
  6651. function webViewerTextLayerRendered(e) {
  6652. }
  6653. function webViewerPageMode(e) {
  6654. var mode = e.mode, view;
  6655. switch (mode) {
  6656. case 'thumbs':
  6657. view = SidebarView.THUMBS;
  6658. break;
  6659. case 'bookmarks':
  6660. case 'outline':
  6661. view = SidebarView.OUTLINE;
  6662. break;
  6663. case 'attachments':
  6664. view = SidebarView.ATTACHMENTS;
  6665. break;
  6666. case 'none':
  6667. view = SidebarView.NONE;
  6668. break;
  6669. default:
  6670. console.error('Invalid "pagemode" hash parameter: ' + mode);
  6671. return;
  6672. }
  6673. PDFViewerApplication.pdfSidebar.switchView(view, true);
  6674. }
  6675. function webViewerNamedAction(e) {
  6676. var action = e.action;
  6677. switch (action) {
  6678. case 'GoToPage':
  6679. PDFViewerApplication.appConfig.toolbar.pageNumber.select();
  6680. break;
  6681. case 'Find':
  6682. if (!PDFViewerApplication.supportsIntegratedFind) {
  6683. PDFViewerApplication.findBar.toggle();
  6684. }
  6685. break;
  6686. }
  6687. }
  6688. function webViewerPresentationModeChanged(e) {
  6689. var active = e.active;
  6690. var switchInProgress = e.switchInProgress;
  6691. PDFViewerApplication.pdfViewer.presentationModeState = switchInProgress ? PresentationModeState.CHANGING : active ? PresentationModeState.FULLSCREEN : PresentationModeState.NORMAL;
  6692. }
  6693. function webViewerSidebarViewChanged(e) {
  6694. PDFViewerApplication.pdfRenderingQueue.isThumbnailViewEnabled = PDFViewerApplication.pdfSidebar.isThumbnailViewVisible;
  6695. var store = PDFViewerApplication.store;
  6696. if (!store || !PDFViewerApplication.isInitialViewSet) {
  6697. return;
  6698. }
  6699. store.initializedPromise.then(function () {
  6700. store.set('sidebarView', e.view).catch(function () {
  6701. });
  6702. });
  6703. }
  6704. function webViewerUpdateViewarea(e) {
  6705. var location = e.location, store = PDFViewerApplication.store;
  6706. if (store) {
  6707. store.initializedPromise.then(function () {
  6708. store.setMultiple({
  6709. 'exists': true,
  6710. 'page': location.pageNumber,
  6711. 'zoom': location.scale,
  6712. 'scrollLeft': location.left,
  6713. 'scrollTop': location.top
  6714. }).catch(function () {
  6715. });
  6716. });
  6717. }
  6718. var href = PDFViewerApplication.pdfLinkService.getAnchorUrl(location.pdfOpenParams);
  6719. PDFViewerApplication.appConfig.toolbar.viewBookmark.href = href;
  6720. PDFViewerApplication.appConfig.secondaryToolbar.viewBookmarkButton.href = href;
  6721. PDFViewerApplication.pdfHistory.updateCurrentBookmark(location.pdfOpenParams, location.pageNumber);
  6722. var currentPage = PDFViewerApplication.pdfViewer.getPageView(PDFViewerApplication.page - 1);
  6723. var loading = currentPage.renderingState !== RenderingStates.FINISHED;
  6724. PDFViewerApplication.toolbar.updateLoadingIndicatorState(loading);
  6725. }
  6726. function webViewerResize() {
  6727. var currentScaleValue = PDFViewerApplication.pdfViewer.currentScaleValue;
  6728. if (currentScaleValue === 'auto' || currentScaleValue === 'page-fit' || currentScaleValue === 'page-width') {
  6729. PDFViewerApplication.pdfViewer.currentScaleValue = currentScaleValue;
  6730. } else if (!currentScaleValue) {
  6731. PDFViewerApplication.pdfViewer.currentScaleValue = DEFAULT_SCALE_VALUE;
  6732. }
  6733. PDFViewerApplication.pdfViewer.update();
  6734. }
  6735. function webViewerHashchange(e) {
  6736. if (PDFViewerApplication.pdfHistory.isHashChangeUnlocked) {
  6737. var hash = e.hash;
  6738. if (!hash) {
  6739. return;
  6740. }
  6741. if (!PDFViewerApplication.isInitialViewSet) {
  6742. PDFViewerApplication.initialBookmark = hash;
  6743. } else {
  6744. PDFViewerApplication.pdfLinkService.setHash(hash);
  6745. }
  6746. }
  6747. }
  6748. var webViewerFileInputChange;
  6749. webViewerFileInputChange = function webViewerFileInputChange(e) {
  6750. var file = e.fileInput.files[0];
  6751. if (!pdfjsLib.PDFJS.disableCreateObjectURL && typeof URL !== 'undefined' && URL.createObjectURL) {
  6752. PDFViewerApplication.open(URL.createObjectURL(file));
  6753. } else {
  6754. var fileReader = new FileReader();
  6755. fileReader.onload = function webViewerChangeFileReaderOnload(evt) {
  6756. var buffer = evt.target.result;
  6757. var uint8Array = new Uint8Array(buffer);
  6758. PDFViewerApplication.open(uint8Array);
  6759. };
  6760. fileReader.readAsArrayBuffer(file);
  6761. }
  6762. PDFViewerApplication.setTitleUsingUrl(file.name);
  6763. var appConfig = PDFViewerApplication.appConfig;
  6764. appConfig.toolbar.viewBookmark.setAttribute('hidden', 'true');
  6765. appConfig.secondaryToolbar.viewBookmarkButton.setAttribute('hidden', 'true');
  6766. appConfig.toolbar.download.setAttribute('hidden', 'true');
  6767. appConfig.secondaryToolbar.downloadButton.setAttribute('hidden', 'true');
  6768. };
  6769. function webViewerPresentationMode() {
  6770. PDFViewerApplication.requestPresentationMode();
  6771. }
  6772. function webViewerOpenFile() {
  6773. var openFileInputName = PDFViewerApplication.appConfig.openFileInputName;
  6774. document.getElementById(openFileInputName).click();
  6775. }
  6776. function webViewerPrint() {
  6777. window.print();
  6778. }
  6779. function webViewerDownload() {
  6780. PDFViewerApplication.download();
  6781. }
  6782. function webViewerFirstPage() {
  6783. if (PDFViewerApplication.pdfDocument) {
  6784. PDFViewerApplication.page = 1;
  6785. }
  6786. }
  6787. function webViewerLastPage() {
  6788. if (PDFViewerApplication.pdfDocument) {
  6789. PDFViewerApplication.page = PDFViewerApplication.pagesCount;
  6790. }
  6791. }
  6792. function webViewerNextPage() {
  6793. PDFViewerApplication.page++;
  6794. }
  6795. function webViewerPreviousPage() {
  6796. PDFViewerApplication.page--;
  6797. }
  6798. function webViewerZoomIn() {
  6799. PDFViewerApplication.zoomIn();
  6800. }
  6801. function webViewerZoomOut() {
  6802. PDFViewerApplication.zoomOut();
  6803. }
  6804. function webViewerPageNumberChanged(e) {
  6805. var pdfViewer = PDFViewerApplication.pdfViewer;
  6806. pdfViewer.currentPageLabel = e.value;
  6807. if (e.value !== pdfViewer.currentPageNumber.toString() && e.value !== pdfViewer.currentPageLabel) {
  6808. PDFViewerApplication.toolbar.setPageNumber(pdfViewer.currentPageNumber, pdfViewer.currentPageLabel);
  6809. }
  6810. }
  6811. function webViewerScaleChanged(e) {
  6812. PDFViewerApplication.pdfViewer.currentScaleValue = e.value;
  6813. }
  6814. function webViewerRotateCw() {
  6815. PDFViewerApplication.rotatePages(90);
  6816. }
  6817. function webViewerRotateCcw() {
  6818. PDFViewerApplication.rotatePages(-90);
  6819. }
  6820. function webViewerDocumentProperties() {
  6821. PDFViewerApplication.pdfDocumentProperties.open();
  6822. }
  6823. function webViewerFind(e) {
  6824. PDFViewerApplication.findController.executeCommand('find' + e.type, {
  6825. query: e.query,
  6826. phraseSearch: e.phraseSearch,
  6827. caseSensitive: e.caseSensitive,
  6828. highlightAll: e.highlightAll,
  6829. findPrevious: e.findPrevious
  6830. });
  6831. }
  6832. function webViewerFindFromUrlHash(e) {
  6833. PDFViewerApplication.findController.executeCommand('find', {
  6834. query: e.query,
  6835. phraseSearch: e.phraseSearch,
  6836. caseSensitive: false,
  6837. highlightAll: true,
  6838. findPrevious: false
  6839. });
  6840. }
  6841. function webViewerScaleChanging(e) {
  6842. PDFViewerApplication.toolbar.setPageScale(e.presetValue, e.scale);
  6843. PDFViewerApplication.pdfViewer.update();
  6844. }
  6845. function webViewerPageChanging(e) {
  6846. var page = e.pageNumber;
  6847. PDFViewerApplication.toolbar.setPageNumber(page, e.pageLabel || null);
  6848. PDFViewerApplication.secondaryToolbar.setPageNumber(page);
  6849. if (PDFViewerApplication.pdfSidebar.isThumbnailViewVisible) {
  6850. PDFViewerApplication.pdfThumbnailViewer.scrollThumbnailIntoView(page);
  6851. }
  6852. if (pdfjsLib.PDFJS.pdfBug && Stats.enabled) {
  6853. var pageView = PDFViewerApplication.pdfViewer.getPageView(page - 1);
  6854. if (pageView.stats) {
  6855. Stats.add(page, pageView.stats);
  6856. }
  6857. }
  6858. }
  6859. var zoomDisabled = false, zoomDisabledTimeout;
  6860. function webViewerWheel(evt) {
  6861. var pdfViewer = PDFViewerApplication.pdfViewer;
  6862. if (pdfViewer.isInPresentationMode) {
  6863. return;
  6864. }
  6865. if (evt.ctrlKey || evt.metaKey) {
  6866. var support = PDFViewerApplication.supportedMouseWheelZoomModifierKeys;
  6867. if (evt.ctrlKey && !support.ctrlKey || evt.metaKey && !support.metaKey) {
  6868. return;
  6869. }
  6870. evt.preventDefault();
  6871. if (zoomDisabled) {
  6872. return;
  6873. }
  6874. var previousScale = pdfViewer.currentScale;
  6875. var delta = normalizeWheelEventDelta(evt);
  6876. var MOUSE_WHEEL_DELTA_PER_PAGE_SCALE = 3.0;
  6877. var ticks = delta * MOUSE_WHEEL_DELTA_PER_PAGE_SCALE;
  6878. if (ticks < 0) {
  6879. PDFViewerApplication.zoomOut(-ticks);
  6880. } else {
  6881. PDFViewerApplication.zoomIn(ticks);
  6882. }
  6883. var currentScale = pdfViewer.currentScale;
  6884. if (previousScale !== currentScale) {
  6885. var scaleCorrectionFactor = currentScale / previousScale - 1;
  6886. var rect = pdfViewer.container.getBoundingClientRect();
  6887. var dx = evt.clientX - rect.left;
  6888. var dy = evt.clientY - rect.top;
  6889. pdfViewer.container.scrollLeft += dx * scaleCorrectionFactor;
  6890. pdfViewer.container.scrollTop += dy * scaleCorrectionFactor;
  6891. }
  6892. } else {
  6893. zoomDisabled = true;
  6894. clearTimeout(zoomDisabledTimeout);
  6895. zoomDisabledTimeout = setTimeout(function () {
  6896. zoomDisabled = false;
  6897. }, 1000);
  6898. }
  6899. }
  6900. function webViewerClick(evt) {
  6901. if (!PDFViewerApplication.secondaryToolbar.isOpen) {
  6902. return;
  6903. }
  6904. var appConfig = PDFViewerApplication.appConfig;
  6905. if (PDFViewerApplication.pdfViewer.containsElement(evt.target) || appConfig.toolbar.container.contains(evt.target) && evt.target !== appConfig.secondaryToolbar.toggleButton) {
  6906. PDFViewerApplication.secondaryToolbar.close();
  6907. }
  6908. }
  6909. function webViewerKeyDown(evt) {
  6910. if (OverlayManager.active) {
  6911. return;
  6912. }
  6913. var handled = false, ensureViewerFocused = false;
  6914. var cmd = (evt.ctrlKey ? 1 : 0) | (evt.altKey ? 2 : 0) | (evt.shiftKey ? 4 : 0) | (evt.metaKey ? 8 : 0);
  6915. var pdfViewer = PDFViewerApplication.pdfViewer;
  6916. var isViewerInPresentationMode = pdfViewer && pdfViewer.isInPresentationMode;
  6917. if (cmd === 1 || cmd === 8 || cmd === 5 || cmd === 12) {
  6918. switch (evt.keyCode) {
  6919. case 70:
  6920. if (!PDFViewerApplication.supportsIntegratedFind) {
  6921. PDFViewerApplication.findBar.open();
  6922. handled = true;
  6923. }
  6924. break;
  6925. case 71:
  6926. if (!PDFViewerApplication.supportsIntegratedFind) {
  6927. var findState = PDFViewerApplication.findController.state;
  6928. if (findState) {
  6929. PDFViewerApplication.findController.executeCommand('findagain', {
  6930. query: findState.query,
  6931. phraseSearch: findState.phraseSearch,
  6932. caseSensitive: findState.caseSensitive,
  6933. highlightAll: findState.highlightAll,
  6934. findPrevious: cmd === 5 || cmd === 12
  6935. });
  6936. }
  6937. handled = true;
  6938. }
  6939. break;
  6940. case 61:
  6941. case 107:
  6942. case 187:
  6943. case 171:
  6944. if (!isViewerInPresentationMode) {
  6945. PDFViewerApplication.zoomIn();
  6946. }
  6947. handled = true;
  6948. break;
  6949. case 173:
  6950. case 109:
  6951. case 189:
  6952. if (!isViewerInPresentationMode) {
  6953. PDFViewerApplication.zoomOut();
  6954. }
  6955. handled = true;
  6956. break;
  6957. case 48:
  6958. case 96:
  6959. if (!isViewerInPresentationMode) {
  6960. setTimeout(function () {
  6961. pdfViewer.currentScaleValue = DEFAULT_SCALE_VALUE;
  6962. });
  6963. handled = false;
  6964. }
  6965. break;
  6966. case 38:
  6967. if (isViewerInPresentationMode || PDFViewerApplication.page > 1) {
  6968. PDFViewerApplication.page = 1;
  6969. handled = true;
  6970. ensureViewerFocused = true;
  6971. }
  6972. break;
  6973. case 40:
  6974. if (isViewerInPresentationMode || PDFViewerApplication.page < PDFViewerApplication.pagesCount) {
  6975. PDFViewerApplication.page = PDFViewerApplication.pagesCount;
  6976. handled = true;
  6977. ensureViewerFocused = true;
  6978. }
  6979. break;
  6980. }
  6981. }
  6982. if (cmd === 1 || cmd === 8) {
  6983. switch (evt.keyCode) {
  6984. case 83:
  6985. PDFViewerApplication.download();
  6986. handled = true;
  6987. break;
  6988. }
  6989. }
  6990. if (cmd === 3 || cmd === 10) {
  6991. switch (evt.keyCode) {
  6992. case 80:
  6993. PDFViewerApplication.requestPresentationMode();
  6994. handled = true;
  6995. break;
  6996. case 71:
  6997. PDFViewerApplication.appConfig.toolbar.pageNumber.select();
  6998. handled = true;
  6999. break;
  7000. }
  7001. }
  7002. if (handled) {
  7003. if (ensureViewerFocused && !isViewerInPresentationMode) {
  7004. pdfViewer.focus();
  7005. }
  7006. evt.preventDefault();
  7007. return;
  7008. }
  7009. var curElement = document.activeElement || document.querySelector(':focus');
  7010. var curElementTagName = curElement && curElement.tagName.toUpperCase();
  7011. if (curElementTagName === 'INPUT' || curElementTagName === 'TEXTAREA' || curElementTagName === 'SELECT') {
  7012. if (evt.keyCode !== 27) {
  7013. return;
  7014. }
  7015. }
  7016. if (cmd === 0) {
  7017. switch (evt.keyCode) {
  7018. case 38:
  7019. case 33:
  7020. case 8:
  7021. if (!isViewerInPresentationMode && pdfViewer.currentScaleValue !== 'page-fit') {
  7022. break;
  7023. }
  7024. case 37:
  7025. if (pdfViewer.isHorizontalScrollbarEnabled) {
  7026. break;
  7027. }
  7028. case 75:
  7029. case 80:
  7030. if (PDFViewerApplication.page > 1) {
  7031. PDFViewerApplication.page--;
  7032. }
  7033. handled = true;
  7034. break;
  7035. case 27:
  7036. if (PDFViewerApplication.secondaryToolbar.isOpen) {
  7037. PDFViewerApplication.secondaryToolbar.close();
  7038. handled = true;
  7039. }
  7040. if (!PDFViewerApplication.supportsIntegratedFind && PDFViewerApplication.findBar.opened) {
  7041. PDFViewerApplication.findBar.close();
  7042. handled = true;
  7043. }
  7044. break;
  7045. case 40:
  7046. case 34:
  7047. case 32:
  7048. if (!isViewerInPresentationMode && pdfViewer.currentScaleValue !== 'page-fit') {
  7049. break;
  7050. }
  7051. case 39:
  7052. if (pdfViewer.isHorizontalScrollbarEnabled) {
  7053. break;
  7054. }
  7055. case 74:
  7056. case 78:
  7057. if (PDFViewerApplication.page < PDFViewerApplication.pagesCount) {
  7058. PDFViewerApplication.page++;
  7059. }
  7060. handled = true;
  7061. break;
  7062. case 36:
  7063. if (isViewerInPresentationMode || PDFViewerApplication.page > 1) {
  7064. PDFViewerApplication.page = 1;
  7065. handled = true;
  7066. ensureViewerFocused = true;
  7067. }
  7068. break;
  7069. case 35:
  7070. if (isViewerInPresentationMode || PDFViewerApplication.page < PDFViewerApplication.pagesCount) {
  7071. PDFViewerApplication.page = PDFViewerApplication.pagesCount;
  7072. handled = true;
  7073. ensureViewerFocused = true;
  7074. }
  7075. break;
  7076. case 72:
  7077. if (!isViewerInPresentationMode) {
  7078. PDFViewerApplication.handTool.toggle();
  7079. }
  7080. break;
  7081. case 82:
  7082. PDFViewerApplication.rotatePages(90);
  7083. break;
  7084. }
  7085. }
  7086. if (cmd === 4) {
  7087. switch (evt.keyCode) {
  7088. case 32:
  7089. if (!isViewerInPresentationMode && pdfViewer.currentScaleValue !== 'page-fit') {
  7090. break;
  7091. }
  7092. if (PDFViewerApplication.page > 1) {
  7093. PDFViewerApplication.page--;
  7094. }
  7095. handled = true;
  7096. break;
  7097. case 82:
  7098. PDFViewerApplication.rotatePages(-90);
  7099. break;
  7100. }
  7101. }
  7102. if (!handled && !isViewerInPresentationMode) {
  7103. if (evt.keyCode >= 33 && evt.keyCode <= 40 || evt.keyCode === 32 && curElementTagName !== 'BUTTON') {
  7104. ensureViewerFocused = true;
  7105. }
  7106. }
  7107. if (cmd === 2) {
  7108. switch (evt.keyCode) {
  7109. case 37:
  7110. if (isViewerInPresentationMode) {
  7111. PDFViewerApplication.pdfHistory.back();
  7112. handled = true;
  7113. }
  7114. break;
  7115. case 39:
  7116. if (isViewerInPresentationMode) {
  7117. PDFViewerApplication.pdfHistory.forward();
  7118. handled = true;
  7119. }
  7120. break;
  7121. }
  7122. }
  7123. if (ensureViewerFocused && !pdfViewer.containsElement(curElement)) {
  7124. pdfViewer.focus();
  7125. }
  7126. if (handled) {
  7127. evt.preventDefault();
  7128. }
  7129. }
  7130. localized.then(function webViewerLocalized() {
  7131. document.getElementsByTagName('html')[0].dir = mozL10n.getDirection();
  7132. });
  7133. var PDFPrintServiceFactory = {
  7134. instance: {
  7135. supportsPrinting: false,
  7136. createPrintService: function () {
  7137. throw new Error('Not implemented: createPrintService');
  7138. }
  7139. }
  7140. };
  7141. exports.PDFViewerApplication = PDFViewerApplication;
  7142. exports.DefaultExernalServices = DefaultExernalServices;
  7143. exports.PDFPrintServiceFactory = PDFPrintServiceFactory;
  7144. }));
  7145. (function (root, factory) {
  7146. factory(root.pdfjsWebPDFPrintService = {}, root.pdfjsWebUIUtils, root.pdfjsWebOverlayManager, root.pdfjsWebApp, root.pdfjsWebPDFJS);
  7147. }(this, function (exports, uiUtils, overlayManager, app, pdfjsLib) {
  7148. var mozL10n = uiUtils.mozL10n;
  7149. var CSS_UNITS = uiUtils.CSS_UNITS;
  7150. var PDFPrintServiceFactory = app.PDFPrintServiceFactory;
  7151. var OverlayManager = overlayManager.OverlayManager;
  7152. var activeService = null;
  7153. function renderPage(activeServiceOnEntry, pdfDocument, pageNumber, size) {
  7154. var scratchCanvas = activeService.scratchCanvas;
  7155. var PRINT_RESOLUTION = 150;
  7156. var PRINT_UNITS = PRINT_RESOLUTION / 72.0;
  7157. scratchCanvas.width = Math.floor(size.width * PRINT_UNITS);
  7158. scratchCanvas.height = Math.floor(size.height * PRINT_UNITS);
  7159. var width = Math.floor(size.width * CSS_UNITS) + 'px';
  7160. var height = Math.floor(size.height * CSS_UNITS) + 'px';
  7161. var ctx = scratchCanvas.getContext('2d');
  7162. ctx.save();
  7163. ctx.fillStyle = 'rgb(255, 255, 255)';
  7164. ctx.fillRect(0, 0, scratchCanvas.width, scratchCanvas.height);
  7165. ctx.restore();
  7166. return pdfDocument.getPage(pageNumber).then(function (pdfPage) {
  7167. var renderContext = {
  7168. canvasContext: ctx,
  7169. transform: [
  7170. PRINT_UNITS,
  7171. 0,
  7172. 0,
  7173. PRINT_UNITS,
  7174. 0,
  7175. 0
  7176. ],
  7177. viewport: pdfPage.getViewport(1),
  7178. intent: 'print'
  7179. };
  7180. return pdfPage.render(renderContext).promise;
  7181. }).then(function () {
  7182. return {
  7183. width: width,
  7184. height: height
  7185. };
  7186. });
  7187. }
  7188. function PDFPrintService(pdfDocument, pagesOverview, printContainer) {
  7189. this.pdfDocument = pdfDocument;
  7190. this.pagesOverview = pagesOverview;
  7191. this.printContainer = printContainer;
  7192. this.currentPage = -1;
  7193. this.scratchCanvas = document.createElement('canvas');
  7194. }
  7195. PDFPrintService.prototype = {
  7196. layout: function () {
  7197. this.throwIfInactive();
  7198. var pdfDocument = this.pdfDocument;
  7199. var body = document.querySelector('body');
  7200. body.setAttribute('data-pdfjsprinting', true);
  7201. var hasEqualPageSizes = this.pagesOverview.every(function (size) {
  7202. return size.width === this.pagesOverview[0].width && size.height === this.pagesOverview[0].height;
  7203. }, this);
  7204. if (!hasEqualPageSizes) {
  7205. console.warn('Not all pages have the same size. The printed ' + 'result may be incorrect!');
  7206. }
  7207. this.pageStyleSheet = document.createElement('style');
  7208. var pageSize = this.pagesOverview[0];
  7209. this.pageStyleSheet.textContent = '@supports ((size:A4) and (size:1pt 1pt)) {' + '@page { size: ' + pageSize.width + 'pt ' + pageSize.height + 'pt;}' + '}';
  7210. body.appendChild(this.pageStyleSheet);
  7211. },
  7212. destroy: function () {
  7213. if (activeService !== this) {
  7214. return;
  7215. }
  7216. this.printContainer.textContent = '';
  7217. if (this.pageStyleSheet && this.pageStyleSheet.parentNode) {
  7218. this.pageStyleSheet.parentNode.removeChild(this.pageStyleSheet);
  7219. this.pageStyleSheet = null;
  7220. }
  7221. this.scratchCanvas.width = this.scratchCanvas.height = 0;
  7222. this.scratchCanvas = null;
  7223. activeService = null;
  7224. ensureOverlay().then(function () {
  7225. if (OverlayManager.active !== 'printServiceOverlay') {
  7226. return;
  7227. }
  7228. OverlayManager.close('printServiceOverlay');
  7229. });
  7230. },
  7231. renderPages: function () {
  7232. var pageCount = this.pagesOverview.length;
  7233. var renderNextPage = function (resolve, reject) {
  7234. this.throwIfInactive();
  7235. if (++this.currentPage >= pageCount) {
  7236. renderProgress(pageCount, pageCount);
  7237. resolve();
  7238. return;
  7239. }
  7240. var index = this.currentPage;
  7241. renderProgress(index, pageCount);
  7242. renderPage(this, this.pdfDocument, index + 1, this.pagesOverview[index]).then(this.useRenderedPage.bind(this)).then(function () {
  7243. renderNextPage(resolve, reject);
  7244. }, reject);
  7245. }.bind(this);
  7246. return new Promise(renderNextPage);
  7247. },
  7248. useRenderedPage: function (printItem) {
  7249. this.throwIfInactive();
  7250. var img = document.createElement('img');
  7251. img.style.width = printItem.width;
  7252. img.style.height = printItem.height;
  7253. var scratchCanvas = this.scratchCanvas;
  7254. if ('toBlob' in scratchCanvas && !pdfjsLib.PDFJS.disableCreateObjectURL) {
  7255. scratchCanvas.toBlob(function (blob) {
  7256. img.src = URL.createObjectURL(blob);
  7257. });
  7258. } else {
  7259. img.src = scratchCanvas.toDataURL();
  7260. }
  7261. var wrapper = document.createElement('div');
  7262. wrapper.appendChild(img);
  7263. this.printContainer.appendChild(wrapper);
  7264. return new Promise(function (resolve, reject) {
  7265. img.onload = resolve;
  7266. img.onerror = reject;
  7267. });
  7268. },
  7269. performPrint: function () {
  7270. this.throwIfInactive();
  7271. return new Promise(function (resolve) {
  7272. setTimeout(function () {
  7273. if (!this.active) {
  7274. resolve();
  7275. return;
  7276. }
  7277. print.call(window);
  7278. setTimeout(resolve, 20);
  7279. }.bind(this), 0);
  7280. }.bind(this));
  7281. },
  7282. get active() {
  7283. return this === activeService;
  7284. },
  7285. throwIfInactive: function () {
  7286. if (!this.active) {
  7287. throw new Error('This print request was cancelled or completed.');
  7288. }
  7289. }
  7290. };
  7291. var print = window.print;
  7292. window.print = function print() {
  7293. if (activeService) {
  7294. console.warn('Ignored window.print() because of a pending print job.');
  7295. return;
  7296. }
  7297. ensureOverlay().then(function () {
  7298. if (activeService) {
  7299. OverlayManager.open('printServiceOverlay');
  7300. }
  7301. });
  7302. try {
  7303. dispatchEvent('beforeprint');
  7304. } finally {
  7305. if (!activeService) {
  7306. console.error('Expected print service to be initialized.');
  7307. if (OverlayManager.active === 'printServiceOverlay') {
  7308. OverlayManager.close('printServiceOverlay');
  7309. }
  7310. return;
  7311. }
  7312. var activeServiceOnEntry = activeService;
  7313. activeService.renderPages().then(function () {
  7314. return activeServiceOnEntry.performPrint();
  7315. }).catch(function () {
  7316. }).then(function () {
  7317. if (activeServiceOnEntry.active) {
  7318. abort();
  7319. }
  7320. });
  7321. }
  7322. };
  7323. function dispatchEvent(eventType) {
  7324. var event = document.createEvent('CustomEvent');
  7325. event.initCustomEvent(eventType, false, false, 'custom');
  7326. window.dispatchEvent(event);
  7327. }
  7328. function abort() {
  7329. if (activeService) {
  7330. activeService.destroy();
  7331. dispatchEvent('afterprint');
  7332. }
  7333. }
  7334. function renderProgress(index, total) {
  7335. var progressContainer = document.getElementById('printServiceOverlay');
  7336. var progress = Math.round(100 * index / total);
  7337. var progressBar = progressContainer.querySelector('progress');
  7338. var progressPerc = progressContainer.querySelector('.relative-progress');
  7339. progressBar.value = progress;
  7340. progressPerc.textContent = mozL10n.get('print_progress_percent', { progress: progress }, progress + '%');
  7341. }
  7342. var hasAttachEvent = !!document.attachEvent;
  7343. window.addEventListener('keydown', function (event) {
  7344. if (event.keyCode === 80 && (event.ctrlKey || event.metaKey) && !event.altKey && (!event.shiftKey || window.chrome || window.opera)) {
  7345. window.print();
  7346. if (hasAttachEvent) {
  7347. return;
  7348. }
  7349. event.preventDefault();
  7350. if (event.stopImmediatePropagation) {
  7351. event.stopImmediatePropagation();
  7352. } else {
  7353. event.stopPropagation();
  7354. }
  7355. return;
  7356. }
  7357. }, true);
  7358. if (hasAttachEvent) {
  7359. document.attachEvent('onkeydown', function (event) {
  7360. event = event || window.event;
  7361. if (event.keyCode === 80 && event.ctrlKey) {
  7362. event.keyCode = 0;
  7363. return false;
  7364. }
  7365. });
  7366. }
  7367. if ('onbeforeprint' in window) {
  7368. var stopPropagationIfNeeded = function (event) {
  7369. if (event.detail !== 'custom' && event.stopImmediatePropagation) {
  7370. event.stopImmediatePropagation();
  7371. }
  7372. };
  7373. window.addEventListener('beforeprint', stopPropagationIfNeeded);
  7374. window.addEventListener('afterprint', stopPropagationIfNeeded);
  7375. }
  7376. var overlayPromise;
  7377. function ensureOverlay() {
  7378. if (!overlayPromise) {
  7379. overlayPromise = OverlayManager.register('printServiceOverlay', document.getElementById('printServiceOverlay'), abort, true);
  7380. document.getElementById('printCancel').onclick = abort;
  7381. }
  7382. return overlayPromise;
  7383. }
  7384. PDFPrintServiceFactory.instance = {
  7385. supportsPrinting: true,
  7386. createPrintService: function (pdfDocument, pagesOverview, printContainer) {
  7387. if (activeService) {
  7388. throw new Error('The print service is created and active.');
  7389. }
  7390. activeService = new PDFPrintService(pdfDocument, pagesOverview, printContainer);
  7391. return activeService;
  7392. }
  7393. };
  7394. exports.PDFPrintService = PDFPrintService;
  7395. }));
  7396. }.call(pdfjsWebLibs));
  7397. }
  7398. ;
  7399. function getViewerConfiguration() {
  7400. return {
  7401. appContainer: document.body,
  7402. mainContainer: document.getElementById('viewerContainer'),
  7403. viewerContainer: document.getElementById('viewer'),
  7404. eventBus: null,
  7405. toolbar: {
  7406. container: document.getElementById('toolbarViewer'),
  7407. numPages: document.getElementById('numPages'),
  7408. pageNumber: document.getElementById('pageNumber'),
  7409. scaleSelectContainer: document.getElementById('scaleSelectContainer'),
  7410. scaleSelect: document.getElementById('scaleSelect'),
  7411. customScaleOption: document.getElementById('customScaleOption'),
  7412. previous: document.getElementById('previous'),
  7413. next: document.getElementById('next'),
  7414. zoomIn: document.getElementById('zoomIn'),
  7415. zoomOut: document.getElementById('zoomOut'),
  7416. viewFind: document.getElementById('viewFind'),
  7417. openFile: document.getElementById('openFile'),
  7418. print: document.getElementById('print'),
  7419. presentationModeButton: document.getElementById('presentationMode'),
  7420. download: document.getElementById('download'),
  7421. viewBookmark: document.getElementById('viewBookmark')
  7422. },
  7423. secondaryToolbar: {
  7424. toolbar: document.getElementById('secondaryToolbar'),
  7425. toggleButton: document.getElementById('secondaryToolbarToggle'),
  7426. toolbarButtonContainer: document.getElementById('secondaryToolbarButtonContainer'),
  7427. presentationModeButton: document.getElementById('secondaryPresentationMode'),
  7428. openFileButton: document.getElementById('secondaryOpenFile'),
  7429. printButton: document.getElementById('secondaryPrint'),
  7430. downloadButton: document.getElementById('secondaryDownload'),
  7431. viewBookmarkButton: document.getElementById('secondaryViewBookmark'),
  7432. firstPageButton: document.getElementById('firstPage'),
  7433. lastPageButton: document.getElementById('lastPage'),
  7434. pageRotateCwButton: document.getElementById('pageRotateCw'),
  7435. pageRotateCcwButton: document.getElementById('pageRotateCcw'),
  7436. toggleHandToolButton: document.getElementById('toggleHandTool'),
  7437. documentPropertiesButton: document.getElementById('documentProperties')
  7438. },
  7439. fullscreen: {
  7440. contextFirstPage: document.getElementById('contextFirstPage'),
  7441. contextLastPage: document.getElementById('contextLastPage'),
  7442. contextPageRotateCw: document.getElementById('contextPageRotateCw'),
  7443. contextPageRotateCcw: document.getElementById('contextPageRotateCcw')
  7444. },
  7445. sidebar: {
  7446. mainContainer: document.getElementById('mainContainer'),
  7447. outerContainer: document.getElementById('outerContainer'),
  7448. toggleButton: document.getElementById('sidebarToggle'),
  7449. thumbnailButton: document.getElementById('viewThumbnail'),
  7450. outlineButton: document.getElementById('viewOutline'),
  7451. attachmentsButton: document.getElementById('viewAttachments'),
  7452. thumbnailView: document.getElementById('thumbnailView'),
  7453. outlineView: document.getElementById('outlineView'),
  7454. attachmentsView: document.getElementById('attachmentsView')
  7455. },
  7456. findBar: {
  7457. bar: document.getElementById('findbar'),
  7458. toggleButton: document.getElementById('viewFind'),
  7459. findField: document.getElementById('findInput'),
  7460. highlightAllCheckbox: document.getElementById('findHighlightAll'),
  7461. caseSensitiveCheckbox: document.getElementById('findMatchCase'),
  7462. findMsg: document.getElementById('findMsg'),
  7463. findResultsCount: document.getElementById('findResultsCount'),
  7464. findStatusIcon: document.getElementById('findStatusIcon'),
  7465. findPreviousButton: document.getElementById('findPrevious'),
  7466. findNextButton: document.getElementById('findNext')
  7467. },
  7468. passwordOverlay: {
  7469. overlayName: 'passwordOverlay',
  7470. container: document.getElementById('passwordOverlay'),
  7471. label: document.getElementById('passwordText'),
  7472. input: document.getElementById('password'),
  7473. submitButton: document.getElementById('passwordSubmit'),
  7474. cancelButton: document.getElementById('passwordCancel')
  7475. },
  7476. documentProperties: {
  7477. overlayName: 'documentPropertiesOverlay',
  7478. container: document.getElementById('documentPropertiesOverlay'),
  7479. closeButton: document.getElementById('documentPropertiesClose'),
  7480. fields: {
  7481. 'fileName': document.getElementById('fileNameField'),
  7482. 'fileSize': document.getElementById('fileSizeField'),
  7483. 'title': document.getElementById('titleField'),
  7484. 'author': document.getElementById('authorField'),
  7485. 'subject': document.getElementById('subjectField'),
  7486. 'keywords': document.getElementById('keywordsField'),
  7487. 'creationDate': document.getElementById('creationDateField'),
  7488. 'modificationDate': document.getElementById('modificationDateField'),
  7489. 'creator': document.getElementById('creatorField'),
  7490. 'producer': document.getElementById('producerField'),
  7491. 'version': document.getElementById('versionField'),
  7492. 'pageCount': document.getElementById('pageCountField')
  7493. }
  7494. },
  7495. errorWrapper: {
  7496. container: document.getElementById('errorWrapper'),
  7497. errorMessage: document.getElementById('errorMessage'),
  7498. closeButton: document.getElementById('errorClose'),
  7499. errorMoreInfo: document.getElementById('errorMoreInfo'),
  7500. moreInfoButton: document.getElementById('errorShowMore'),
  7501. lessInfoButton: document.getElementById('errorShowLess')
  7502. },
  7503. printContainer: document.getElementById('printContainer'),
  7504. openFileInputName: 'fileInput',
  7505. debuggerScriptPath: './debugger.js'
  7506. };
  7507. }
  7508. function webViewerLoad() {
  7509. var config = getViewerConfiguration();
  7510. window.PDFViewerApplication = pdfjsWebLibs.pdfjsWebApp.PDFViewerApplication;
  7511. pdfjsWebLibs.pdfjsWebApp.PDFViewerApplication.run(config);
  7512. }
  7513. if (document.readyState === 'interactive' || document.readyState === 'complete') {
  7514. webViewerLoad();
  7515. } else {
  7516. document.addEventListener('DOMContentLoaded', webViewerLoad, true);
  7517. }