forked from instructure/pdf-annotate.js
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathpdf_viewer.js
3132 lines (2770 loc) · 98.5 KB
/
pdf_viewer.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/* Copyright 2014 Mozilla Foundation
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/*jshint globalstrict: false */
/* globals PDFJS, PDFViewer, PDFPageView, TextLayerBuilder, PDFLinkService,
DefaultTextLayerFactory, AnnotationLayerBuilder, PDFHistory,
DefaultAnnotationLayerFactory, DownloadManager, ProgressBar */
// Initializing PDFJS global object (if still undefined)
if (typeof PDFJS === 'undefined') {
(typeof window !== 'undefined' ? window : this).PDFJS = {};
}
(function pdfViewerWrapper() {
'use strict';
var CSS_UNITS = 96.0 / 72.0;
var DEFAULT_SCALE_VALUE = 'auto';
var DEFAULT_SCALE = 1.0;
var UNKNOWN_SCALE = 0;
var MAX_AUTO_SCALE = 1.25;
var SCROLLBAR_PADDING = 40;
var VERTICAL_PADDING = 5;
/**
* Returns scale factor for the canvas. It makes sense for the HiDPI displays.
* @return {Object} The object with horizontal (sx) and vertical (sy)
scales. The scaled property is set to false if scaling is
not required, true otherwise.
*/
function getOutputScale(ctx) {
var devicePixelRatio = window.devicePixelRatio || 1;
var backingStoreRatio = ctx.webkitBackingStorePixelRatio ||
ctx.mozBackingStorePixelRatio ||
ctx.msBackingStorePixelRatio ||
ctx.oBackingStorePixelRatio ||
ctx.backingStorePixelRatio || 1;
var pixelRatio = devicePixelRatio / backingStoreRatio;
return {
sx: pixelRatio,
sy: pixelRatio,
scaled: pixelRatio !== 1
};
}
/**
* Scrolls specified element into view of its parent.
* @param {Object} element - The element to be visible.
* @param {Object} spot - An object with optional top and left properties,
* specifying the offset from the top left edge.
* @param {boolean} skipOverflowHiddenElements - Ignore elements that have
* the CSS rule `overflow: hidden;` set. The default is false.
*/
function scrollIntoView(element, spot, skipOverflowHiddenElements) {
// Assuming offsetParent is available (it's not available when viewer is in
// hidden iframe or object). We have to scroll: if the offsetParent is not set
// producing the error. See also animationStartedClosure.
var parent = element.offsetParent;
if (!parent) {
console.error('offsetParent is not set -- cannot scroll');
return;
}
var checkOverflow = skipOverflowHiddenElements || false;
var offsetY = element.offsetTop + element.clientTop;
var offsetX = element.offsetLeft + element.clientLeft;
while (parent.clientHeight === parent.scrollHeight ||
(checkOverflow && getComputedStyle(parent).overflow === 'hidden')) {
if (parent.dataset._scaleY) {
offsetY /= parent.dataset._scaleY;
offsetX /= parent.dataset._scaleX;
}
offsetY += parent.offsetTop;
offsetX += parent.offsetLeft;
parent = parent.offsetParent;
if (!parent) {
return; // no need to scroll
}
}
if (spot) {
if (spot.top !== undefined) {
offsetY += spot.top;
}
if (spot.left !== undefined) {
offsetX += spot.left;
parent.scrollLeft = offsetX;
}
}
parent.scrollTop = offsetY;
}
/**
* Helper function to start monitoring the scroll event and converting them into
* PDF.js friendly one: with scroll debounce and scroll direction.
*/
function watchScroll(viewAreaElement, callback) {
var debounceScroll = function debounceScroll(evt) {
if (rAF) {
return;
}
// schedule an invocation of scroll for next animation frame.
rAF = window.requestAnimationFrame(function viewAreaElementScrolled() {
rAF = null;
var currentY = viewAreaElement.scrollTop;
var lastY = state.lastY;
if (currentY !== lastY) {
state.down = currentY > lastY;
}
state.lastY = currentY;
callback(state);
});
};
var state = {
down: true,
lastY: viewAreaElement.scrollTop,
_eventHandler: debounceScroll
};
var rAF = null;
viewAreaElement.addEventListener('scroll', debounceScroll, true);
return state;
}
/**
* Helper function to parse query string (e.g. ?param1=value&parm2=...).
*/
function parseQueryString(query) {
var parts = query.split('&');
var params = {};
for (var i = 0, ii = parts.length; i < ii; ++i) {
var param = parts[i].split('=');
var key = param[0].toLowerCase();
var value = param.length > 1 ? param[1] : null;
params[decodeURIComponent(key)] = decodeURIComponent(value);
}
return params;
}
/**
* Use binary search to find the index of the first item in a given array which
* passes a given condition. The items are expected to be sorted in the sense
* that if the condition is true for one item in the array, then it is also true
* for all following items.
*
* @returns {Number} Index of the first array element to pass the test,
* or |items.length| if no such element exists.
*/
function binarySearchFirstItem(items, condition) {
var minIndex = 0;
var maxIndex = items.length - 1;
if (items.length === 0 || !condition(items[maxIndex])) {
return items.length;
}
if (condition(items[minIndex])) {
return minIndex;
}
while (minIndex < maxIndex) {
var currentIndex = (minIndex + maxIndex) >> 1;
var currentItem = items[currentIndex];
if (condition(currentItem)) {
maxIndex = currentIndex;
} else {
minIndex = currentIndex + 1;
}
}
return minIndex; /* === maxIndex */
}
/**
* Approximates float number as a fraction using Farey sequence (max order
* of 8).
* @param {number} x - Positive float number.
* @returns {Array} Estimated fraction: the first array item is a numerator,
* the second one is a denominator.
*/
function approximateFraction(x) {
// Fast paths for int numbers or their inversions.
if (Math.floor(x) === x) {
return [x, 1];
}
var xinv = 1 / x;
var limit = 8;
if (xinv > limit) {
return [1, limit];
} else if (Math.floor(xinv) === xinv) {
return [1, xinv];
}
var x_ = x > 1 ? xinv : x;
// a/b and c/d are neighbours in Farey sequence.
var a = 0, b = 1, c = 1, d = 1;
// Limiting search to order 8.
while (true) {
// Generating next term in sequence (order of q).
var p = a + c, q = b + d;
if (q > limit) {
break;
}
if (x_ <= p / q) {
c = p; d = q;
} else {
a = p; b = q;
}
}
// Select closest of the neighbours to x.
if (x_ - a / b < c / d - x_) {
return x_ === x ? [a, b] : [b, a];
} else {
return x_ === x ? [c, d] : [d, c];
}
}
function roundToDivide(x, div) {
var r = x % div;
return r === 0 ? x : Math.round(x - r + div);
}
/**
* Generic helper to find out what elements are visible within a scroll pane.
*/
function getVisibleElements(scrollEl, views, sortByVisibility) {
var top = scrollEl.scrollTop, bottom = top + scrollEl.clientHeight;
var left = scrollEl.scrollLeft, right = left + scrollEl.clientWidth;
function isElementBottomBelowViewTop(view) {
var element = view.div;
var elementBottom =
element.offsetTop + element.clientTop + element.clientHeight;
return elementBottom > top;
}
var visible = [], view, element;
var currentHeight, viewHeight, hiddenHeight, percentHeight;
var currentWidth, viewWidth;
var firstVisibleElementInd = (views.length === 0) ? 0 :
binarySearchFirstItem(views, isElementBottomBelowViewTop);
for (var i = firstVisibleElementInd, ii = views.length; i < ii; i++) {
view = views[i];
element = view.div;
currentHeight = element.offsetTop + element.clientTop;
viewHeight = element.clientHeight;
if (currentHeight > bottom) {
break;
}
currentWidth = element.offsetLeft + element.clientLeft;
viewWidth = element.clientWidth;
if (currentWidth + viewWidth < left || currentWidth > right) {
continue;
}
hiddenHeight = Math.max(0, top - currentHeight) +
Math.max(0, currentHeight + viewHeight - bottom);
percentHeight = ((viewHeight - hiddenHeight) * 100 / viewHeight) | 0;
visible.push({
id: view.id,
x: currentWidth,
y: currentHeight,
view: view,
percent: percentHeight
});
}
var first = visible[0];
var last = visible[visible.length - 1];
if (sortByVisibility) {
visible.sort(function(a, b) {
var pc = a.percent - b.percent;
if (Math.abs(pc) > 0.001) {
return -pc;
}
return a.id - b.id; // ensure stability
});
}
return {first: first, last: last, views: visible};
}
/**
* Event handler to suppress context menu.
*/
function noContextMenuHandler(e) {
e.preventDefault();
}
/**
* Returns the filename or guessed filename from the url (see issue 3455).
* url {String} The original PDF location.
* @return {String} Guessed PDF file name.
*/
function getPDFFileNameFromURL(url) {
var reURI = /^(?:([^:]+:)?\/\/[^\/]+)?([^?#]*)(\?[^#]*)?(#.*)?$/;
// SCHEME HOST 1.PATH 2.QUERY 3.REF
// Pattern to get last matching NAME.pdf
var reFilename = /[^\/?#=]+\.pdf\b(?!.*\.pdf\b)/i;
var splitURI = reURI.exec(url);
var suggestedFilename = reFilename.exec(splitURI[1]) ||
reFilename.exec(splitURI[2]) ||
reFilename.exec(splitURI[3]);
if (suggestedFilename) {
suggestedFilename = suggestedFilename[0];
if (suggestedFilename.indexOf('%') !== -1) {
// URL-encoded %2Fpath%2Fto%2Ffile.pdf should be file.pdf
try {
suggestedFilename =
reFilename.exec(decodeURIComponent(suggestedFilename))[0];
} catch(e) { // Possible (extremely rare) errors:
// URIError "Malformed URI", e.g. for "%AA.pdf"
// TypeError "null has no properties", e.g. for "%2F.pdf"
}
}
}
return suggestedFilename || 'document.pdf';
}
var ProgressBar = (function ProgressBarClosure() {
function clamp(v, min, max) {
return Math.min(Math.max(v, min), max);
}
function ProgressBar(id, opts) {
this.visible = true;
// Fetch the sub-elements for later.
this.div = document.querySelector(id + ' .progress');
// Get the loading bar element, so it can be resized to fit the viewer.
this.bar = this.div.parentNode;
// Get options, with sensible defaults.
this.height = opts.height || 100;
this.width = opts.width || 100;
this.units = opts.units || '%';
// Initialize heights.
this.div.style.height = this.height + this.units;
this.percent = 0;
}
ProgressBar.prototype = {
updateBar: function ProgressBar_updateBar() {
if (this._indeterminate) {
this.div.classList.add('indeterminate');
this.div.style.width = this.width + this.units;
return;
}
this.div.classList.remove('indeterminate');
var progressSize = this.width * this._percent / 100;
this.div.style.width = progressSize + this.units;
},
get percent() {
return this._percent;
},
set percent(val) {
this._indeterminate = isNaN(val);
this._percent = clamp(val, 0, 100);
this.updateBar();
},
setWidth: function ProgressBar_setWidth(viewer) {
if (viewer) {
var container = viewer.parentNode;
var scrollbarWidth = container.offsetWidth - viewer.offsetWidth;
if (scrollbarWidth > 0) {
this.bar.setAttribute('style', 'width: calc(100% - ' +
scrollbarWidth + 'px);');
}
}
},
hide: function ProgressBar_hide() {
if (!this.visible) {
return;
}
this.visible = false;
this.bar.classList.add('hidden');
document.body.classList.remove('loadingInProgress');
},
show: function ProgressBar_show() {
if (this.visible) {
return;
}
this.visible = true;
document.body.classList.add('loadingInProgress');
this.bar.classList.remove('hidden');
}
};
return ProgressBar;
})();
/**
* Performs navigation functions inside PDF, such as opening specified page,
* or destination.
* @class
* @implements {IPDFLinkService}
*/
var PDFLinkService = (function () {
/**
* @constructs PDFLinkService
*/
function PDFLinkService() {
this.baseUrl = null;
this.pdfDocument = null;
this.pdfViewer = null;
this.pdfHistory = null;
this._pagesRefCache = null;
}
PDFLinkService.prototype = {
setDocument: function PDFLinkService_setDocument(pdfDocument, baseUrl) {
this.baseUrl = baseUrl;
this.pdfDocument = pdfDocument;
this._pagesRefCache = Object.create(null);
},
setViewer: function PDFLinkService_setViewer(pdfViewer) {
this.pdfViewer = pdfViewer;
},
setHistory: function PDFLinkService_setHistory(pdfHistory) {
this.pdfHistory = pdfHistory;
},
/**
* @returns {number}
*/
get pagesCount() {
return this.pdfDocument.numPages;
},
/**
* @returns {number}
*/
get page() {
return this.pdfViewer.currentPageNumber;
},
/**
* @param {number} value
*/
set page(value) {
this.pdfViewer.currentPageNumber = value;
},
/**
* @param dest - The PDF destination object.
*/
navigateTo: function PDFLinkService_navigateTo(dest) {
var destString = '';
var self = this;
var goToDestination = function(destRef) {
// dest array looks like that: <page-ref> </XYZ|FitXXX> <args..>
var pageNumber = destRef instanceof Object ?
self._pagesRefCache[destRef.num + ' ' + destRef.gen + ' R'] :
(destRef + 1);
if (pageNumber) {
if (pageNumber > self.pagesCount) {
pageNumber = self.pagesCount;
}
self.pdfViewer.scrollPageIntoView(pageNumber, dest);
if (self.pdfHistory) {
// Update the browsing history.
self.pdfHistory.push({
dest: dest,
hash: destString,
page: pageNumber
});
}
} else {
self.pdfDocument.getPageIndex(destRef).then(function (pageIndex) {
var pageNum = pageIndex + 1;
var cacheKey = destRef.num + ' ' + destRef.gen + ' R';
self._pagesRefCache[cacheKey] = pageNum;
goToDestination(destRef);
});
}
};
var destinationPromise;
if (typeof dest === 'string') {
destString = dest;
destinationPromise = this.pdfDocument.getDestination(dest);
} else {
destinationPromise = Promise.resolve(dest);
}
destinationPromise.then(function(destination) {
dest = destination;
if (!(destination instanceof Array)) {
return; // invalid destination
}
goToDestination(destination[0]);
});
},
/**
* @param dest - The PDF destination object.
* @returns {string} The hyperlink to the PDF object.
*/
getDestinationHash: function PDFLinkService_getDestinationHash(dest) {
if (typeof dest === 'string') {
return this.getAnchorUrl('#' + escape(dest));
}
if (dest instanceof Array) {
var destRef = dest[0]; // see navigateTo method for dest format
var pageNumber = destRef instanceof Object ?
this._pagesRefCache[destRef.num + ' ' + destRef.gen + ' R'] :
(destRef + 1);
if (pageNumber) {
var pdfOpenParams = this.getAnchorUrl('#page=' + pageNumber);
var destKind = dest[1];
if (typeof destKind === 'object' && 'name' in destKind &&
destKind.name === 'XYZ') {
var scale = (dest[4] || this.pdfViewer.currentScaleValue);
var scaleNumber = parseFloat(scale);
if (scaleNumber) {
scale = scaleNumber * 100;
}
pdfOpenParams += '&zoom=' + scale;
if (dest[2] || dest[3]) {
pdfOpenParams += ',' + (dest[2] || 0) + ',' + (dest[3] || 0);
}
}
return pdfOpenParams;
}
}
return this.getAnchorUrl('');
},
/**
* Prefix the full url on anchor links to make sure that links are resolved
* relative to the current URL instead of the one defined in <base href>.
* @param {String} anchor The anchor hash, including the #.
* @returns {string} The hyperlink to the PDF object.
*/
getAnchorUrl: function PDFLinkService_getAnchorUrl(anchor) {
return (this.baseUrl || '') + anchor;
},
/**
* @param {string} hash
*/
setHash: function PDFLinkService_setHash(hash) {
if (hash.indexOf('=') >= 0) {
var params = parseQueryString(hash);
// borrowing syntax from "Parameters for Opening PDF Files"
if ('nameddest' in params) {
if (this.pdfHistory) {
this.pdfHistory.updateNextHashParam(params.nameddest);
}
this.navigateTo(params.nameddest);
return;
}
var pageNumber, dest;
if ('page' in params) {
pageNumber = (params.page | 0) || 1;
}
if ('zoom' in params) {
// Build the destination array.
var zoomArgs = params.zoom.split(','); // scale,left,top
var zoomArg = zoomArgs[0];
var zoomArgNumber = parseFloat(zoomArg);
if (zoomArg.indexOf('Fit') === -1) {
// If the zoomArg is a number, it has to get divided by 100. If it's
// a string, it should stay as it is.
dest = [null, { name: 'XYZ' },
zoomArgs.length > 1 ? (zoomArgs[1] | 0) : null,
zoomArgs.length > 2 ? (zoomArgs[2] | 0) : null,
(zoomArgNumber ? zoomArgNumber / 100 : zoomArg)];
} else {
if (zoomArg === 'Fit' || zoomArg === 'FitB') {
dest = [null, { name: zoomArg }];
} else if ((zoomArg === 'FitH' || zoomArg === 'FitBH') ||
(zoomArg === 'FitV' || zoomArg === 'FitBV')) {
dest = [null, { name: zoomArg },
zoomArgs.length > 1 ? (zoomArgs[1] | 0) : null];
} else if (zoomArg === 'FitR') {
if (zoomArgs.length !== 5) {
console.error('PDFLinkService_setHash: ' +
'Not enough parameters for \'FitR\'.');
} else {
dest = [null, { name: zoomArg },
(zoomArgs[1] | 0), (zoomArgs[2] | 0),
(zoomArgs[3] | 0), (zoomArgs[4] | 0)];
}
} else {
console.error('PDFLinkService_setHash: \'' + zoomArg +
'\' is not a valid zoom value.');
}
}
}
if (dest) {
this.pdfViewer.scrollPageIntoView(pageNumber || this.page, dest);
} else if (pageNumber) {
this.page = pageNumber; // simple page
}
if ('pagemode' in params) {
var event = document.createEvent('CustomEvent');
event.initCustomEvent('pagemode', true, true, {
mode: params.pagemode,
});
this.pdfViewer.container.dispatchEvent(event);
}
} else if (/^\d+$/.test(hash)) { // page number
this.page = hash;
} else { // named destination
if (this.pdfHistory) {
this.pdfHistory.updateNextHashParam(unescape(hash));
}
this.navigateTo(unescape(hash));
}
},
/**
* @param {string} action
*/
executeNamedAction: function PDFLinkService_executeNamedAction(action) {
// See PDF reference, table 8.45 - Named action
switch (action) {
case 'GoBack':
if (this.pdfHistory) {
this.pdfHistory.back();
}
break;
case 'GoForward':
if (this.pdfHistory) {
this.pdfHistory.forward();
}
break;
case 'NextPage':
this.page++;
break;
case 'PrevPage':
this.page--;
break;
case 'LastPage':
this.page = this.pagesCount;
break;
case 'FirstPage':
this.page = 1;
break;
default:
break; // No action according to spec
}
var event = document.createEvent('CustomEvent');
event.initCustomEvent('namedaction', true, true, {
action: action
});
this.pdfViewer.container.dispatchEvent(event);
},
/**
* @param {number} pageNum - page number.
* @param {Object} pageRef - reference to the page.
*/
cachePageRef: function PDFLinkService_cachePageRef(pageNum, pageRef) {
var refStr = pageRef.num + ' ' + pageRef.gen + ' R';
this._pagesRefCache[refStr] = pageNum;
}
};
return PDFLinkService;
})();
var PresentationModeState = {
UNKNOWN: 0,
NORMAL: 1,
CHANGING: 2,
FULLSCREEN: 3,
};
var IGNORE_CURRENT_POSITION_ON_ZOOM = false;
var DEFAULT_CACHE_SIZE = 10;
var CLEANUP_TIMEOUT = 30000;
var RenderingStates = {
INITIAL: 0,
RUNNING: 1,
PAUSED: 2,
FINISHED: 3
};
/**
* Controls rendering of the views for pages and thumbnails.
* @class
*/
var PDFRenderingQueue = (function PDFRenderingQueueClosure() {
/**
* @constructs
*/
function PDFRenderingQueue() {
this.pdfViewer = null;
this.pdfThumbnailViewer = null;
this.onIdle = null;
this.highestPriorityPage = null;
this.idleTimeout = null;
this.printing = false;
this.isThumbnailViewEnabled = false;
}
PDFRenderingQueue.prototype = /** @lends PDFRenderingQueue.prototype */ {
/**
* @param {PDFViewer} pdfViewer
*/
setViewer: function PDFRenderingQueue_setViewer(pdfViewer) {
this.pdfViewer = pdfViewer;
},
/**
* @param {PDFThumbnailViewer} pdfThumbnailViewer
*/
setThumbnailViewer:
function PDFRenderingQueue_setThumbnailViewer(pdfThumbnailViewer) {
this.pdfThumbnailViewer = pdfThumbnailViewer;
},
/**
* @param {IRenderableView} view
* @returns {boolean}
*/
isHighestPriority: function PDFRenderingQueue_isHighestPriority(view) {
return this.highestPriorityPage === view.renderingId;
},
renderHighestPriority: function
PDFRenderingQueue_renderHighestPriority(currentlyVisiblePages) {
if (this.idleTimeout) {
clearTimeout(this.idleTimeout);
this.idleTimeout = null;
}
// Pages have a higher priority than thumbnails, so check them first.
if (this.pdfViewer.forceRendering(currentlyVisiblePages)) {
return;
}
// No pages needed rendering so check thumbnails.
if (this.pdfThumbnailViewer && this.isThumbnailViewEnabled) {
if (this.pdfThumbnailViewer.forceRendering()) {
return;
}
}
if (this.printing) {
// If printing is currently ongoing do not reschedule cleanup.
return;
}
if (this.onIdle) {
this.idleTimeout = setTimeout(this.onIdle.bind(this), CLEANUP_TIMEOUT);
}
},
getHighestPriority: function
PDFRenderingQueue_getHighestPriority(visible, views, scrolledDown) {
// The state has changed figure out which page has the highest priority to
// render next (if any).
// Priority:
// 1 visible pages
// 2 if last scrolled down page after the visible pages
// 2 if last scrolled up page before the visible pages
var visibleViews = visible.views;
var numVisible = visibleViews.length;
if (numVisible === 0) {
return false;
}
for (var i = 0; i < numVisible; ++i) {
var view = visibleViews[i].view;
if (!this.isViewFinished(view)) {
return view;
}
}
// All the visible views have rendered, try to render next/previous pages.
if (scrolledDown) {
var nextPageIndex = visible.last.id;
// ID's start at 1 so no need to add 1.
if (views[nextPageIndex] &&
!this.isViewFinished(views[nextPageIndex])) {
return views[nextPageIndex];
}
} else {
var previousPageIndex = visible.first.id - 2;
if (views[previousPageIndex] &&
!this.isViewFinished(views[previousPageIndex])) {
return views[previousPageIndex];
}
}
// Everything that needs to be rendered has been.
return null;
},
/**
* @param {IRenderableView} view
* @returns {boolean}
*/
isViewFinished: function PDFRenderingQueue_isViewFinished(view) {
return view.renderingState === RenderingStates.FINISHED;
},
/**
* Render a page or thumbnail view. This calls the appropriate function
* based on the views state. If the view is already rendered it will return
* false.
* @param {IRenderableView} view
*/
renderView: function PDFRenderingQueue_renderView(view) {
var state = view.renderingState;
switch (state) {
case RenderingStates.FINISHED:
return false;
case RenderingStates.PAUSED:
this.highestPriorityPage = view.renderingId;
view.resume();
break;
case RenderingStates.RUNNING:
this.highestPriorityPage = view.renderingId;
break;
case RenderingStates.INITIAL:
this.highestPriorityPage = view.renderingId;
var continueRendering = function () {
this.renderHighestPriority();
}.bind(this);
view.draw().then(continueRendering, continueRendering);
break;
}
return true;
},
};
return PDFRenderingQueue;
})();
var TEXT_LAYER_RENDER_DELAY = 200; // ms
/**
* @typedef {Object} PDFPageViewOptions
* @property {HTMLDivElement} container - The viewer element.
* @property {number} id - The page unique ID (normally its number).
* @property {number} scale - The page scale display.
* @property {PageViewport} defaultViewport - The page viewport.
* @property {PDFRenderingQueue} renderingQueue - The rendering queue object.
* @property {IPDFTextLayerFactory} textLayerFactory
* @property {IPDFAnnotationLayerFactory} annotationLayerFactory
*/
/**
* @class
* @implements {IRenderableView}
*/
var PDFPageView = (function PDFPageViewClosure() {
/**
* @constructs PDFPageView
* @param {PDFPageViewOptions} options
*/
function PDFPageView(options) {
var container = options.container;
var id = options.id;
var scale = options.scale;
var defaultViewport = options.defaultViewport;
var renderingQueue = options.renderingQueue;
var textLayerFactory = options.textLayerFactory;
var annotationLayerFactory = options.annotationLayerFactory;
this.id = id;
this.renderingId = 'page' + id;
this.rotation = 0;
this.scale = scale || DEFAULT_SCALE;
this.viewport = defaultViewport;
this.pdfPageRotate = defaultViewport.rotation;
this.hasRestrictedScaling = false;
this.renderingQueue = renderingQueue;
this.textLayerFactory = textLayerFactory;
this.annotationLayerFactory = annotationLayerFactory;
this.renderingState = RenderingStates.INITIAL;
this.resume = null;
this.onBeforeDraw = null;
this.onAfterDraw = null;
this.textLayer = null;
this.zoomLayer = null;
this.annotationLayer = null;
var div = document.createElement('div');
div.id = 'pageContainer' + this.id;
div.className = 'page';
div.style.width = Math.floor(this.viewport.width) + 'px';
div.style.height = Math.floor(this.viewport.height) + 'px';
div.setAttribute('data-page-number', this.id);
this.div = div;
container.appendChild(div);
}
PDFPageView.prototype = {
setPdfPage: function PDFPageView_setPdfPage(pdfPage) {
this.pdfPage = pdfPage;
this.pdfPageRotate = pdfPage.rotate;
var totalRotation = (this.rotation + this.pdfPageRotate) % 360;
this.viewport = pdfPage.getViewport(this.scale * CSS_UNITS,
totalRotation);
this.stats = pdfPage.stats;
this.reset();
},
destroy: function PDFPageView_destroy() {
this.zoomLayer = null;
this.reset();
if (this.pdfPage) {
this.pdfPage.cleanup();
}
},
reset: function PDFPageView_reset(keepZoomLayer, keepAnnotations) {
if (this.renderTask) {
this.renderTask.cancel();
}
this.resume = null;
this.renderingState = RenderingStates.INITIAL;
var div = this.div;
div.style.width = Math.floor(this.viewport.width) + 'px';
div.style.height = Math.floor(this.viewport.height) + 'px';
var childNodes = div.childNodes;
var currentZoomLayerNode = (keepZoomLayer && this.zoomLayer) || null;
var currentAnnotationNode = (keepAnnotations && this.annotationLayer &&
this.annotationLayer.div) || null;
for (var i = childNodes.length - 1; i >= 0; i--) {
var node = childNodes[i];
if (currentZoomLayerNode === node || currentAnnotationNode === node) {
continue;
}
div.removeChild(node);
}
div.removeAttribute('data-loaded');
if (currentAnnotationNode) {
// Hide annotationLayer until all elements are resized
// so they are not displayed on the already-resized page
this.annotationLayer.hide();
} else {
this.annotationLayer = null;
}
if (this.canvas && !currentZoomLayerNode) {
// Zeroing the width and height causes Firefox to release graphics
// resources immediately, which can greatly reduce memory consumption.
this.canvas.width = 0;
this.canvas.height = 0;
delete this.canvas;
}
this.loadingIconDiv = document.createElement('div');