forked from Simbul/baker
/
RootViewController.m
executable file
·1507 lines (1245 loc) · 58 KB
/
RootViewController.m
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
//
// RootViewController.m
// Baker
//
// ==========================================================================================
//
// Copyright (c) 2010-2011, Davide Casali, Marco Colombo, Alessandro Morandi
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without modification, are
// permitted provided that the following conditions are met:
//
// Redistributions of source code must retain the above copyright notice, this list of
// conditions and the following disclaimer.
// Redistributions in binary form must reproduce the above copyright notice, this list of
// conditions and the following disclaimer in the documentation and/or other materials
// provided with the distribution.
// Neither the name of the Baker Framework nor the names of its contributors may be used to
// endorse or promote products derived from this software without specific prior written
// permission.
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY
// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
// OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT
// SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
// INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
// LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
#import <QuartzCore/QuartzCore.h>
#import "RootViewController.h"
#import "Downloader.h"
#import "SSZipArchive.h"
#import "NSDictionary_JSONExtensions.h"
#import "PageTitleLabel.h"
#import "Utils.h"
// ALERT LABELS
#define OPEN_BOOK_MESSAGE @"Do you want to download "
#define OPEN_BOOK_CONFIRM @"Open book"
#define CLOSE_BOOK_MESSAGE @"Do you want to close this book?"
#define CLOSE_BOOK_CONFIRM @"Close book"
#define ZERO_PAGES_TITLE @"Whoops!"
#define ZERO_PAGES_MESSAGE @"Sorry, that book had no pages."
#define ERROR_FEEDBACK_TITLE @"Whoops!"
#define ERROR_FEEDBACK_MESSAGE @"There was a problem downloading the book."
#define ERROR_FEEDBACK_CONFIRM @"Retry"
#define EXTRACT_FEEDBACK_TITLE @"Extracting..."
#define ALERT_FEEDBACK_CANCEL @"Cancel"
#define INDEX_FILE_NAME @"index.html"
// IOS VERSION >= 5.0 MACRO
#ifndef kCFCoreFoundationVersionNumber_iPhoneOS_5_0
#define kCFCoreFoundationVersionNumber_iPhoneOS_5_0 675.00
#endif
#if __IPHONE_OS_VERSION_MAX_ALLOWED >= __IPHONE_5_0
#define IF_IOS5_OR_GREATER(...) \
if (kCFCoreFoundationVersionNumber >= kCFCoreFoundationVersionNumber_iPhoneOS_5_0) { \
__VA_ARGS__ \
}
#else
#define IF_IOS5_OR_GREATER(...)
#endif
@implementation RootViewController
#pragma mark - SYNTHESIS
@synthesize scrollView;
@synthesize currPage;
@synthesize currentPageNumber;
@synthesize availableOrientation;
@synthesize backgroundImageLandscape;
@synthesize backgroundImagePortrait;
#pragma mark - INIT
- (id)init {
self = [super initWithNibName:nil bundle:nil];
if (self) {
NSLog(@"• INIT");
// ****** INIT PROPERTIES
properties = [Properties properties];
// ****** DEVICE SCREEN BOUNDS
screenBounds = [[UIScreen mainScreen] bounds];
NSLog(@" Device Width: %f", screenBounds.size.width);
NSLog(@" Device Height: %f", screenBounds.size.height);
// ****** BOOK DIRECTORIES
NSArray *documentsPaths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsPath = [NSString stringWithString:[documentsPaths objectAtIndex:0]];
documentsBookPath = [[documentsPath stringByAppendingPathComponent:@"book"] retain];
bundleBookPath = [[[NSBundle mainBundle] pathForResource:@"book" ofType:nil] retain];
defaultSnapshotsPath = [[documentsPath stringByAppendingPathComponent:@"baker-snapshots"] retain];
// ****** BOOK ENVIRONMENT
pages = [[NSMutableArray array] retain];
toLoad = [[NSMutableArray array] retain];
pageDetails = [[NSMutableArray array] retain];
pageNameFromURL = nil;
anchorFromURL = nil;
tapNumber = 0;
stackedScrollingAnimations = 0;
currentPageFirstLoading = YES;
currentPageIsDelayingLoading = YES;
currentPageHasChanged = NO;
currentPageIsLocked = NO;
discardNextStatusBarToggle = NO;
// ****** LISTENER FOR DOWNLOAD NOTIFICATION
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(downloadBook:) name:@"downloadNotification" object:nil];
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(handleDownloadResult:) name:@"handleDownloadResult" object:nil];
[self setPageSize:[self getCurrentInterfaceOrientation]];
[self hideStatusBar];
// ****** SCROLLVIEW INIT
scrollView = [[UIScrollView alloc] initWithFrame:CGRectMake(0, 0, pageWidth, pageHeight)];
scrollView.autoresizingMask = UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight;
scrollView.showsHorizontalScrollIndicator = YES;
scrollView.showsVerticalScrollIndicator = NO;
scrollView.delaysContentTouches = NO;
scrollView.pagingEnabled = YES;
scrollView.delegate = self;
[self.view addSubview:scrollView];
// ****** INDEX WEBVIEW INIT
indexViewController = [[IndexViewController alloc] initWithBookBundlePath:bundleBookPath documentsBookPath:documentsBookPath fileName:INDEX_FILE_NAME webViewDelegate:self];
[self.view addSubview:indexViewController.view];
// ****** BOOK INIT
if ([[NSFileManager defaultManager] fileExistsAtPath:documentsBookPath]) {
[self initBook:documentsBookPath];
} else {
if ([[NSFileManager defaultManager] fileExistsAtPath:bundleBookPath]) {
[self initBook:bundleBookPath];
} else {
// Do something if there are no books available to show
}
}
}
return self;
}
- (void)setupWebView:(UIWebView *)webView {
NSLog(@"• Setup webView");
webView.delegate = self;
webView.autoresizingMask = UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight;
webView.mediaPlaybackRequiresUserAction = ![[properties get:@"-baker-media-autoplay", nil] boolValue];
webView.scalesPageToFit = [[properties get:@"zoomable", nil] boolValue];
BOOL verticalBounce = [[properties get:@"-baker-vertical-bounce", nil] boolValue];
for (UIView *subview in webView.subviews) {
if ([subview isKindOfClass:[UIScrollView class]]) {
((UIScrollView *)subview).bounces = verticalBounce;
}
}
}
- (void)setPageSize:(NSString *)orientation {
NSLog(@"• Set size for orientation: %@", orientation);
pageWidth = screenBounds.size.width;
pageHeight = screenBounds.size.height;
if ([orientation isEqualToString:@"landscape"]) {
pageWidth = screenBounds.size.height;
pageHeight = screenBounds.size.width;
}
}
- (void)setTappableAreaSize {
NSLog(@"• Set tappable area size");
int tappableAreaSize = screenBounds.size.width/16;
if (screenBounds.size.width < 768) {
tappableAreaSize = screenBounds.size.width/8;
}
upTapArea = CGRectMake(tappableAreaSize, 0, pageWidth - (tappableAreaSize * 2), tappableAreaSize);
downTapArea = CGRectMake(tappableAreaSize, pageHeight - tappableAreaSize, pageWidth - (tappableAreaSize * 2), tappableAreaSize);
leftTapArea = CGRectMake(0, tappableAreaSize, tappableAreaSize, pageHeight - (tappableAreaSize * 2));
rightTapArea = CGRectMake(pageWidth - tappableAreaSize, tappableAreaSize, tappableAreaSize, pageHeight - (tappableAreaSize * 2));
}
- (void)resetScrollView {
NSLog(@"• Reset scrollview subviews");
NSLog(@" Prevent page from changing until scrollview reset is finished");
[self lockPage:YES];
[self setTappableAreaSize];
for (NSMutableDictionary *details in pageDetails) {
for (NSString *key in details) {
UIView *value = [details objectForKey:key];
value.hidden = YES;
}
}
[self showPageDetails];
scrollView.contentSize = CGSizeMake(pageWidth * totalPages, pageHeight);
int scrollViewY = 0;
if (![UIApplication sharedApplication].statusBarHidden) {
scrollViewY = -20;
}
[UIView animateWithDuration:0.2
animations:^{ scrollView.frame = CGRectMake(0, scrollViewY, pageWidth, pageHeight); }];
if (prevPage && [prevPage.superview isEqual:scrollView]) {
prevPage.frame = [self frameForPage:currentPageNumber - 1];
[scrollView bringSubviewToFront:prevPage];
}
if (nextPage && [nextPage.superview isEqual:scrollView]) {
nextPage.frame = [self frameForPage:currentPageNumber + 1];
[scrollView bringSubviewToFront:nextPage];
}
if (currPage) {
currPage.frame = [self frameForPage:currentPageNumber];
}
[scrollView bringSubviewToFront:currPage];
[scrollView scrollRectToVisible:[self frameForPage:currentPageNumber] animated:NO];
NSLog(@" Unlock page changing");
[self lockPage:NO];
}
- (void)initPageDetails {
NSLog(@"• Init page details for the book pages");
for (int i = 0; i < totalPages; i++) {
UIColor *foregroundColor = [Utils colorWithHexString:[properties get:@"-baker-page-numbers-color", nil]];
id foregroundAlpha = [properties get:@"-baker-page-numbers-alpha", nil];
// ****** Background
UIImageView *backgroundView = [[UIImageView alloc] initWithFrame:CGRectMake(pageWidth * i, 0, pageWidth, pageHeight)];
[self setImageFor:backgroundView];
[scrollView addSubview:backgroundView];
[backgroundView release];
// ****** Spinners
UIActivityIndicatorView *spinner = [[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleGray];
spinner.backgroundColor = [UIColor clearColor];
IF_IOS5_OR_GREATER(
spinner.color = foregroundColor;
spinner.alpha = [(NSNumber*) foregroundAlpha floatValue];
);
CGRect frame = spinner.frame;
frame.origin.x = pageWidth * i + (pageWidth - frame.size.width) / 2;
frame.origin.y = (pageHeight - frame.size.height) / 2;
spinner.frame = frame;
[scrollView addSubview:spinner];
[spinner startAnimating];
[spinner release];
// ****** Numbers
UILabel *number = [[UILabel alloc] initWithFrame:CGRectMake(pageWidth * i + (pageWidth - 115) / 2, pageHeight / 2 - 55, 115, 30)];
number.backgroundColor = [UIColor clearColor];
number.font = [UIFont fontWithName:@"Helvetica" size:40.0];
number.textColor = foregroundColor;
number.textAlignment = UITextAlignmentCenter;
number.alpha = [(NSNumber*) foregroundAlpha floatValue];
number.text = [NSString stringWithFormat:@"%d", i + 1];
[scrollView addSubview:number];
[number release];
// ****** Title
PageTitleLabel *title = [[PageTitleLabel alloc]initWithFile:[pages objectAtIndex: i]];
[title setX:(pageWidth * i + ((pageWidth - title.frame.size.width) / 2)) Y:(pageHeight / 2 + 20)];
[scrollView addSubview:title];
[title release];
// ****** Store instances for later use
NSMutableDictionary *details = [NSMutableDictionary dictionaryWithObjectsAndKeys:spinner, @"spinner", number, @"number", title, @"title", backgroundView, @"background", nil];
[pageDetails insertObject:details atIndex:i];
}
if ([renderingType isEqualToString:@"screenshots"]) {
[self initSnapshots];
}
}
- (void)showPageDetails {
NSLog(@"• Show page details for the book pages");
for (int i = 0; i < totalPages; i++) {
if (pageDetails.count > i && [pageDetails objectAtIndex:i] != nil) {
NSDictionary *details = [NSDictionary dictionaryWithDictionary:[pageDetails objectAtIndex:i]];
UIView *snapView = [details objectForKey:[NSString stringWithFormat:@"snap-%@", [self getCurrentInterfaceOrientation]]];
if (snapView != nil)
{
snapView.hidden = NO;
}
else {
for (NSString *key in details) {
UIView *value = [details objectForKey:key];
if (value != nil) {
CGRect frame = value.frame;
if ([key isEqualToString:@"spinner"]) {
frame.origin.x = pageWidth * i + (pageWidth - frame.size.width) / 2;
frame.origin.y = (pageHeight - frame.size.height) / 2;
value.frame = frame;
value.hidden = NO;
} else if ([key isEqualToString:@"number"]) {
frame.origin.x = pageWidth * i + (pageWidth - 115) / 2;
frame.origin.y = pageHeight / 2 - 55;
value.frame = frame;
value.hidden = NO;
} else if ([key isEqualToString:@"title"]) {
frame.origin.x = pageWidth * i + (pageWidth - frame.size.width) / 2;
frame.origin.y = pageHeight / 2 + 20;
value.frame = frame;
value.hidden = NO;
} else if ([key isEqualToString:@"background"]) {
[self setImageFor:(UIImageView *)value];
frame.origin.x = pageWidth * i;
frame.size.width = pageWidth;
frame.size.height = pageHeight;
value.frame = frame;
value.hidden = NO;
} else {
value.hidden = YES;
}
}
}
}
}
}
}
- (void)resetPageDetails {
NSLog(@"• Reset page details array and empty screenshot directory");
for (NSMutableDictionary *details in pageDetails) {
for (NSString *key in details) {
UIView *value = [details objectForKey:key];
[value removeFromSuperview];
}
}
[pageDetails removeAllObjects];
[pages removeAllObjects];
}
- (void)initBookProperties:(NSString *)path {
NSString *filePath = [path stringByAppendingPathComponent:@"book.json"];
[properties loadManifest:filePath];
// ****** ORIENTATION
self.availableOrientation = [properties get:@"orientation", nil];
NSLog(@"available orientation: %@", availableOrientation);
// ****** RENDERING
renderingType = [[[properties get:@"-baker-rendering", nil] retain] autorelease];
NSLog(@"rendering type: %@", renderingType);
// ****** BACKGROUND
scrollView.backgroundColor = [Utils colorWithHexString:[properties get:@"-baker-background", nil]];
NSString *backgroundPathLandscape = [properties get:@"-baker-background-image-landscape", nil];
if (backgroundPathLandscape != NULL) {
backgroundImageLandscape = [UIImage imageNamed:backgroundPathLandscape];
} else {
backgroundImageLandscape = NULL;
}
NSString *backgroundPathPortrait = [properties get:@"-baker-background-image-portrait", nil];
if (backgroundPathPortrait != NULL) {
backgroundImagePortrait = [UIImage imageNamed:backgroundPathPortrait];
} else {
backgroundImagePortrait = NULL;
}
}
- (void)initBook:(NSString *)path {
NSLog(@"• Init Book");
[self initBookProperties:path];
[self resetPageDetails];
NSEnumerator *pagesEnumerator = [[properties get:@"contents", nil] objectEnumerator];
id page;
while ((page = [pagesEnumerator nextObject])) {
NSString *pageFile;
if ([page isKindOfClass:[NSString class]]) {
pageFile = [path stringByAppendingPathComponent:page];
} else if ([page isKindOfClass:[NSDictionary class]]) {
pageFile = [path stringByAppendingPathComponent:[page objectForKey:@"url"]];
}
if ([[NSFileManager defaultManager] fileExistsAtPath:pageFile]) {
[pages addObject:pageFile];
} else {
NSLog(@"Page %@ does not exist in %@", page, path);
}
}
totalPages = [pages count];
NSLog(@" Pages in this book: %d", totalPages);
if (totalPages > 0) {
// Check if there is a saved starting page
NSString *currPageToLoad = [[NSUserDefaults standardUserDefaults] objectForKey:@"lastPageViewed"];
currentPageNumber = 1;
if (currentPageFirstLoading && currPageToLoad != nil) {
currentPageNumber = [currPageToLoad intValue];
} else if (pageNameFromURL != nil) {
pageNameFromURL = nil;
NSString *fileNameFromURL = [path stringByAppendingPathComponent:pageNameFromURL];
for (int i = 0; i < totalPages; i++) {
if ([[pages objectAtIndex:i] isEqualToString:fileNameFromURL]) {
currentPageNumber = i + 1;
break;
}
}
}
currentPageIsDelayingLoading = YES;
[toLoad removeAllObjects];
cachedSnapshotsPath = [path stringByAppendingPathComponent:@"baker-snapshots"];
if (![[NSFileManager defaultManager] fileExistsAtPath:cachedSnapshotsPath])
{
if ([path isEqualToString:bundleBookPath]) {
cachedSnapshotsPath = defaultSnapshotsPath;
}
[[NSFileManager defaultManager] createDirectoryAtPath:cachedSnapshotsPath withIntermediateDirectories:YES attributes:nil error:nil];
}
[cachedSnapshotsPath retain];
[self initPageDetails];
[self resetScrollView];
[self addPageLoading:0];
if ([renderingType isEqualToString:@"three-cards"]) {
if (currentPageNumber != totalPages) {
[self addPageLoading:+1];
}
if (currentPageNumber != 1) {
[self addPageLoading:-1];
}
}
[self handlePageLoading];
[indexViewController loadContentFromBundle:[path isEqualToString:bundleBookPath]];
} else {
[[NSFileManager defaultManager] removeItemAtPath:path error:NULL];
feedbackAlert = [[UIAlertView alloc] initWithTitle:ZERO_PAGES_TITLE
message:ZERO_PAGES_MESSAGE
delegate:self
cancelButtonTitle:ALERT_FEEDBACK_CANCEL
otherButtonTitles:nil];
[feedbackAlert show];
[feedbackAlert release];
[self initBook:bundleBookPath];
}
}
- (void)setImageFor:(UIImageView *)view {
if (pageWidth > pageHeight && backgroundImageLandscape != NULL) {
// Landscape
view.image = backgroundImageLandscape;
} else if (pageWidth < pageHeight && backgroundImagePortrait != NULL) {
// Portrait
view.image = backgroundImagePortrait;
} else {
view.image = NULL;
}
}
#pragma mark - LOADING
- (BOOL)changePage:(int)page {
NSLog(@"• Check if page has changed");
BOOL pageChanged = NO;
if (page < 1)
{
currentPageNumber = 1;
}
else if (page > totalPages)
{
currentPageNumber = totalPages;
}
else if (page != currentPageNumber)
{
// While we are tapping, we don't want scrolling event to get in the way
scrollView.scrollEnabled = NO;
stackedScrollingAnimations++;
lastPageNumber = currentPageNumber;
currentPageNumber = page;
tapNumber = tapNumber + (lastPageNumber - currentPageNumber);
[self hideStatusBar];
[scrollView scrollRectToVisible:[self frameForPage:currentPageNumber] animated:YES];
[self gotoPageDelayer];
pageChanged = YES;
}
return pageChanged;
}
- (void)gotoPageDelayer {
// This delay is required in order to avoid stuttering when the animation runs.
// The animation lasts 0.5 seconds: so we start loading after that.
if (currentPageIsDelayingLoading) {
[NSObject cancelPreviousPerformRequestsWithTarget:self selector:@selector(gotoPage) object:nil];
}
currentPageIsDelayingLoading = YES;
[self performSelector:@selector(gotoPage) withObject:nil afterDelay:0.5];
}
- (void)gotoPage {
NSString *path = [NSString stringWithString:[pages objectAtIndex:currentPageNumber - 1]];
if ([[NSFileManager defaultManager] fileExistsAtPath:path] && tapNumber != 0) {
NSLog(@"• Goto page: book/%@", [[NSFileManager defaultManager] displayNameAtPath:path]);
if ([renderingType isEqualToString:@"three-cards"])
{
// ****** THREE CARD VIEW METHOD
// ****** Calculate move direction and normalize tapNumber
int direction = 1;
if (tapNumber < 0) {
direction = -direction;
tapNumber = -tapNumber;
}
NSLog(@" Tap number: %d", tapNumber);
if (tapNumber > 2) {
tapNumber = 0;
// ****** Moved away for more than 2 pages: RELOAD ALL pages
[toLoad removeAllObjects];
[currPage removeFromSuperview];
[nextPage removeFromSuperview];
[prevPage removeFromSuperview];
[self addPageLoading:0];
if (currentPageNumber < totalPages)
[self addPageLoading:+1];
if (currentPageNumber > 1)
[self addPageLoading:-1];
} else {
int tmpSlot = 0;
if (tapNumber == 2) {
// ****** Moved away for 2 pages: RELOAD CURRENT page
if (direction < 0) {
// ****** Move LEFT <<<
[prevPage removeFromSuperview];
UIWebView *tmpView = prevPage;
prevPage = nextPage;
nextPage = tmpView;
} else {
// ****** Move RIGHT >>>
[nextPage removeFromSuperview];
UIWebView *tmpView = nextPage;
nextPage = prevPage;
prevPage = tmpView;
}
// Adjust pages slot in the stack to reflect the webviews pointer change
for (int i = 0; i < [toLoad count]; i++) {
tmpSlot = -1 * [[[toLoad objectAtIndex:i] valueForKey:@"slot"] intValue];
[[toLoad objectAtIndex:i] setObject:[NSNumber numberWithInt:tmpSlot] forKey:@"slot"];
}
[currPage removeFromSuperview];
[self addPageLoading:0];
} else if (tapNumber == 1) {
if (direction < 0) {
// ****** Move LEFT <<<
[prevPage removeFromSuperview];
UIWebView *tmpView = prevPage;
prevPage = currPage;
currPage = nextPage;
nextPage = tmpView;
} else {
// ****** Move RIGHT >>>
[nextPage removeFromSuperview];
UIWebView *tmpView = nextPage;
nextPage = currPage;
currPage = prevPage;
prevPage = tmpView;
}
// Adjust pages slot in the stack to reflect the webviews pointer change
for (int i = 0; i < [toLoad count]; i++) {
tmpSlot = [[[toLoad objectAtIndex:i] valueForKey:@"slot"] intValue];
if (direction < 0) {
if (tmpSlot == +1) {
tmpSlot = 0;
} else if (tmpSlot == 0) {
tmpSlot = -1;
} else if (tmpSlot == -1) {
tmpSlot = +1;
}
} else {
if (tmpSlot == -1) {
tmpSlot = 0;
} else if (tmpSlot == 0) {
tmpSlot = +1;
} else if (tmpSlot == +1) {
tmpSlot = -1;
}
}
[[toLoad objectAtIndex:i] setObject:[NSNumber numberWithInt:tmpSlot] forKey:@"slot"];
}
// Since we are not loading anything we have to reset the delayer flag
currentPageIsDelayingLoading = NO;
}
[self getPageHeight];
tapNumber = 0;
if (direction < 0) {
// REMOVE OTHER NEXT page from toLoad stack
for (int i = 0; i < [toLoad count]; i++) {
if ([[[toLoad objectAtIndex:i] valueForKey:@"slot"] intValue] == +1) {
[toLoad removeObjectAtIndex:i];
}
}
// PRELOAD NEXT page
if (currentPageNumber < totalPages) {
[self addPageLoading:+1];
}
} else {
// REMOVE OTHER PREV page from toLoad stack
for (int i = 0; i < [toLoad count]; i++) {
if ([[[toLoad objectAtIndex:i] valueForKey:@"slot"] intValue] == -1) {
[toLoad removeObjectAtIndex:i];
}
}
// PRELOAD PREV page
if (currentPageNumber > 1) {
[self addPageLoading:-1];
}
}
}
[self handlePageLoading];
}
else
{
tapNumber = 0;
[toLoad removeAllObjects];
[currPage removeFromSuperview];
[self addPageLoading:0];
[self handlePageLoading];
}
}
}
- (void)lockPage:(BOOL)lock {
if (lock)
{
if (scrollView.scrollEnabled) {
scrollView.scrollEnabled = NO;
}
currentPageIsLocked = YES;
}
else
{
if (stackedScrollingAnimations == 0) {
scrollView.scrollEnabled = YES;
}
currentPageIsLocked = NO;
}
}
- (void)addPageLoading:(int)slot {
NSLog(@"• Add page to the loding queue");
NSArray *objs = [NSArray arrayWithObjects:[NSNumber numberWithInt:slot], [NSNumber numberWithInt:currentPageNumber + slot], nil];
NSArray *keys = [NSArray arrayWithObjects:@"slot", @"page", nil];
if (slot == 0) {
[toLoad insertObject:[NSMutableDictionary dictionaryWithObjects:objs forKeys:keys] atIndex:0];
} else {
[toLoad addObject:[NSMutableDictionary dictionaryWithObjects:objs forKeys:keys]];
}
}
- (void)handlePageLoading {
if ([toLoad count] != 0) {
int slot = [[[toLoad objectAtIndex:0] valueForKey:@"slot"] intValue];
int page = [[[toLoad objectAtIndex:0] valueForKey:@"page"] intValue];
NSLog(@"• Handle loading of slot %d with page %d", slot, page);
[toLoad removeObjectAtIndex:0];
if ([renderingType isEqualToString:@"screenshots"] && ![self checkSnapshotForPage:page andOrientation:[self getCurrentInterfaceOrientation]]) {
[self lockPage:YES];
}
[self loadSlot:slot withPage:page];
}
}
- (void)loadSlot:(int)slot withPage:(int)page {
NSLog(@"• Setup new page for loading");
UIWebView *webView = [[UIWebView alloc] init];
[self setupWebView:webView];
webView.frame = [self frameForPage:page];
webView.hidden = YES;
// ****** SELECT
// Since pointers can change at any time we've got to handle them directly on a slot basis.
// Save the page pointer to a temp view to avoid code redundancy make Baker go apeshit.
if (slot == 0) {
if (currPage) {
currPage.delegate = nil;
if ([currPage isLoading]) {
[currPage stopLoading];
}
[currPage release];
}
currPage = webView;
currentPageHasChanged = YES;
} else if (slot == +1) {
if (nextPage) {
nextPage.delegate = nil;
if ([nextPage isLoading]) {
[nextPage stopLoading];
}
[nextPage release];
}
nextPage = webView;
} else if (slot == -1) {
if (prevPage) {
prevPage.delegate = nil;
if ([prevPage isLoading]) {
[prevPage stopLoading];
}
[prevPage release];
}
prevPage = webView;
}
((UIScrollView *)[[webView subviews] objectAtIndex:0]).pagingEnabled = [[properties get:@"-baker-vertical-pagination", nil] boolValue];
[scrollView addSubview:webView];
[self loadWebView:webView withPage:page];
}
- (BOOL)loadWebView:(UIWebView*)webView withPage:(int)page {
NSString *path = [NSString stringWithString:[pages objectAtIndex:page - 1]];
if ([[NSFileManager defaultManager] fileExistsAtPath:path]) {
NSLog(@"• Loading: book/%@", [[NSFileManager defaultManager] displayNameAtPath:path]);
[webView loadRequest:[NSURLRequest requestWithURL:[NSURL fileURLWithPath:path]]];
return YES;
}
return NO;
}
#pragma mark - SCROLLVIEW
- (CGRect)frameForPage:(int)page {
return CGRectMake(pageWidth * (page - 1), 0, pageWidth, pageHeight);
}
- (void)scrollViewWillBeginDragging:(UIScrollView *)scroll {
NSLog(@"• Scrollview will begin dragging");
[self hideStatusBar];
}
- (void)scrollViewDidEndDragging:(UIScrollView *)scroll willDecelerate:(BOOL)decelerate {
NSLog(@"• Scrollview did end dragging");
}
- (void)scrollViewWillBeginDecelerating:(UIScrollView *)scroll {
NSLog(@"• Scrollview will begin decelerating");
}
- (void)scrollViewDidEndDecelerating:(UIScrollView *)scroll {
int page = (int)(scroll.contentOffset.x / pageWidth) + 1;
NSLog(@"• Swiping to page: %d", page);
if (currentPageNumber != page) {
lastPageNumber = currentPageNumber;
currentPageNumber = page;
tapNumber = tapNumber + (lastPageNumber - currentPageNumber);
currentPageIsDelayingLoading = YES;
[self gotoPage];
}
}
- (void)scrollViewDidEndScrollingAnimation:(UIScrollView *)scroll {
NSLog(@"• Scrollview did end scrolling animation");
stackedScrollingAnimations--;
if (stackedScrollingAnimations == 0) {
NSLog(@" Scroll enabled");
scroll.scrollEnabled = YES;
}
}
#pragma mark - WEBVIEW
- (BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType {
// Sent before a web view begins loading content, useful to trigger actions before the WebView.
NSLog(@"• Should webView load the page ?");
NSURL *url = [request URL];
if ([webView isEqual:prevPage])
{
NSLog(@" Page is prev page --> load page");
return YES;
}
else if ([webView isEqual:nextPage])
{
NSLog(@" Page is next page --> load page");
return YES;
}
else if (currentPageIsDelayingLoading)
{
NSLog(@" Page is current page and current page IS delaying loading --> load page");
currentPageIsDelayingLoading = NO;
return YES;
}
else
{
[self hideStatusBarDiscardingToggle:YES];
// ****** Handle URI schemes
if (url)
{
// Existing, checking if index...
if([[url lastPathComponent] isEqualToString:INDEX_FILE_NAME])
{
NSLog(@" Page is index --> load index");
return YES;
}
else
{
NSLog(@" Page is current page and current page IS NOT delaying loading --> handle clicked link: %@", [url absoluteString]);
// Not index, checking scheme...
if ([[url scheme] isEqualToString:@"file"])
{
// ****** Handle: file://
NSLog(@" Page is a link with scheme file:// --> load internal link");
anchorFromURL = [[url fragment] retain];
NSString *file = [[url relativePath] stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
int page = [pages indexOfObject:file];
if (page == NSNotFound)
{
// ****** Internal link, but not one of the book pages --> load page anyway
return YES;
}
page = page + 1;
if (![self changePage:page] && ![webView isEqual:indexViewController.view])
{
if (anchorFromURL == nil) {
return YES;
}
[self handleAnchor:YES];
}
else if ([webView isEqual:indexViewController.view])
{
discardNextStatusBarToggle = NO;
}
}
else if ([[url scheme] isEqualToString:@"book"])
{
// ****** Handle: book://
NSLog(@" Page is a link with scheme book:// --> download new book");
if ([[url host] isEqualToString:@"local"] && [[NSFileManager defaultManager] fileExistsAtPath:bundleBookPath]) {
// *** Back to bundled book
feedbackAlert = [[UIAlertView alloc] initWithTitle:@""
message:[NSString stringWithFormat:CLOSE_BOOK_MESSAGE]
delegate:self
cancelButtonTitle:ALERT_FEEDBACK_CANCEL
otherButtonTitles:CLOSE_BOOK_CONFIRM, nil];
[feedbackAlert show];
[feedbackAlert release];
} else {
if ([[url pathExtension] isEqualToString:@"html"]) {
anchorFromURL = [[url fragment] retain];
pageNameFromURL = [[[url lastPathComponent] stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding] retain];
NSString *tmpUrl = [[url URLByDeletingLastPathComponent] absoluteString];
url = [NSURL URLWithString:[tmpUrl stringByTrimmingCharactersInSet:[NSCharacterSet characterSetWithCharactersInString:@"/"]]];
}
// ****** Download book
URLDownload = [[@"http:" stringByAppendingString:[url resourceSpecifier]] retain];
if ([[[NSURL URLWithString:URLDownload] pathExtension] isEqualToString:@""]) {
URLDownload = [[URLDownload stringByAppendingString:@".hpub"] retain];
}
[self downloadBook:nil];
}
}
else
{
NSString *params = [url query];
if (params != nil)
{
NSRegularExpression *referrerRegex = [NSRegularExpression regularExpressionWithPattern:@"referrer=Baker" options:NSRegularExpressionCaseInsensitive error:NULL];
NSUInteger matches = [referrerRegex numberOfMatchesInString:params options:0 range:NSMakeRange(0, [params length])];
if (matches > 0) {
NSLog(@" Link contain param \"referrer=Baker\" --> open link in Safari");
[[UIApplication sharedApplication] openURL:[request URL]];
return NO;
}
}
NSLog(@" Link doesn't contain param \"referrer=Baker\" --> open link in Page");
return YES;
}
}
}
return NO;
}
}
- (void)webViewDidStartLoad:(UIWebView *)webView {
NSLog(@"• Page did start load");
}
- (void)webView:(UIWebView *)webView didFailLoadWithError:(NSError *)error {
// Sent if a web view failed to load content.
if ([webView isEqual:currPage]) {
NSLog(@"• CurrPage failed to load content with error: %@", error);
} else if ([webView isEqual:prevPage]) {
NSLog(@"• PrevPage failed to load content with error: %@", error);
} else if ([webView isEqual:nextPage]) {
NSLog(@"• NextPage failed to load content with error: %@", error);
}
}
- (void)webViewDidFinishLoad:(UIWebView *)webView {
NSLog(@"• Page did finish load");
if (webView.hidden == YES)