-
Notifications
You must be signed in to change notification settings - Fork 2.1k
Expand file tree
/
Copy pathPDFView.java
More file actions
1567 lines (1284 loc) · 50.7 KB
/
Copy pathPDFView.java
File metadata and controls
1567 lines (1284 loc) · 50.7 KB
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 2016 Bartosz Schiller
* <p/>
* 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
* <p/>
* http://www.apache.org/licenses/LICENSE-2.0
* <p/>
* 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.
*/
package com.github.barteksc.pdfviewer;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.ColorMatrix;
import android.graphics.ColorMatrixColorFilter;
import android.graphics.Paint;
import android.graphics.Paint.Style;
import android.graphics.PaintFlagsDrawFilter;
import android.graphics.PointF;
import android.graphics.Rect;
import android.graphics.RectF;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Build;
import android.os.HandlerThread;
import android.util.AttributeSet;
import android.util.Log;
import android.widget.RelativeLayout;
import com.github.barteksc.pdfviewer.exception.PageRenderingException;
import com.github.barteksc.pdfviewer.link.DefaultLinkHandler;
import com.github.barteksc.pdfviewer.link.LinkHandler;
import com.github.barteksc.pdfviewer.listener.Callbacks;
import com.github.barteksc.pdfviewer.listener.OnDrawListener;
import com.github.barteksc.pdfviewer.listener.OnErrorListener;
import com.github.barteksc.pdfviewer.listener.OnLoadCompleteListener;
import com.github.barteksc.pdfviewer.listener.OnLongPressListener;
import com.github.barteksc.pdfviewer.listener.OnPageChangeListener;
import com.github.barteksc.pdfviewer.listener.OnPageErrorListener;
import com.github.barteksc.pdfviewer.listener.OnPageScrollListener;
import com.github.barteksc.pdfviewer.listener.OnRenderListener;
import com.github.barteksc.pdfviewer.listener.OnTapListener;
import com.github.barteksc.pdfviewer.model.PagePart;
import com.github.barteksc.pdfviewer.scroll.ScrollHandle;
import com.github.barteksc.pdfviewer.source.AssetSource;
import com.github.barteksc.pdfviewer.source.ByteArraySource;
import com.github.barteksc.pdfviewer.source.DocumentSource;
import com.github.barteksc.pdfviewer.source.FileSource;
import com.github.barteksc.pdfviewer.source.InputStreamSource;
import com.github.barteksc.pdfviewer.source.UriSource;
import com.github.barteksc.pdfviewer.util.Constants;
import com.github.barteksc.pdfviewer.util.FitPolicy;
import com.github.barteksc.pdfviewer.util.MathUtils;
import com.github.barteksc.pdfviewer.util.SnapEdge;
import com.github.barteksc.pdfviewer.util.Util;
import com.shockwave.pdfium.PdfDocument;
import com.shockwave.pdfium.PdfiumCore;
import com.shockwave.pdfium.util.Size;
import com.shockwave.pdfium.util.SizeF;
import java.io.File;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
/**
* It supports animations, zoom, cache, and swipe.
* <p>
* To fully understand this class you must know its principles :
* - The PDF document is seen as if we always want to draw all the pages.
* - The thing is that we only draw the visible parts.
* - All parts are the same size, this is because we can't interrupt a native page rendering,
* so we need these renderings to be as fast as possible, and be able to interrupt them
* as soon as we can.
* - The parts are loaded when the current offset or the current zoom level changes
* <p>
* Important :
* - DocumentPage = A page of the PDF document.
* - UserPage = A page as defined by the user.
* By default, they're the same. But the user can change the pages order
* using {@link #load(DocumentSource, String, int[])}. In this
* particular case, a userPage of 5 can refer to a documentPage of 17.
*/
public class PDFView extends RelativeLayout {
private static final String TAG = PDFView.class.getSimpleName();
public static final float DEFAULT_MAX_SCALE = 3.0f;
public static final float DEFAULT_MID_SCALE = 1.75f;
public static final float DEFAULT_MIN_SCALE = 1.0f;
private float minZoom = DEFAULT_MIN_SCALE;
private float midZoom = DEFAULT_MID_SCALE;
private float maxZoom = DEFAULT_MAX_SCALE;
/**
* START - scrolling in first page direction
* END - scrolling in last page direction
* NONE - not scrolling
*/
enum ScrollDir {
NONE, START, END
}
private ScrollDir scrollDir = ScrollDir.NONE;
/** Rendered parts go to the cache manager */
CacheManager cacheManager;
/** Animation manager manage all offset and zoom animation */
private AnimationManager animationManager;
/** Drag manager manage all touch events */
private DragPinchManager dragPinchManager;
PdfFile pdfFile;
/** The index of the current sequence */
private int currentPage;
/**
* If you picture all the pages side by side in their optimal width,
* and taking into account the zoom level, the current offset is the
* position of the left border of the screen in this big picture
*/
private float currentXOffset = 0;
/**
* If you picture all the pages side by side in their optimal width,
* and taking into account the zoom level, the current offset is the
* position of the left border of the screen in this big picture
*/
private float currentYOffset = 0;
/** The zoom level, always >= 1 */
private float zoom = 1f;
/** True if the PDFView has been recycled */
private boolean recycled = true;
/** Current state of the view */
private State state = State.DEFAULT;
/** Async task used during the loading phase to decode a PDF document */
private DecodingAsyncTask decodingAsyncTask;
/** The thread {@link #renderingHandler} will run on */
private HandlerThread renderingHandlerThread;
/** Handler always waiting in the background and rendering tasks */
RenderingHandler renderingHandler;
private PagesLoader pagesLoader;
Callbacks callbacks = new Callbacks();
/** Paint object for drawing */
private Paint paint;
/** Paint object for drawing debug stuff */
private Paint debugPaint;
/** Policy for fitting pages to screen */
private FitPolicy pageFitPolicy = FitPolicy.WIDTH;
private boolean fitEachPage = false;
private int defaultPage = 0;
/** True if should scroll through pages vertically instead of horizontally */
private boolean swipeVertical = true;
private boolean enableSwipe = true;
private boolean doubletapEnabled = true;
private boolean nightMode = false;
private boolean pageSnap = true;
/** Pdfium core for loading and rendering PDFs */
private PdfiumCore pdfiumCore;
private ScrollHandle scrollHandle;
private boolean isScrollHandleInit = false;
ScrollHandle getScrollHandle() {
return scrollHandle;
}
/**
* True if bitmap should use ARGB_8888 format and take more memory
* False if bitmap should be compressed by using RGB_565 format and take less memory
*/
private boolean bestQuality = false;
/**
* True if annotations should be rendered
* False otherwise
*/
private boolean annotationRendering = false;
/**
* True if the view should render during scaling<br/>
* Can not be forced on older API versions (< Build.VERSION_CODES.KITKAT) as the GestureDetector does
* not detect scrolling while scaling.<br/>
* False otherwise
*/
private boolean renderDuringScale = false;
/** Antialiasing and bitmap filtering */
private boolean enableAntialiasing = true;
private PaintFlagsDrawFilter antialiasFilter =
new PaintFlagsDrawFilter(0, Paint.ANTI_ALIAS_FLAG | Paint.FILTER_BITMAP_FLAG);
/** Spacing between pages, in px */
private int spacingPx = 0;
/** Add dynamic spacing to fit each page separately on the screen. */
private boolean autoSpacing = false;
/** Fling a single page at a time */
private boolean pageFling = true;
/** Pages numbers used when calling onDrawAllListener */
private List<Integer> onDrawPagesNums = new ArrayList<>(10);
/** Holds info whether view has been added to layout and has width and height */
private boolean hasSize = false;
/** Holds last used Configurator that should be loaded when view has size */
private Configurator waitingDocumentConfigurator;
/** Construct the initial view */
public PDFView(Context context, AttributeSet set) {
super(context, set);
if (isInEditMode()) {
return;
}
cacheManager = new CacheManager();
animationManager = new AnimationManager(this);
dragPinchManager = new DragPinchManager(this, animationManager);
pagesLoader = new PagesLoader(this);
paint = new Paint();
debugPaint = new Paint();
debugPaint.setStyle(Style.STROKE);
pdfiumCore = new PdfiumCore(context);
setWillNotDraw(false);
}
private void load(DocumentSource docSource, String password) {
load(docSource, password, null);
}
private void load(DocumentSource docSource, String password, int[] userPages) {
if (!recycled) {
throw new IllegalStateException("Don't call load on a PDF View without recycling it first.");
}
recycled = false;
// Start decoding document
decodingAsyncTask = new DecodingAsyncTask(docSource, password, userPages, this, pdfiumCore);
decodingAsyncTask.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
}
/**
* Go to the given page.
*
* @param page Page index.
*/
public void jumpTo(int page, boolean withAnimation) {
if (pdfFile == null) {
return;
}
page = pdfFile.determineValidPageNumberFrom(page);
float offset = page == 0 ? 0 : -pdfFile.getPageOffset(page, zoom);
if (swipeVertical) {
if (withAnimation) {
animationManager.startYAnimation(currentYOffset, offset);
} else {
moveTo(currentXOffset, offset);
}
} else {
if (withAnimation) {
animationManager.startXAnimation(currentXOffset, offset);
} else {
moveTo(offset, currentYOffset);
}
}
showPage(page);
}
public void jumpTo(int page) {
jumpTo(page, false);
}
void showPage(int pageNb) {
if (recycled) {
return;
}
// Check the page number and makes the
// difference between UserPages and DocumentPages
pageNb = pdfFile.determineValidPageNumberFrom(pageNb);
currentPage = pageNb;
loadPages();
if (scrollHandle != null && !documentFitsView()) {
scrollHandle.setPageNum(currentPage + 1);
}
callbacks.callOnPageChange(currentPage, pdfFile.getPagesCount());
}
/**
* Get current position as ratio of document length to visible area.
* 0 means that document start is visible, 1 that document end is visible
*
* @return offset between 0 and 1
*/
public float getPositionOffset() {
float offset;
if (swipeVertical) {
offset = -currentYOffset / (pdfFile.getDocLen(zoom) - getHeight());
} else {
offset = -currentXOffset / (pdfFile.getDocLen(zoom) - getWidth());
}
return MathUtils.limit(offset, 0, 1);
}
/**
* @param progress must be between 0 and 1
* @param moveHandle whether to move scroll handle
* @see PDFView#getPositionOffset()
*/
public void setPositionOffset(float progress, boolean moveHandle) {
if (swipeVertical) {
moveTo(currentXOffset, (-pdfFile.getDocLen(zoom) + getHeight()) * progress, moveHandle);
} else {
moveTo((-pdfFile.getDocLen(zoom) + getWidth()) * progress, currentYOffset, moveHandle);
}
loadPageByOffset();
}
public void setPositionOffset(float progress) {
setPositionOffset(progress, true);
}
public void stopFling() {
animationManager.stopFling();
}
public int getPageCount() {
if (pdfFile == null) {
return 0;
}
return pdfFile.getPagesCount();
}
public void setSwipeEnabled(boolean enableSwipe) {
this.enableSwipe = enableSwipe;
}
public void setNightMode(boolean nightMode) {
this.nightMode = nightMode;
if (nightMode) {
ColorMatrix colorMatrixInverted =
new ColorMatrix(new float[]{
-1, 0, 0, 0, 255,
0, -1, 0, 0, 255,
0, 0, -1, 0, 255,
0, 0, 0, 1, 0});
ColorMatrixColorFilter filter = new ColorMatrixColorFilter(colorMatrixInverted);
paint.setColorFilter(filter);
} else {
paint.setColorFilter(null);
}
}
void enableDoubletap(boolean enableDoubletap) {
this.doubletapEnabled = enableDoubletap;
}
boolean isDoubletapEnabled() {
return doubletapEnabled;
}
void onPageError(PageRenderingException ex) {
if (!callbacks.callOnPageError(ex.getPage(), ex.getCause())) {
Log.e(TAG, "Cannot open page " + ex.getPage(), ex.getCause());
}
}
public void recycle() {
waitingDocumentConfigurator = null;
animationManager.stopAll();
dragPinchManager.disable();
// Stop tasks
if (renderingHandler != null) {
renderingHandler.stop();
renderingHandler.removeMessages(RenderingHandler.MSG_RENDER_TASK);
}
if (decodingAsyncTask != null) {
decodingAsyncTask.cancel(true);
}
// Clear caches
cacheManager.recycle();
if (scrollHandle != null && isScrollHandleInit) {
scrollHandle.destroyLayout();
}
if (pdfFile != null) {
pdfFile.dispose();
pdfFile = null;
}
renderingHandler = null;
scrollHandle = null;
isScrollHandleInit = false;
currentXOffset = currentYOffset = 0;
zoom = 1f;
recycled = true;
callbacks = new Callbacks();
state = State.DEFAULT;
}
public boolean isRecycled() {
return recycled;
}
/** Handle fling animation */
@Override
public void computeScroll() {
super.computeScroll();
if (isInEditMode()) {
return;
}
animationManager.computeFling();
}
@Override
protected void onAttachedToWindow() {
super.onAttachedToWindow();
renderingHandlerThread = new HandlerThread("PDF renderer");
}
@Override
protected void onDetachedFromWindow() {
recycle();
if (renderingHandlerThread != null) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR2) {
renderingHandlerThread.quitSafely();
} else {
renderingHandlerThread.quit();
}
renderingHandlerThread = null;
}
super.onDetachedFromWindow();
}
@Override
protected void onSizeChanged(int w, int h, int oldw, int oldh) {
hasSize = true;
if (waitingDocumentConfigurator != null) {
waitingDocumentConfigurator.load();
}
if (isInEditMode() || state != State.SHOWN) {
return;
}
// calculates the position of the point which in the center of view relative to big strip
float centerPointInStripXOffset = -currentXOffset + oldw * 0.5f;
float centerPointInStripYOffset = -currentYOffset + oldh * 0.5f;
float relativeCenterPointInStripXOffset;
float relativeCenterPointInStripYOffset;
if (swipeVertical){
relativeCenterPointInStripXOffset = centerPointInStripXOffset / pdfFile.getMaxPageWidth();
relativeCenterPointInStripYOffset = centerPointInStripYOffset / pdfFile.getDocLen(zoom);
}else {
relativeCenterPointInStripXOffset = centerPointInStripXOffset / pdfFile.getDocLen(zoom);
relativeCenterPointInStripYOffset = centerPointInStripYOffset / pdfFile.getMaxPageHeight();
}
animationManager.stopAll();
pdfFile.recalculatePageSizes(new Size(w, h));
if (swipeVertical) {
currentXOffset = -relativeCenterPointInStripXOffset * pdfFile.getMaxPageWidth() + w * 0.5f;
currentYOffset = -relativeCenterPointInStripYOffset * pdfFile.getDocLen(zoom) + h * 0.5f ;
}else {
currentXOffset = -relativeCenterPointInStripXOffset * pdfFile.getDocLen(zoom) + w * 0.5f;
currentYOffset = -relativeCenterPointInStripYOffset * pdfFile.getMaxPageHeight() + h * 0.5f;
}
moveTo(currentXOffset,currentYOffset);
loadPageByOffset();
}
@Override
public boolean canScrollHorizontally(int direction) {
if (pdfFile == null) {
return true;
}
if (swipeVertical) {
if (direction < 0 && currentXOffset < 0) {
return true;
} else if (direction > 0 && currentXOffset + toCurrentScale(pdfFile.getMaxPageWidth()) > getWidth()) {
return true;
}
} else {
if (direction < 0 && currentXOffset < 0) {
return true;
} else if (direction > 0 && currentXOffset + pdfFile.getDocLen(zoom) > getWidth()) {
return true;
}
}
return false;
}
@Override
public boolean canScrollVertically(int direction) {
if (pdfFile == null) {
return true;
}
if (swipeVertical) {
if (direction < 0 && currentYOffset < 0) {
return true;
} else if (direction > 0 && currentYOffset + pdfFile.getDocLen(zoom) > getHeight()) {
return true;
}
} else {
if (direction < 0 && currentYOffset < 0) {
return true;
} else if (direction > 0 && currentYOffset + toCurrentScale(pdfFile.getMaxPageHeight()) > getHeight()) {
return true;
}
}
return false;
}
@Override
protected void onDraw(Canvas canvas) {
if (isInEditMode()) {
return;
}
// As I said in this class javadoc, we can think of this canvas as a huge
// strip on which we draw all the images. We actually only draw the rendered
// parts, of course, but we render them in the place they belong in this huge
// strip.
// That's where Canvas.translate(x, y) becomes very helpful.
// This is the situation :
// _______________________________________________
// | | |
// | the actual | The big strip |
// | canvas | |
// |_____________| |
// |_______________________________________________|
//
// If the rendered part is on the bottom right corner of the strip
// we can draw it but we won't see it because the canvas is not big enough.
// But if we call translate(-X, -Y) on the canvas just before drawing the object :
// _______________________________________________
// | _____________|
// | The big strip | |
// | | the actual |
// | | canvas |
// |_________________________________|_____________|
//
// The object will be on the canvas.
// This technique is massively used in this method, and allows
// abstraction of the screen position when rendering the parts.
// Draws background
if (enableAntialiasing) {
canvas.setDrawFilter(antialiasFilter);
}
Drawable bg = getBackground();
if (bg == null) {
canvas.drawColor(nightMode ? Color.BLACK : Color.WHITE);
} else {
bg.draw(canvas);
}
if (recycled) {
return;
}
if (state != State.SHOWN) {
return;
}
// Moves the canvas before drawing any element
float currentXOffset = this.currentXOffset;
float currentYOffset = this.currentYOffset;
canvas.translate(currentXOffset, currentYOffset);
// Draws thumbnails
for (PagePart part : cacheManager.getThumbnails()) {
drawPart(canvas, part);
}
// Draws parts
for (PagePart part : cacheManager.getPageParts()) {
drawPart(canvas, part);
if (callbacks.getOnDrawAll() != null
&& !onDrawPagesNums.contains(part.getPage())) {
onDrawPagesNums.add(part.getPage());
}
}
for (Integer page : onDrawPagesNums) {
drawWithListener(canvas, page, callbacks.getOnDrawAll());
}
onDrawPagesNums.clear();
drawWithListener(canvas, currentPage, callbacks.getOnDraw());
// Restores the canvas position
canvas.translate(-currentXOffset, -currentYOffset);
}
private void drawWithListener(Canvas canvas, int page, OnDrawListener listener) {
if (listener != null) {
float translateX, translateY;
if (swipeVertical) {
translateX = 0;
translateY = pdfFile.getPageOffset(page, zoom);
} else {
translateY = 0;
translateX = pdfFile.getPageOffset(page, zoom);
}
canvas.translate(translateX, translateY);
SizeF size = pdfFile.getPageSize(page);
listener.onLayerDrawn(canvas,
toCurrentScale(size.getWidth()),
toCurrentScale(size.getHeight()),
page);
canvas.translate(-translateX, -translateY);
}
}
/** Draw a given PagePart on the canvas */
private void drawPart(Canvas canvas, PagePart part) {
// Can seem strange, but avoid lot of calls
RectF pageRelativeBounds = part.getPageRelativeBounds();
Bitmap renderedBitmap = part.getRenderedBitmap();
if (renderedBitmap.isRecycled()) {
return;
}
// Move to the target page
float localTranslationX = 0;
float localTranslationY = 0;
SizeF size = pdfFile.getPageSize(part.getPage());
if (swipeVertical) {
localTranslationY = pdfFile.getPageOffset(part.getPage(), zoom);
float maxWidth = pdfFile.getMaxPageWidth();
localTranslationX = toCurrentScale(maxWidth - size.getWidth()) / 2;
} else {
localTranslationX = pdfFile.getPageOffset(part.getPage(), zoom);
float maxHeight = pdfFile.getMaxPageHeight();
localTranslationY = toCurrentScale(maxHeight - size.getHeight()) / 2;
}
canvas.translate(localTranslationX, localTranslationY);
Rect srcRect = new Rect(0, 0, renderedBitmap.getWidth(),
renderedBitmap.getHeight());
float offsetX = toCurrentScale(pageRelativeBounds.left * size.getWidth());
float offsetY = toCurrentScale(pageRelativeBounds.top * size.getHeight());
float width = toCurrentScale(pageRelativeBounds.width() * size.getWidth());
float height = toCurrentScale(pageRelativeBounds.height() * size.getHeight());
// If we use float values for this rectangle, there will be
// a possible gap between page parts, especially when
// the zoom level is high.
RectF dstRect = new RectF((int) offsetX, (int) offsetY,
(int) (offsetX + width),
(int) (offsetY + height));
// Check if bitmap is in the screen
float translationX = currentXOffset + localTranslationX;
float translationY = currentYOffset + localTranslationY;
if (translationX + dstRect.left >= getWidth() || translationX + dstRect.right <= 0 ||
translationY + dstRect.top >= getHeight() || translationY + dstRect.bottom <= 0) {
canvas.translate(-localTranslationX, -localTranslationY);
return;
}
canvas.drawBitmap(renderedBitmap, srcRect, dstRect, paint);
if (Constants.DEBUG_MODE) {
debugPaint.setColor(part.getPage() % 2 == 0 ? Color.RED : Color.BLUE);
canvas.drawRect(dstRect, debugPaint);
}
// Restore the canvas position
canvas.translate(-localTranslationX, -localTranslationY);
}
/**
* Load all the parts around the center of the screen,
* taking into account X and Y offsets, zoom level, and
* the current page displayed
*/
public void loadPages() {
if (pdfFile == null || renderingHandler == null) {
return;
}
// Cancel all current tasks
renderingHandler.removeMessages(RenderingHandler.MSG_RENDER_TASK);
cacheManager.makeANewSet();
pagesLoader.loadPages();
redraw();
}
/** Called when the PDF is loaded */
void loadComplete(PdfFile pdfFile) {
state = State.LOADED;
this.pdfFile = pdfFile;
if (!renderingHandlerThread.isAlive()) {
renderingHandlerThread.start();
}
renderingHandler = new RenderingHandler(renderingHandlerThread.getLooper(), this);
renderingHandler.start();
if (scrollHandle != null) {
scrollHandle.setupLayout(this);
isScrollHandleInit = true;
}
dragPinchManager.enable();
callbacks.callOnLoadComplete(pdfFile.getPagesCount());
jumpTo(defaultPage, false);
}
void loadError(Throwable t) {
state = State.ERROR;
// store reference, because callbacks will be cleared in recycle() method
OnErrorListener onErrorListener = callbacks.getOnError();
recycle();
invalidate();
if (onErrorListener != null) {
onErrorListener.onError(t);
} else {
Log.e("PDFView", "load pdf error", t);
}
}
void redraw() {
invalidate();
}
/**
* Called when a rendering task is over and
* a PagePart has been freshly created.
*
* @param part The created PagePart.
*/
public void onBitmapRendered(PagePart part) {
// when it is first rendered part
if (state == State.LOADED) {
state = State.SHOWN;
callbacks.callOnRender(pdfFile.getPagesCount());
}
if (part.isThumbnail()) {
cacheManager.cacheThumbnail(part);
} else {
cacheManager.cachePart(part);
}
redraw();
}
public void moveTo(float offsetX, float offsetY) {
moveTo(offsetX, offsetY, true);
}
/**
* Move to the given X and Y offsets, but check them ahead of time
* to be sure not to go outside the the big strip.
*
* @param offsetX The big strip X offset to use as the left border of the screen.
* @param offsetY The big strip Y offset to use as the right border of the screen.
* @param moveHandle whether to move scroll handle or not
*/
public void moveTo(float offsetX, float offsetY, boolean moveHandle) {
if (swipeVertical) {
// Check X offset
float scaledPageWidth = toCurrentScale(pdfFile.getMaxPageWidth());
if (scaledPageWidth < getWidth()) {
offsetX = getWidth() / 2 - scaledPageWidth / 2;
} else {
if (offsetX > 0) {
offsetX = 0;
} else if (offsetX + scaledPageWidth < getWidth()) {
offsetX = getWidth() - scaledPageWidth;
}
}
// Check Y offset
float contentHeight = pdfFile.getDocLen(zoom);
if (contentHeight < getHeight()) { // whole document height visible on screen
offsetY = (getHeight() - contentHeight) / 2;
} else {
if (offsetY > 0) { // top visible
offsetY = 0;
} else if (offsetY + contentHeight < getHeight()) { // bottom visible
offsetY = -contentHeight + getHeight();
}
}
if (offsetY < currentYOffset) {
scrollDir = ScrollDir.END;
} else if (offsetY > currentYOffset) {
scrollDir = ScrollDir.START;
} else {
scrollDir = ScrollDir.NONE;
}
} else {
// Check Y offset
float scaledPageHeight = toCurrentScale(pdfFile.getMaxPageHeight());
if (scaledPageHeight < getHeight()) {
offsetY = getHeight() / 2 - scaledPageHeight / 2;
} else {
if (offsetY > 0) {
offsetY = 0;
} else if (offsetY + scaledPageHeight < getHeight()) {
offsetY = getHeight() - scaledPageHeight;
}
}
// Check X offset
float contentWidth = pdfFile.getDocLen(zoom);
if (contentWidth < getWidth()) { // whole document width visible on screen
offsetX = (getWidth() - contentWidth) / 2;
} else {
if (offsetX > 0) { // left visible
offsetX = 0;
} else if (offsetX + contentWidth < getWidth()) { // right visible
offsetX = -contentWidth + getWidth();
}
}
if (offsetX < currentXOffset) {
scrollDir = ScrollDir.END;
} else if (offsetX > currentXOffset) {
scrollDir = ScrollDir.START;
} else {
scrollDir = ScrollDir.NONE;
}
}
currentXOffset = offsetX;
currentYOffset = offsetY;
float positionOffset = getPositionOffset();
if (moveHandle && scrollHandle != null && !documentFitsView()) {
scrollHandle.setScroll(positionOffset);
}
callbacks.callOnPageScroll(getCurrentPage(), positionOffset);
redraw();
}
void loadPageByOffset() {
if (0 == pdfFile.getPagesCount()) {
return;
}
float offset, screenCenter;
if (swipeVertical) {
offset = currentYOffset;
screenCenter = ((float) getHeight()) / 2;
} else {
offset = currentXOffset;
screenCenter = ((float) getWidth()) / 2;
}
int page = pdfFile.getPageAtOffset(-(offset - screenCenter), zoom);
if (page >= 0 && page <= pdfFile.getPagesCount() - 1 && page != getCurrentPage()) {
showPage(page);
} else {
loadPages();
}
}
/**
* Animate to the nearest snapping position for the current SnapPolicy
*/
public void performPageSnap() {
if (!pageSnap || pdfFile == null || pdfFile.getPagesCount() == 0) {
return;
}
int centerPage = findFocusPage(currentXOffset, currentYOffset);
SnapEdge edge = findSnapEdge(centerPage);
if (edge == SnapEdge.NONE) {
return;
}
float offset = snapOffsetForPage(centerPage, edge);
if (swipeVertical) {
animationManager.startYAnimation(currentYOffset, -offset);
} else {
animationManager.startXAnimation(currentXOffset, -offset);
}
}
/**
* Find the edge to snap to when showing the specified page
*/
SnapEdge findSnapEdge(int page) {
if (!pageSnap || page < 0) {
return SnapEdge.NONE;
}
float currentOffset = swipeVertical ? currentYOffset : currentXOffset;
float offset = -pdfFile.getPageOffset(page, zoom);
int length = swipeVertical ? getHeight() : getWidth();
float pageLength = pdfFile.getPageLength(page, zoom);
if (length >= pageLength) {
return SnapEdge.CENTER;
} else if (currentOffset >= offset) {
return SnapEdge.START;
} else if (offset - pageLength > currentOffset - length) {
return SnapEdge.END;
} else {
return SnapEdge.NONE;
}
}
/**
* Get the offset to move to in order to snap to the page
*/
float snapOffsetForPage(int pageIndex, SnapEdge edge) {
float offset = pdfFile.getPageOffset(pageIndex, zoom);
float length = swipeVertical ? getHeight() : getWidth();
float pageLength = pdfFile.getPageLength(pageIndex, zoom);
if (edge == SnapEdge.CENTER) {
offset = offset - length / 2f + pageLength / 2f;
} else if (edge == SnapEdge.END) {
offset = offset - length + pageLength;
}
return offset;
}
int findFocusPage(float xOffset, float yOffset) {
float currOffset = swipeVertical ? yOffset : xOffset;
float length = swipeVertical ? getHeight() : getWidth();
// make sure first and last page can be found
if (currOffset > -1) {
return 0;
} else if (currOffset < -pdfFile.getDocLen(zoom) + length + 1) {
return pdfFile.getPagesCount() - 1;
}