/
BookReader.js
5279 lines (4441 loc) · 189 KB
/
BookReader.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(c)2008-2009 Internet Archive. Software license AGPL version 3.
This file is part of BookReader.
BookReader is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
BookReader is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with BookReader. If not, see <http://www.gnu.org/licenses/>.
The BookReader source is hosted at http://github.com/openlibrary/bookreader/
*/
// BookReader()
//______________________________________________________________________________
// After you instantiate this object, you must supply the following
// book-specific functions, before calling init(). Some of these functions
// can just be stubs for simple books.
// - getPageWidth()
// - getPageHeight()
// - getPageURI()
// - getPageSide()
// - canRotatePage()
// - getPageNum()
// - getSpreadIndices()
// You must also add a numLeafs property before calling init().
function BookReader() {
// Mode constants
this.constMode1up = 1;
this.constMode2up = 2;
this.constModeThumb = 3;
this.reduce = 4;
this.padding = 10; // Padding in 1up
this.mode = this.constMode1up;
this.ui = 'full'; // UI mode
this.uiAutoHide = false; // Controls whether nav/toolbar will autohide
// thumbnail mode
this.thumbWidth = 100; // will be overridden during prepareThumbnailView
this.thumbRowBuffer = 2; // number of rows to pre-cache out a view
this.thumbColumns = 6; // default
this.thumbMaxLoading = 4; // number of thumbnails to load at once
this.thumbPadding = 10; // spacing between thumbnails
this.displayedRows=[];
this.displayedIndices = [];
//this.indicesToDisplay = [];
this.imgs = {};
this.prefetchedImgs = {}; //an object with numeric keys cooresponding to page index
this.timer = null;
this.animating = false;
this.auto = false;
this.autoTimer = null;
this.flipSpeed = 'fast';
this.twoPagePopUp = null;
this.leafEdgeTmp = null;
this.embedPopup = null;
this.printPopup = null;
this.searchTerm = '';
this.searchResults = null;
this.firstIndex = null;
this.lastDisplayableIndex2up = null;
// Should be overriden (before init) by custom implmentations.
this.logoURL = 'http://www.archive.org';
// Base URL for UI images - should be overriden (before init) by
// custom implementations.
// $$$ This is the same directory as the images referenced by relative
// path in the CSS. Would be better to automagically find that path.
this.imagesBaseURL = '/bookreader/images/';
// Zoom levels
// $$$ provide finer grained zooming
/*
this.reductionFactors = [ {reduce: 0.5, autofit: null},
{reduce: 1, autofit: null},
{reduce: 2, autofit: null},
{reduce: 4, autofit: null},
{reduce: 8, autofit: null},
{reduce: 16, autofit: null} ];
*/
/* The autofit code ensures that fit to width and fit to height will be available */
this.reductionFactors = [ {reduce: 0.5, autofit: null},
{reduce: 1, autofit: null},
{reduce: 2, autofit: null},
{reduce: 3, autofit: null},
{reduce: 4, autofit: null},
{reduce: 6, autofit: null} ];
// Object to hold parameters related to 1up mode
this.onePage = {
autofit: 'height' // valid values are height, width, none
};
// Object to hold parameters related to 2up mode
this.twoPage = {
coverInternalPadding: 0, // Width of cover
coverExternalPadding: 0, // Padding outside of cover
bookSpineDivWidth: 64, // Width of book spine $$$ consider sizing based on book length
autofit: 'auto'
};
// This object/dictionary controls which optional features are enabled
// XXXmang in progress
this.features = {
// search
// read aloud
// open library entry
// table of contents
// embed/share ui
// info ui
};
// Text-to-Speech params
this.ttsPlaying = false;
this.ttsIndex = null; //leaf index
this.ttsPosition = -1; //chunk (paragraph) number
this.ttsBuffering = false;
this.ttsPoller = null;
this.ttsFormat = null;
return this;
};
(function ($) {
// init()
//______________________________________________________________________________
BookReader.prototype.init = function() {
var startIndex = undefined;
this.pageScale = this.reduce; // preserve current reduce
// Find start index and mode if set in location hash
var params = {};
if (window.location.hash) {
// params explicitly set in URL
params = this.paramsFromFragment(window.location.hash);
} else {
// params not explicitly set, use defaults if we have them
if ('defaults' in this) {
params = this.paramsFromFragment(this.defaults);
}
}
// Sanitize/process parameters
if ( !this.canSwitchToMode( this.mode ) ) {
this.mode = this.constMode1up;
}
if ('undefined' != typeof(params.index)) {
startIndex = params.index;
} else if ('undefined' != typeof(params.page)) {
startIndex = this.getPageIndex(params.page);
}
if ('undefined' == typeof(startIndex)) {
if ('undefined' != typeof(this.titleLeaf)) {
// title leaf is known - but only use as default if book has a few pages
if (this.numLeafs > 2) {
startIndex = this.leafNumToIndex(this.titleLeaf);
}
}
}
if ('undefined' == typeof(startIndex)) {
startIndex = 0;
}
if ('undefined' != typeof(params.mode)) {
this.mode = params.mode;
}
// Set document title -- may have already been set in enclosing html for
// search engine visibility
document.title = this.shortTitle(50);
$("#BookReader").empty();
this.initToolbar(this.mode, this.ui); // Build inside of toolbar div
$("#BookReader").append("<div id='BRcontainer' dir='ltr'></div>");
$("#BRcontainer").append("<div id='BRpageview'></div>");
$("#BRcontainer").bind('scroll', this, function(e) {
e.data.loadLeafs();
});
this.setupKeyListeners();
this.startLocationPolling();
$(window).bind('resize', this, function(e) {
//console.log('resize!');
if (1 == e.data.mode) {
//console.log('centering 1page view');
if (e.data.autofit) {
e.data.resizePageView();
}
e.data.centerPageView();
$('#BRpageview').empty()
e.data.displayedIndices = [];
e.data.updateSearchHilites(); //deletes hilights but does not call remove()
e.data.loadLeafs();
} else if (3 == e.data.mode){
e.data.prepareThumbnailView();
} else {
//console.log('drawing 2 page view');
// We only need to prepare again in autofit (size of spread changes)
if (e.data.twoPage.autofit) {
e.data.prepareTwoPageView();
} else {
// Re-center if the scrollbars have disappeared
var center = e.data.twoPageGetViewCenter();
var doRecenter = false;
if (e.data.twoPage.totalWidth < $('#BRcontainer').attr('clientWidth')) {
center.percentageX = 0.5;
doRecenter = true;
}
if (e.data.twoPage.totalHeight < $('#BRcontainer').attr('clientHeight')) {
center.percentageY = 0.5;
doRecenter = true;
}
if (doRecenter) {
e.data.twoPageCenterView(center.percentageX, center.percentageY);
}
}
}
});
if (this.protected) {
$('.BRpagediv1up').live('contextmenu dragstart', this, function(e) {
return false;
});
$('.BRpageimage').live('contextmenu dragstart', this, function(e) {
return false;
});
$('.BRpagedivthumb').live('contextmenu dragstart', this, function(e) {
return false;
});
}
$('.BRpagediv1up').bind('mousedown', this, function(e) {
// $$$ the purpose of this is to disable selection of the image (makes it turn blue)
// but this also interferes with right-click. See https://bugs.edge.launchpad.net/gnubook/+bug/362626
return false;
});
// $$$ refactor this so it's enough to set the first index and call preparePageView
// (get rid of mode-specific logic at this point)
if (1 == this.mode) {
this.firstIndex = startIndex;
this.prepareOnePageView();
this.jumpToIndex(startIndex);
} else if (3 == this.mode) {
this.firstIndex = startIndex;
this.prepareThumbnailView();
this.jumpToIndex(startIndex);
} else {
this.displayedIndices=[0];
this.firstIndex = startIndex;
this.displayedIndices = [this.firstIndex];
//console.log('titleLeaf: %d', this.titleLeaf);
//console.log('displayedIndices: %s', this.displayedIndices);
this.prepareTwoPageView();
}
// Enact other parts of initial params
this.updateFromParams(params);
// We init the nav bar after the params processing so that the nav slider knows where
// it should start (doesn't jump after init)
if (this.ui == "embed") {
this.initEmbedNavbar();
} else {
this.initNavbar();
}
this.bindNavigationHandlers();
// Set strings in the UI
this.initUIStrings();
// Start AJAX request for OL data
if (this.getOpenLibraryRecord) {
this.getOpenLibraryRecord(this.gotOpenLibraryRecord);
}
}
BookReader.prototype.setupKeyListeners = function() {
var self = this;
var KEY_PGUP = 33;
var KEY_PGDOWN = 34;
var KEY_END = 35;
var KEY_HOME = 36;
var KEY_LEFT = 37;
var KEY_UP = 38;
var KEY_RIGHT = 39;
var KEY_DOWN = 40;
// We use document here instead of window to avoid a bug in jQuery on IE7
$(document).keydown(function(e) {
// Keyboard navigation
if (!self.keyboardNavigationIsDisabled(e)) {
switch(e.keyCode) {
case KEY_PGUP:
case KEY_UP:
// In 1up mode page scrolling is handled by browser
if (2 == self.mode) {
e.preventDefault();
self.prev();
}
break;
case KEY_DOWN:
case KEY_PGDOWN:
if (2 == self.mode) {
e.preventDefault();
self.next();
}
break;
case KEY_END:
e.preventDefault();
self.last();
break;
case KEY_HOME:
e.preventDefault();
self.first();
break;
case KEY_LEFT:
if (2 == self.mode) {
e.preventDefault();
self.left();
}
break;
case KEY_RIGHT:
if (2 == self.mode) {
e.preventDefault();
self.right();
}
break;
}
}
});
}
// drawLeafs()
//______________________________________________________________________________
BookReader.prototype.drawLeafs = function() {
if (1 == this.mode) {
this.drawLeafsOnePage();
} else if (3 == this.mode) {
this.drawLeafsThumbnail();
} else {
this.drawLeafsTwoPage();
}
}
// bindGestures(jElement)
//______________________________________________________________________________
BookReader.prototype.bindGestures = function(jElement) {
jElement.unbind('gesturechange').bind('gesturechange', function(e) {
e.preventDefault();
if (e.originalEvent.scale > 1.5) {
br.zoom(1);
} else if (e.originalEvent.scale < 0.6) {
br.zoom(-1);
}
});
}
BookReader.prototype.setClickHandler2UP = function( element, data, handler) {
//console.log('setting handler');
//console.log(element.tagName);
$(element).unbind('click').bind('click', data, function(e) {
handler(e);
});
}
// drawLeafsOnePage()
//______________________________________________________________________________
BookReader.prototype.drawLeafsOnePage = function() {
//alert('drawing leafs!');
this.timer = null;
var scrollTop = $('#BRcontainer').attr('scrollTop');
var scrollBottom = scrollTop + $('#BRcontainer').height();
//console.log('top=' + scrollTop + ' bottom='+scrollBottom);
var indicesToDisplay = [];
var i;
var leafTop = 0;
var leafBottom = 0;
for (i=0; i<this.numLeafs; i++) {
var height = parseInt(this._getPageHeight(i)/this.reduce);
leafBottom += height;
//console.log('leafTop = '+leafTop+ ' pageH = ' + this.pageH[i] + 'leafTop>=scrollTop=' + (leafTop>=scrollTop));
var topInView = (leafTop >= scrollTop) && (leafTop <= scrollBottom);
var bottomInView = (leafBottom >= scrollTop) && (leafBottom <= scrollBottom);
var middleInView = (leafTop <=scrollTop) && (leafBottom>=scrollBottom);
if (topInView | bottomInView | middleInView) {
//console.log('displayed: ' + this.displayedIndices);
//console.log('to display: ' + i);
indicesToDisplay.push(i);
}
leafTop += height +10;
leafBottom += 10;
}
// Based of the pages displayed in the view we set the current index
// $$$ we should consider the page in the center of the view to be the current one
var firstIndexToDraw = indicesToDisplay[0];
if (firstIndexToDraw != this.firstIndex) {
this.willChangeToIndex(firstIndexToDraw);
}
this.firstIndex = firstIndexToDraw;
// Update hash, but only if we're currently displaying a leaf
// Hack that fixes #365790
if (this.displayedIndices.length > 0) {
this.updateLocationHash();
}
if ((0 != firstIndexToDraw) && (1 < this.reduce)) {
firstIndexToDraw--;
indicesToDisplay.unshift(firstIndexToDraw);
}
var lastIndexToDraw = indicesToDisplay[indicesToDisplay.length-1];
if ( ((this.numLeafs-1) != lastIndexToDraw) && (1 < this.reduce) ) {
indicesToDisplay.push(lastIndexToDraw+1);
}
leafTop = 0;
var i;
for (i=0; i<firstIndexToDraw; i++) {
leafTop += parseInt(this._getPageHeight(i)/this.reduce) +10;
}
//var viewWidth = $('#BRpageview').width(); //includes scroll bar width
var viewWidth = $('#BRcontainer').attr('scrollWidth');
for (i=0; i<indicesToDisplay.length; i++) {
var index = indicesToDisplay[i];
var height = parseInt(this._getPageHeight(index)/this.reduce);
if (BookReader.util.notInArray(indicesToDisplay[i], this.displayedIndices)) {
var width = parseInt(this._getPageWidth(index)/this.reduce);
//console.log("displaying leaf " + indicesToDisplay[i] + ' leafTop=' +leafTop);
var div = document.createElement("div");
div.className = 'BRpagediv1up';
div.id = 'pagediv'+index;
div.style.position = "absolute";
$(div).css('top', leafTop + 'px');
var left = (viewWidth-width)>>1;
if (left<0) left = 0;
$(div).css('left', left+'px');
$(div).css('width', width+'px');
$(div).css('height', height+'px');
//$(div).text('loading...');
$('#BRpageview').append(div);
var img = document.createElement("img");
img.src = this._getPageURI(index, this.reduce, 0);
$(img).addClass('BRnoselect');
$(img).css('width', width+'px');
$(img).css('height', height+'px');
$(div).append(img);
} else {
//console.log("not displaying " + indicesToDisplay[i] + ' score=' + jQuery.inArray(indicesToDisplay[i], this.displayedIndices));
}
leafTop += height +10;
}
for (i=0; i<this.displayedIndices.length; i++) {
if (BookReader.util.notInArray(this.displayedIndices[i], indicesToDisplay)) {
var index = this.displayedIndices[i];
//console.log('Removing leaf ' + index);
//console.log('id='+'#pagediv'+index+ ' top = ' +$('#pagediv'+index).css('top'));
$('#pagediv'+index).remove();
} else {
//console.log('NOT Removing leaf ' + this.displayedIndices[i]);
}
}
this.displayedIndices = indicesToDisplay.slice();
this.updateSearchHilites();
if (null != this.getPageNum(firstIndexToDraw)) {
$("#BRpagenum").val(this.getPageNum(this.currentIndex()));
} else {
$("#BRpagenum").val('');
}
this.updateToolbarZoom(this.reduce);
}
// drawLeafsThumbnail()
//______________________________________________________________________________
// If seekIndex is defined, the view will be drawn with that page visible (without any
// animated scrolling)
BookReader.prototype.drawLeafsThumbnail = function( seekIndex ) {
//alert('drawing leafs!');
this.timer = null;
var viewWidth = $('#BRcontainer').attr('scrollWidth') - 20; // width minus buffer
//console.log('top=' + scrollTop + ' bottom='+scrollBottom);
var i;
var leafWidth;
var leafHeight;
var rightPos = 0;
var bottomPos = 0;
var maxRight = 0;
var currentRow = 0;
var leafIndex = 0;
var leafMap = [];
var self = this;
// Will be set to top of requested seek index, if set
var seekTop;
// Calculate the position of every thumbnail. $$$ cache instead of calculating on every draw
for (i=0; i<this.numLeafs; i++) {
leafWidth = this.thumbWidth;
if (rightPos + (leafWidth + this.thumbPadding) > viewWidth){
currentRow++;
rightPos = 0;
leafIndex = 0;
}
if (leafMap[currentRow]===undefined) { leafMap[currentRow] = {}; }
if (leafMap[currentRow].leafs===undefined) {
leafMap[currentRow].leafs = [];
leafMap[currentRow].height = 0;
leafMap[currentRow].top = 0;
}
leafMap[currentRow].leafs[leafIndex] = {};
leafMap[currentRow].leafs[leafIndex].num = i;
leafMap[currentRow].leafs[leafIndex].left = rightPos;
leafHeight = parseInt((this.getPageHeight(leafMap[currentRow].leafs[leafIndex].num)*this.thumbWidth)/this.getPageWidth(leafMap[currentRow].leafs[leafIndex].num), 10);
if (leafHeight > leafMap[currentRow].height) {
leafMap[currentRow].height = leafHeight;
}
if (leafIndex===0) { bottomPos += this.thumbPadding + leafMap[currentRow].height; }
rightPos += leafWidth + this.thumbPadding;
if (rightPos > maxRight) { maxRight = rightPos; }
leafIndex++;
if (i == seekIndex) {
seekTop = bottomPos - this.thumbPadding - leafMap[currentRow].height;
}
}
// reset the bottom position based on thumbnails
$('#BRpageview').height(bottomPos);
var pageViewBuffer = Math.floor(($('#BRcontainer').attr('scrollWidth') - maxRight) / 2) - 14;
// If seekTop is defined, seeking was requested and target found
if (typeof(seekTop) != 'undefined') {
$('#BRcontainer').scrollTop( seekTop );
}
var scrollTop = $('#BRcontainer').attr('scrollTop');
var scrollBottom = scrollTop + $('#BRcontainer').height();
var leafTop = 0;
var leafBottom = 0;
var rowsToDisplay = [];
// Visible leafs with least/greatest index
var leastVisible = this.numLeafs - 1;
var mostVisible = 0;
// Determine the thumbnails in view
for (i=0; i<leafMap.length; i++) {
leafBottom += this.thumbPadding + leafMap[i].height;
var topInView = (leafTop >= scrollTop) && (leafTop <= scrollBottom);
var bottomInView = (leafBottom >= scrollTop) && (leafBottom <= scrollBottom);
var middleInView = (leafTop <=scrollTop) && (leafBottom>=scrollBottom);
if (topInView | bottomInView | middleInView) {
//console.log('row to display: ' + j);
rowsToDisplay.push(i);
if (leafMap[i].leafs[0].num < leastVisible) {
leastVisible = leafMap[i].leafs[0].num;
}
if (leafMap[i].leafs[leafMap[i].leafs.length - 1].num > mostVisible) {
mostVisible = leafMap[i].leafs[leafMap[i].leafs.length - 1].num;
}
}
if (leafTop > leafMap[i].top) { leafMap[i].top = leafTop; }
leafTop = leafBottom;
}
// create a buffer of preloaded rows before and after the visible rows
var firstRow = rowsToDisplay[0];
var lastRow = rowsToDisplay[rowsToDisplay.length-1];
for (i=1; i<this.thumbRowBuffer+1; i++) {
if (lastRow+i < leafMap.length) { rowsToDisplay.push(lastRow+i); }
}
for (i=1; i<this.thumbRowBuffer+1; i++) {
if (firstRow-i >= 0) { rowsToDisplay.push(firstRow-i); }
}
// Create the thumbnail divs and images (lazy loaded)
var j;
var row;
var left;
var index;
var div;
var link;
var img;
var page;
for (i=0; i<rowsToDisplay.length; i++) {
if (BookReader.util.notInArray(rowsToDisplay[i], this.displayedRows)) {
row = rowsToDisplay[i];
for (j=0; j<leafMap[row].leafs.length; j++) {
index = j;
leaf = leafMap[row].leafs[j].num;
leafWidth = this.thumbWidth;
leafHeight = parseInt((this.getPageHeight(leaf)*this.thumbWidth)/this.getPageWidth(leaf), 10);
leafTop = leafMap[row].top;
left = leafMap[row].leafs[index].left + pageViewBuffer;
if ('rl' == this.pageProgression){
left = viewWidth - leafWidth - left;
}
div = document.createElement("div");
div.id = 'pagediv'+leaf;
div.style.position = "absolute";
div.className = "BRpagedivthumb";
left += this.thumbPadding;
$(div).css('top', leafTop + 'px');
$(div).css('left', left+'px');
$(div).css('width', leafWidth+'px');
$(div).css('height', leafHeight+'px');
//$(div).text('loading...');
// link to page in single page mode
link = document.createElement("a");
$(link).data('leaf', leaf);
$(link).bind('tap', function(event) {
self.firstIndex = $(this).data('leaf');
self.switchMode(self.constMode1up);
event.preventDefault();
event.stopPropagation();
});
$(div).append(link);
$('#BRpageview').append(div);
img = document.createElement("img");
var thumbReduce = Math.floor(this.getPageWidth(leaf) / this.thumbWidth);
$(img).attr('src', this.imagesBaseURL + 'transparent.png')
.css({'width': leafWidth+'px', 'height': leafHeight+'px' })
.addClass('BRlazyload')
// Store the URL of the image that will replace this one
.data('srcURL', this._getPageURI(leaf, thumbReduce));
$(link).append(img);
//console.log('displaying thumbnail: ' + leaf);
}
}
}
// Remove thumbnails that are not to be displayed
var k;
for (i=0; i<this.displayedRows.length; i++) {
if (BookReader.util.notInArray(this.displayedRows[i], rowsToDisplay)) {
row = this.displayedRows[i];
// $$$ Safari doesn't like the comprehension
//var rowLeafs = [leaf.num for each (leaf in leafMap[row].leafs)];
//console.log('Removing row ' + row + ' ' + rowLeafs);
for (k=0; k<leafMap[row].leafs.length; k++) {
index = leafMap[row].leafs[k].num;
//console.log('Removing leaf ' + index);
$('#pagediv'+index).remove();
}
} else {
// var mRow = this.displayedRows[i];
// var mLeafs = '[' + [leaf.num for each (leaf in leafMap[mRow].leafs)] + ']';
// console.log('NOT Removing row ' + mRow + ' ' + mLeafs);
}
}
// Update which page is considered current to make sure a visible page is the current one
var currentIndex = this.currentIndex();
// console.log('current ' + currentIndex);
// console.log('least visible ' + leastVisible + ' most visible ' + mostVisible);
if (currentIndex < leastVisible) {
this.willChangeToIndex(leastVisible);
this.setCurrentIndex(leastVisible);
} else if (currentIndex > mostVisible) {
this.willChangeToIndex(mostVisible);
this.setCurrentIndex(mostVisible);
}
this.displayedRows = rowsToDisplay.slice();
// Update hash, but only if we're currently displaying a leaf
// Hack that fixes #365790
if (this.displayedRows.length > 0) {
this.updateLocationHash();
}
// remove previous highlights
$('.BRpagedivthumb_highlight').removeClass('BRpagedivthumb_highlight');
// highlight current page
$('#pagediv'+this.currentIndex()).addClass('BRpagedivthumb_highlight');
this.lazyLoadThumbnails();
// Update page number box. $$$ refactor to function
if (null !== this.getPageNum(this.currentIndex())) {
$("#BRpagenum").val(this.getPageNum(this.currentIndex()));
} else {
$("#BRpagenum").val('');
}
this.updateToolbarZoom(this.reduce);
}
BookReader.prototype.lazyLoadThumbnails = function() {
// console.log('lazy load');
// We check the complete property since load may not be fired if loading from the cache
$('.BRlazyloading').filter('[complete=true]').removeClass('BRlazyloading');
var loading = $('.BRlazyloading').length;
var toLoad = this.thumbMaxLoading - loading;
// console.log(' ' + loading + ' thumbnails loading');
// console.log(' this.thumbMaxLoading ' + this.thumbMaxLoading);
var self = this;
if (toLoad > 0) {
// $$$ TODO load those near top (but not beyond) page view first
$('#BRpageview img.BRlazyload').filter(':lt(' + toLoad + ')').each( function() {
self.lazyLoadImage(this);
});
}
}
BookReader.prototype.lazyLoadImage = function (dummyImage) {
//console.log(' lazy load started for ' + $(dummyImage).data('srcURL').match('([0-9]{4}).jp2')[1] );
var img = new Image();
var self = this;
$(img)
.addClass('BRlazyloading')
.one('load', function() {
//if (console) { console.log(' onload ' + $(this).attr('src').match('([0-9]{4}).jp2')[1]); };
$(this).removeClass('BRlazyloading');
// $$$ Calling lazyLoadThumbnails here was causing stack overflow on IE so
// we call the function after a slight delay. Also the img.complete property
// is not yet set in IE8 inside this onload handler
setTimeout(function() { self.lazyLoadThumbnails(); }, 100);
})
.one('error', function() {
// Remove class so we no longer count as loading
$(this).removeClass('BRlazyloading');
})
//the width set with .attr is ignored by Internet Explorer, causing it to show the image at its original size
//but with this one line of css, even IE shows the image at the proper size
.css({
'width': $(dummyImage).width()+'px',
'height': $(dummyImage).height()+'px'
})
.attr({
'width': $(dummyImage).width(),
'height': $(dummyImage).height(),
'src': $(dummyImage).data('srcURL')
});
// replace with the new img
$(dummyImage).before(img).remove();
img = null; // tidy up closure
}
// drawLeafsTwoPage()
//______________________________________________________________________________
BookReader.prototype.drawLeafsTwoPage = function() {
var scrollTop = $('#BRtwopageview').attr('scrollTop');
var scrollBottom = scrollTop + $('#BRtwopageview').height();
// $$$ we should use calculated values in this.twoPage (recalc if necessary)
var indexL = this.twoPage.currentIndexL;
var heightL = this._getPageHeight(indexL);
var widthL = this._getPageWidth(indexL);
var leafEdgeWidthL = this.leafEdgeWidth(indexL);
var leafEdgeWidthR = this.twoPage.edgeWidth - leafEdgeWidthL;
//var bookCoverDivWidth = this.twoPage.width*2 + 20 + this.twoPage.edgeWidth; // $$$ hardcoded cover width
var bookCoverDivWidth = this.twoPage.bookCoverDivWidth;
//console.log(leafEdgeWidthL);
var middle = this.twoPage.middle; // $$$ getter instead?
var top = this.twoPageTop();
var bookCoverDivLeft = this.twoPage.bookCoverDivLeft;
this.twoPage.scaledWL = this.getPageWidth2UP(indexL);
this.twoPage.gutter = this.twoPageGutter();
this.prefetchImg(indexL);
$(this.prefetchedImgs[indexL]).css({
position: 'absolute',
left: this.twoPage.gutter-this.twoPage.scaledWL+'px',
right: '',
top: top+'px',
height: this.twoPage.height +'px', // $$$ height forced the same for both pages
width: this.twoPage.scaledWL + 'px',
zIndex: 2
}).appendTo('#BRtwopageview');
var indexR = this.twoPage.currentIndexR;
var heightR = this._getPageHeight(indexR);
var widthR = this._getPageWidth(indexR);
// $$$ should use getwidth2up?
//var scaledWR = this.twoPage.height*widthR/heightR;
this.twoPage.scaledWR = this.getPageWidth2UP(indexR);
this.prefetchImg(indexR);
$(this.prefetchedImgs[indexR]).css({
position: 'absolute',
left: this.twoPage.gutter+'px',
right: '',
top: top+'px',
height: this.twoPage.height + 'px', // $$$ height forced the same for both pages
width: this.twoPage.scaledWR + 'px',
zIndex: 2
}).appendTo('#BRtwopageview');
this.displayedIndices = [this.twoPage.currentIndexL, this.twoPage.currentIndexR];
this.setMouseHandlers2UP();
this.twoPageSetCursor();
this.updatePageNumBox2UP();
this.updateToolbarZoom(this.reduce);
// this.twoPagePlaceFlipAreas(); // No longer used
}
// updatePageNumBox2UP
//______________________________________________________________________________
BookReader.prototype.updatePageNumBox2UP = function() {
if (null != this.getPageNum(this.twoPage.currentIndexL)) {
$("#BRpagenum").val(this.getPageNum(this.currentIndex()));
} else {
$("#BRpagenum").val('');
}
this.updateLocationHash();
}
// loadLeafs()
//______________________________________________________________________________
BookReader.prototype.loadLeafs = function() {
var self = this;
if (null == this.timer) {
this.timer=setTimeout(function(){self.drawLeafs()},250);
} else {
clearTimeout(this.timer);
this.timer=setTimeout(function(){self.drawLeafs()},250);
}
}
// zoom(direction)
//
// Pass 1 to zoom in, anything else to zoom out
//______________________________________________________________________________
BookReader.prototype.zoom = function(direction) {
switch (this.mode) {
case this.constMode1up:
if (direction == 1) {
// XXX other cases
return this.zoom1up('in');
} else {
return this.zoom1up('out');
}
case this.constMode2up:
if (direction == 1) {
// XXX other cases
return this.zoom2up('in');
} else {
return this.zoom2up('out');
}
case this.constModeThumb:
// XXX update zoomThumb for named directions
return this.zoomThumb(direction);
}
}
// zoom1up(dir)
//______________________________________________________________________________
BookReader.prototype.zoom1up = function(direction) {
if (2 == this.mode) { //can only zoom in 1-page mode
this.switchMode(1);
return;
}
var reduceFactor = this.nextReduce(this.reduce, direction, this.onePage.reductionFactors);
if (this.reduce == reduceFactor.reduce) {
// Already at this level
return;
}
this.reduce = reduceFactor.reduce; // $$$ incorporate into function
this.onePage.autofit = reduceFactor.autofit;
this.pageScale = this.reduce; // preserve current reduce
this.resizePageView();
$('#BRpageview').empty()
this.displayedIndices = [];
this.loadLeafs();
this.updateToolbarZoom(this.reduce);
// Recalculate search hilites
this.removeSearchHilites();
this.updateSearchHilites();
}
// resizePageView()
//______________________________________________________________________________
BookReader.prototype.resizePageView = function() {
// $$$ This code assumes 1up mode
// e.g. does not preserve position in thumbnail mode
// See http://bugs.launchpad.net/bookreader/+bug/552972
switch (this.mode) {
case this.constMode1up: