forked from sumatrapdfreader/sumatrapdf
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathDisplayModel.cpp
More file actions
1610 lines (1412 loc) · 57.2 KB
/
Copy pathDisplayModel.cpp
File metadata and controls
1610 lines (1412 loc) · 57.2 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 2015 the SumatraPDF project authors (see AUTHORS file).
License: GPLv3 */
/* How to think of display logic: physical screen of size
viewPort.Size() is a window into (possibly much larger)
total area (canvas) of size canvasSize.
In DM_SINGLE_PAGE mode total area is the size of currently displayed page
given current zoom level and rotation.
In DM_CONTINUOUS mode canvas area consist of all pages rendered sequentially
with a given zoom level and rotation. canvasSize.dy is the sum of heights
of all pages plus spaces between them and canvasSize.dx is the size of
the widest page.
A possible configuration could look like this:
-----------------------------------
| |
| ------------- |
| | window | |
| | i.e. | |
| | view port | |
| ------------- |
| |
| |
| canvas |
| |
| |
| |
| |
-----------------------------------
We calculate the canvas size and position of each page we display on the
canvas.
Changing zoom level or rotation requires recalculation of canvas size and
position of pages in it.
We keep the offset of view port relative to canvas. The offset changes
due to scrolling (with keys or using scrollbars).
To draw we calculate which part of each page overlaps draw area, we render
those pages to a bitmap and display those bitmaps.
*/
// utils
#include "BaseUtil.h"
#include "WinUtil.h"
// rendering engines
#include "BaseEngine.h"
#include "EngineManager.h"
// layout controllers
#include "SettingsStructs.h"
#include "Controller.h"
#include "DisplayModel.h"
#include "GlobalPrefs.h"
#include "PdfSync.h"
#include "TextSelection.h"
#include "TextSearch.h"
// if true, we pre-render the pages right before and after the visible pages
static bool gPredictiveRender = true;
static int ColumnsFromDisplayMode(DisplayMode displayMode)
{
if (!IsSingle(displayMode))
return 2;
return 1;
}
int NormalizeRotation(int rotation)
{
assert((rotation % 90) == 0);
rotation = rotation % 360;
if (rotation < 0)
rotation += 360;
if (rotation < 0 || rotation >= 360 || (rotation % 90) != 0) {
assert(0);
return 0;
}
return rotation;
}
void DisplayModel::UpdateDisplayState(DisplayState *ds)
{
if (!ds->filePath || !str::EqI(ds->filePath, engine->FileName()))
str::ReplacePtr(&ds->filePath, engine->FileName());
ds->useDefaultState = !gGlobalPrefs->rememberStatePerDocument;
str::ReplacePtr(&ds->displayMode, prefs::conv::FromDisplayMode(presentationMode ? presDisplayMode : GetDisplayMode()));
prefs::conv::FromZoom(&ds->zoom, presentationMode ? presZoomVirtual : zoomVirtual, ds);
ScrollState ss = GetScrollState();
ds->pageNo = ss.page;
if (presentationMode)
ds->scrollPos = PointI();
else
ds->scrollPos = PointD(ss.x, ss.y).ToInt();
ds->rotation = rotation;
ds->displayR2L = displayR2L;
free(ds->decryptionKey);
ds->decryptionKey = engine->GetDecryptionKey();
}
SizeD DisplayModel::PageSizeAfterRotation(int pageNo, bool fitToContent) const
{
PageInfo *pageInfo = GetPageInfo(pageNo);
if (fitToContent && pageInfo->contentBox.IsEmpty()) {
pageInfo->contentBox = engine->PageContentBox(pageNo);
if (pageInfo->contentBox.IsEmpty())
return PageSizeAfterRotation(pageNo);
}
RectD box = fitToContent ? pageInfo->contentBox : pageInfo->page;
return engine->Transform(box, pageNo, 1.0, rotation).Size();
}
/* given 'columns' and an absolute 'pageNo', return the number of the first
page in a row to which a 'pageNo' belongs e.g. if 'columns' is 2 and we
have 5 pages in 3 rows (depending on showCover):
Pages Result Pages Result Pages Result (R2L)
(1,2) 1 (1) 1 (2,1) 1
(3,4) 3 (2,3) 2 (4,3) 3
(5) 5 (4,5) 4 (5) 5
*/
static int FirstPageInARowNo(int pageNo, int columns, bool showCover)
{
if (showCover && columns > 1)
pageNo++;
int firstPageNo = pageNo - ((pageNo - 1) % columns);
if (showCover && columns > 1 && firstPageNo > 1)
firstPageNo--;
return firstPageNo;
}
static int LastPageInARowNo(int pageNo, int columns, bool showCover, int pageCount)
{
int lastPageNo = FirstPageInARowNo(pageNo, columns, showCover) + columns - 1;
if (showCover && pageNo < columns)
lastPageNo--;
return std::min(lastPageNo, pageCount);
}
// must call SetInitialViewSettings() after creation
DisplayModel::DisplayModel(BaseEngine *engine, EngineType type, ControllerCallback *cb) :
Controller(cb), engine(engine),
userAnnots(nullptr), userAnnotsModified(false), engineType(type), pdfSync(nullptr),
pagesInfo(nullptr), displayMode(DM_AUTOMATIC), startPage(1),
zoomReal(INVALID_ZOOM), zoomVirtual(INVALID_ZOOM),
rotation(0), dpiFactor(1.0f), displayR2L(false),
presentationMode(false), presZoomVirtual(INVALID_ZOOM),
presDisplayMode(DM_AUTOMATIC), navHistoryIx(0),
dontRenderFlag(false)
{
CrashIf(!engine || engine->PageCount() <= 0);
if (!engine->IsImageCollection()) {
windowMargin = gGlobalPrefs->fixedPageUI.windowMargin;
pageSpacing = gGlobalPrefs->fixedPageUI.pageSpacing;
}
else {
windowMargin = gGlobalPrefs->comicBookUI.windowMargin;
pageSpacing = gGlobalPrefs->comicBookUI.pageSpacing;
}
#ifdef DRAW_PAGE_SHADOWS
windowMargin.top += 3; windowMargin.bottom += 5;
windowMargin.right += 3; windowMargin.left += 1;
pageSpacing.dx += 4; pageSpacing.dy += 4;
#endif
textCache = new PageTextCache(engine);
textSelection = new TextSelection(engine, textCache);
textSearch = new TextSearch(engine, textCache);
}
DisplayModel::~DisplayModel()
{
dontRenderFlag = true;
cb->CleanUp(this);
delete pdfSync;
delete userAnnots;
delete textSearch;
delete textSelection;
delete textCache;
delete engine;
free(pagesInfo);
}
PageInfo *DisplayModel::GetPageInfo(int pageNo) const
{
if (!ValidPageNo(pageNo))
return nullptr;
assert(pagesInfo);
if (!pagesInfo) return nullptr;
return &(pagesInfo[pageNo-1]);
}
// Call this before the first Relayout
void DisplayModel::SetInitialViewSettings(DisplayMode newDisplayMode, int newStartPage, SizeI viewPort, int screenDPI)
{
totalViewPortSize = viewPort;
dpiFactor = 1.0f * screenDPI / engine->GetFileDPI();
if (ValidPageNo(newStartPage))
startPage = newStartPage;
displayMode = newDisplayMode;
presDisplayMode = newDisplayMode;
PageLayoutType layout = engine->PreferredLayout();
if (DM_AUTOMATIC == displayMode) {
switch (layout & ~Layout_R2L) {
case Layout_Single: displayMode = DM_CONTINUOUS; break;
case Layout_Facing: displayMode = DM_CONTINUOUS_FACING; break;
case Layout_Book: displayMode = DM_CONTINUOUS_BOOK_VIEW; break;
case Layout_Single | Layout_NonContinuous: displayMode = DM_SINGLE_PAGE; break;
case Layout_Facing | Layout_NonContinuous: displayMode = DM_FACING; break;
case Layout_Book | Layout_NonContinuous: displayMode = DM_BOOK_VIEW; break;
}
}
displayR2L = (layout & Layout_R2L) != 0;
BuildPagesInfo();
}
void DisplayModel::BuildPagesInfo()
{
AssertCrash(!pagesInfo);
int pageCount = PageCount();
pagesInfo = AllocArray<PageInfo>(pageCount);
RectD defaultRect;
if (0 == GetMeasurementSystem())
defaultRect = RectD(0, 0, 21.0 / 2.54 * engine->GetFileDPI(), 29.7 / 2.54 * engine->GetFileDPI());
else
defaultRect = RectD(0, 0, 8.5 * engine->GetFileDPI(), 11 * engine->GetFileDPI());
int columns = ColumnsFromDisplayMode(displayMode);
int newStartPage = startPage;
if (IsBookView(displayMode) && newStartPage == 1 && columns > 1)
newStartPage--;
for (int pageNo = 1; pageNo <= pageCount; pageNo++) {
PageInfo *pageInfo = GetPageInfo(pageNo);
pageInfo->page = engine->PageMediabox(pageNo);
// layout pages with an empty mediabox as A4 size (resp. letter size)
if (pageInfo->page.IsEmpty())
pageInfo->page = defaultRect;
pageInfo->visibleRatio = 0.0;
pageInfo->shown = false;
if (IsContinuous(displayMode))
pageInfo->shown = true;
else if (newStartPage <= pageNo && pageNo < newStartPage + columns)
pageInfo->shown = true;
}
}
// TODO: a better name e.g. ShouldShow() to better distinguish between
// before-layout info and after-layout visibility checks
bool DisplayModel::PageShown(int pageNo) const
{
PageInfo *pageInfo = GetPageInfo(pageNo);
if (!pageInfo)
return false;
return pageInfo->shown;
}
bool DisplayModel::PageVisible(int pageNo) const
{
PageInfo *pageInfo = GetPageInfo(pageNo);
if (!pageInfo)
return false;
return pageInfo->visibleRatio > 0.0;
}
/* Return true if a page is visible or a page in a row below or above is visible */
bool DisplayModel::PageVisibleNearby(int pageNo) const
{
DisplayMode mode = GetDisplayMode();
int columns = ColumnsFromDisplayMode(mode);
pageNo = FirstPageInARowNo(pageNo, columns, IsBookView(mode));
for (int i = pageNo - columns; i < pageNo + 2 * columns; i++) {
if (ValidPageNo(i) && PageVisible(i))
return true;
}
return false;
}
/* Return true if the first page is fully visible and alone on a line in
show cover mode (i.e. it's not possible to flip to a previous page) */
bool DisplayModel::FirstBookPageVisible() const
{
if (!IsBookView(GetDisplayMode()))
return false;
if (CurrentPageNo() != 1)
return false;
return true;
}
/* Return true if the last page is fully visible and alone on a line in
facing or show cover mode (i.e. it's not possible to flip to a next page) */
bool DisplayModel::LastBookPageVisible() const
{
int count = PageCount();
DisplayMode mode = GetDisplayMode();
if (IsSingle(mode))
return false;
if (CurrentPageNo() == count)
return true;
if (GetPageInfo(count)->visibleRatio < 1.0)
return false;
if (FirstPageInARowNo(count, ColumnsFromDisplayMode(mode),
IsBookView(mode)) < count)
return false;
return true;
}
/* Given a zoom level that can include a "virtual" zoom levels like ZOOM_FIT_WIDTH,
ZOOM_FIT_PAGE or ZOOM_FIT_CONTENT, calculate an absolute zoom level */
float DisplayModel::ZoomRealFromVirtualForPage(float zoomVirtual, int pageNo) const
{
if (zoomVirtual != ZOOM_FIT_WIDTH && zoomVirtual != ZOOM_FIT_PAGE && zoomVirtual != ZOOM_FIT_CONTENT)
return zoomVirtual * 0.01f * dpiFactor;
SizeD row;
int columns = ColumnsFromDisplayMode(GetDisplayMode());
bool fitToContent = (ZOOM_FIT_CONTENT == zoomVirtual);
if (fitToContent && columns > 1) {
// Fit the content of all the pages in the same row into the visible area
// (i.e. don't crop inner margins but just the left-most, right-most, etc.)
int first = FirstPageInARowNo(pageNo, columns, IsBookView(GetDisplayMode()));
int last = LastPageInARowNo(pageNo, columns, IsBookView(GetDisplayMode()), PageCount());
RectD box;
for (int i = first; i <= last; i++) {
PageInfo *pageInfo = GetPageInfo(i);
if (pageInfo->contentBox.IsEmpty())
pageInfo->contentBox = engine->PageContentBox(i);
RectD pageBox = engine->Transform(pageInfo->page, i, 1.0, rotation);
RectD contentBox = engine->Transform(pageInfo->contentBox, i, 1.0, rotation);
if (contentBox.IsEmpty())
contentBox = pageBox;
contentBox.x += row.dx;
box = box.Union(contentBox);
row.dx += pageBox.dx + pageSpacing.dx;
}
row = box.Size();
} else {
row = PageSizeAfterRotation(pageNo, fitToContent);
row.dx *= columns;
row.dx += pageSpacing.dx * (columns - 1);
}
assert(!RectD(PointD(), row).IsEmpty());
if (RectD(PointD(), row).IsEmpty())
return 0;
int areaForPagesDx = viewPort.dx - windowMargin.left - windowMargin.right;
int areaForPagesDy = viewPort.dy - windowMargin.top - windowMargin.bottom;
if (areaForPagesDx <= 0 || areaForPagesDy <= 0)
return 0;
float zoomX = areaForPagesDx / (float)row.dx;
float zoomY = areaForPagesDy / (float)row.dy;
if (zoomX < zoomY || ZOOM_FIT_WIDTH == zoomVirtual)
return zoomX;
return zoomY;
}
int DisplayModel::FirstVisiblePageNo() const
{
assert(pagesInfo);
if (!pagesInfo) return INVALID_PAGE_NO;
for (int pageNo = 1; pageNo <= PageCount(); ++pageNo) {
PageInfo *pageInfo = GetPageInfo(pageNo);
if (pageInfo->visibleRatio > 0.0)
return pageNo;
}
/* If no pages are visible */
return INVALID_PAGE_NO;
}
// we consider the most visible page the current one
// (in continuous layout, there's no better criteria)
int DisplayModel::CurrentPageNo() const
{
if (!IsContinuous(GetDisplayMode()))
return startPage;
assert(pagesInfo);
if (!pagesInfo) return INVALID_PAGE_NO;
// determine the most visible page
int mostVisiblePage = INVALID_PAGE_NO;
float ratio = 0;
for (int pageNo = 1; pageNo <= PageCount(); pageNo++) {
PageInfo *pageInfo = GetPageInfo(pageNo);
if (pageInfo->visibleRatio > ratio) {
mostVisiblePage = pageNo;
ratio = pageInfo->visibleRatio;
}
}
/* if no page is visible, default to either the first or the last one */
if (INVALID_PAGE_NO == mostVisiblePage) {
PageInfo *pageInfo = GetPageInfo(1);
if (pageInfo && viewPort.y > pageInfo->pos.y + pageInfo->pos.dy)
mostVisiblePage = PageCount();
else
mostVisiblePage = 1;
}
return mostVisiblePage;
}
void DisplayModel::CalcZoomVirtual(float newZoomVirtual)
{
CrashIf(!IsValidZoom(newZoomVirtual));
zoomVirtual = newZoomVirtual;
if ((ZOOM_FIT_WIDTH == newZoomVirtual) || (ZOOM_FIT_PAGE == newZoomVirtual)) {
/* we want the same zoom for all pages, so use the smallest zoom
across the pages so that the largest page fits. In most documents
all pages are the same size anyway */
float minZoom = (float)HUGE_VAL;
for (int pageNo = 1; pageNo <= PageCount(); pageNo++) {
if (PageShown(pageNo)) {
float thisPageZoom = ZoomRealFromVirtualForPage(newZoomVirtual, pageNo);
if (minZoom > thisPageZoom)
minZoom = thisPageZoom;
}
}
assert(minZoom != (float)HUGE_VAL);
zoomReal = minZoom;
} else if (ZOOM_FIT_CONTENT == newZoomVirtual) {
float newZoom = ZoomRealFromVirtualForPage(newZoomVirtual, CurrentPageNo());
// limit zooming in to 800% on almost empty pages
if (newZoom > 8.0)
newZoom = 8.0;
// don't zoom in by just a few pixels (throwing away a prerendered page)
if (newZoom < zoomReal || zoomReal / newZoom < 0.95 ||
zoomReal < ZoomRealFromVirtualForPage(ZOOM_FIT_PAGE, CurrentPageNo()))
zoomReal = newZoom;
} else {
zoomReal = zoomVirtual * 0.01f * dpiFactor;
}
}
float DisplayModel::GetZoomReal(int pageNo) const
{
DisplayMode mode = GetDisplayMode();
if (IsContinuous(mode))
return zoomReal;
if (IsSingle(mode))
return ZoomRealFromVirtualForPage(zoomVirtual, pageNo);
pageNo = FirstPageInARowNo(pageNo, ColumnsFromDisplayMode(mode), IsBookView(mode));
if (pageNo == PageCount() || pageNo == 1 && IsBookView(mode))
return ZoomRealFromVirtualForPage(zoomVirtual, pageNo);
return std::min(ZoomRealFromVirtualForPage(zoomVirtual, pageNo), ZoomRealFromVirtualForPage(zoomVirtual, pageNo + 1));
}
/* Given zoom and rotation, calculate the position of each page on a
large sheet that is continous view. Needs to be recalculated when:
* zoom changes
* rotation changes
* switching between display modes
* navigating to another page in non-continuous mode */
void DisplayModel::Relayout(float newZoomVirtual, int newRotation)
{
assert(pagesInfo);
if (!pagesInfo)
return;
rotation = NormalizeRotation(newRotation);
bool needHScroll = false;
bool needVScroll = false;
viewPort = RectI(viewPort.TL(), totalViewPortSize);
RestartLayout:
int currPosY = windowMargin.top;
float currZoomReal = zoomReal;
CalcZoomVirtual(newZoomVirtual);
int newViewPortOffsetX = 0;
if (0 != currZoomReal && INVALID_ZOOM != currZoomReal)
newViewPortOffsetX = (int)(viewPort.x * zoomReal / currZoomReal);
viewPort.x = newViewPortOffsetX;
/* calculate the position of each page on the canvas, given current zoom,
rotation, columns parameters. You can think of it as a simple
table layout i.e. rows with a fixed number of columns. */
int columns = ColumnsFromDisplayMode(GetDisplayMode());
int columnMaxWidth[2] = { 0, 0 };
int pageInARow = 0;
int rowMaxPageDy = 0;
for (int pageNo = 1; pageNo <= PageCount(); ++pageNo) {
PageInfo *pageInfo = GetPageInfo(pageNo);
if (!pageInfo->shown) {
assert(0.0 == pageInfo->visibleRatio);
continue;
}
SizeD pageSize = PageSizeAfterRotation(pageNo);
RectI pos;
// don't add the full 0.5 for rounding to account for precision errors
pos.dx = (int)(pageSize.dx * zoomReal + 0.499);
pos.dy = (int)(pageSize.dy * zoomReal + 0.499);
if (rowMaxPageDy < pos.dy)
rowMaxPageDy = pos.dy;
pos.y = currPosY;
// restart the layout if we detect we need to show scrollbars
if (!needVScroll && viewPort.dy < currPosY + rowMaxPageDy) {
needVScroll = true;
viewPort.dx -= GetSystemMetrics(SM_CXVSCROLL);
goto RestartLayout;
}
if (IsBookView(GetDisplayMode()) && pageNo == 1 && columns - pageInARow > 1)
pageInARow++;
CrashIf(pageInARow >= dimof(columnMaxWidth));
if (columnMaxWidth[pageInARow] < pos.dx)
columnMaxWidth[pageInARow] = pos.dx;
if (!needHScroll && viewPort.dx < windowMargin.left + columnMaxWidth[0] + (columns == 2 ? pageSpacing.dx + columnMaxWidth[1] : 0) + windowMargin.right) {
needHScroll = true;
viewPort.dy -= GetSystemMetrics(SM_CYHSCROLL);
goto RestartLayout;
}
pageInfo->pos = pos;
pageInARow++;
assert(pageInARow <= columns);
if (pageInARow == columns) {
/* starting next row */
currPosY += rowMaxPageDy + pageSpacing.dy;
rowMaxPageDy = 0;
pageInARow = 0;
}
}
if (pageInARow != 0) {
/* this is a partial row */
currPosY += rowMaxPageDy + pageSpacing.dy;
}
// restart the layout if we detect we need to show scrollbars
// (there are some edge cases we can't catch in the above loop)
const int canvasDy = currPosY + windowMargin.bottom - pageSpacing.dy;
if (!needVScroll && canvasDy > viewPort.dy) {
needVScroll = true;
viewPort.dx -= GetSystemMetrics(SM_CXVSCROLL);
goto RestartLayout;
}
if (columns == 2 && PageCount() == 1) {
/* don't center a single page over two columns */
if (IsBookView(GetDisplayMode()))
columnMaxWidth[0] = columnMaxWidth[1];
else
columnMaxWidth[1] = columnMaxWidth[0];
}
// restart the layout if we detect we need to show scrollbars
// (there are some edge cases we can't catch in the above loop)
int canvasDx = windowMargin.left + columnMaxWidth[0] + (columns == 2 ? pageSpacing.dx + columnMaxWidth[1] : 0) + windowMargin.right;
if (!needHScroll && canvasDx > viewPort.dx) {
needHScroll = true;
viewPort.dy -= GetSystemMetrics(SM_CYHSCROLL);
goto RestartLayout;
}
/* since pages can be smaller than the drawing area, center them in x axis */
int offX = 0;
if (canvasDx < viewPort.dx) {
viewPort.x = 0;
offX = (viewPort.dx - canvasDx) / 2;
canvasDx = viewPort.dx;
}
assert(offX >= 0);
pageInARow = 0;
int pageOffX = offX + windowMargin.left;
for (int pageNo = 1; pageNo <= PageCount(); ++pageNo) {
PageInfo *pageInfo = GetPageInfo(pageNo);
if (!pageInfo->shown) {
assert(0.0 == pageInfo->visibleRatio);
continue;
}
// leave first spot empty in cover page mode
if (IsBookView(GetDisplayMode()) && pageNo == 1) {
CrashIf(pageInARow >= dimof(columnMaxWidth));
pageOffX += columnMaxWidth[pageInARow] + pageSpacing.dx;
++pageInARow;
}
CrashIf(pageInARow >= dimof(columnMaxWidth));
// center pages in a single column but right/left align them when using two columns
if (1 == columns)
pageInfo->pos.x = pageOffX + (columnMaxWidth[0] - pageInfo->pos.dx) / 2;
else if (0 == pageInARow)
pageInfo->pos.x = pageOffX + columnMaxWidth[0] - pageInfo->pos.dx;
else
pageInfo->pos.x = pageOffX;
// center the cover page over the first two spots in non-continuous mode
if (IsBookView(GetDisplayMode()) && pageNo == 1 && !IsContinuous(GetDisplayMode())) {
pageInfo->pos.x = offX + windowMargin.left + (columnMaxWidth[0] + pageSpacing.dx + columnMaxWidth[1] - pageInfo->pos.dx) / 2;
}
// mirror the page layout when displaying a Right-to-Left document
if (displayR2L && columns > 1)
pageInfo->pos.x = canvasDx - pageInfo->pos.x - pageInfo->pos.dx;
CrashIf(pageInARow >= dimof(columnMaxWidth));
pageOffX += columnMaxWidth[pageInARow] + pageSpacing.dx;
++pageInARow;
assert(pageOffX >= 0 && pageInfo->pos.x >= 0);
if (pageInARow == columns) {
pageOffX = offX + windowMargin.left;
pageInARow = 0;
}
}
/* if after resizing we would have blank space on the right due to x offset
being too much, make x offset smaller so that there's no blank space */
if (viewPort.dx - (canvasDx - newViewPortOffsetX) > 0)
viewPort.x = canvasDx - viewPort.dx;
/* if a page is smaller than drawing area in y axis, y-center the page */
if (canvasDy < viewPort.dy) {
int offY = windowMargin.top + (viewPort.dy - canvasDy) / 2;
assert(offY >= 0.0);
for (int pageNo = 1; pageNo <= PageCount(); ++pageNo) {
PageInfo *pageInfo = GetPageInfo(pageNo);
if (!pageInfo->shown) {
assert(0.0 == pageInfo->visibleRatio);
continue;
}
pageInfo->pos.y += offY;
}
}
canvasSize = SizeI(std::max(canvasDx, viewPort.dx), std::max(canvasDy, viewPort.dy));
}
void DisplayModel::ChangeStartPage(int newStartPage)
{
assert(ValidPageNo(newStartPage));
assert(!IsContinuous(GetDisplayMode()));
int columns = ColumnsFromDisplayMode(GetDisplayMode());
startPage = newStartPage;
if (IsBookView(GetDisplayMode()) && newStartPage == 1 && columns > 1)
newStartPage--;
for (int pageNo = 1; pageNo <= PageCount(); pageNo++) {
PageInfo *pageInfo = GetPageInfo(pageNo);
if (IsContinuous(GetDisplayMode()))
pageInfo->shown = true;
else if (pageNo >= newStartPage && pageNo < newStartPage + columns) {
//lf("DisplayModel::changeStartPage() set page %d as shown", pageNo);
pageInfo->shown = true;
} else
pageInfo->shown = false;
pageInfo->visibleRatio = 0.0;
}
Relayout(zoomVirtual, rotation);
}
/* Given positions of each page in a large sheet that is continous view and
coordinates of a current view into that large sheet, calculate which
parts of each page is visible on the screen.
Needs to be recalucated after scrolling the view. */
void DisplayModel::RecalcVisibleParts()
{
assert(pagesInfo);
if (!pagesInfo)
return;
for (int pageNo = 1; pageNo <= PageCount(); ++pageNo) {
PageInfo *pageInfo = GetPageInfo(pageNo);
if (!pageInfo->shown) {
assert(0.0 == pageInfo->visibleRatio);
continue;
}
RectI pageRect = pageInfo->pos;
RectI visiblePart = pageRect.Intersect(viewPort);
pageInfo->visibleRatio = 0.0;
if (!visiblePart.IsEmpty()) {
assert(pageRect.dx > 0 && pageRect.dy > 0);
// calculate with floating point precision to prevent an integer overflow
pageInfo->visibleRatio = 1.0f * visiblePart.dx * visiblePart.dy / ((float)pageRect.dx * pageRect.dy);
}
pageInfo->pageOnScreen = pageRect;
pageInfo->pageOnScreen.Offset(-viewPort.x, -viewPort.y);
}
}
int DisplayModel::GetPageNoByPoint(PointI pt)
{
// no reasonable answer possible, if zoom hasn't been set yet
if (zoomReal <= 0)
return -1;
for (int pageNo = 1; pageNo <= PageCount(); ++pageNo) {
PageInfo *pageInfo = GetPageInfo(pageNo);
AssertCrash(0.0 == pageInfo->visibleRatio || pageInfo->shown);
if (!pageInfo->shown)
continue;
if (pageInfo->pageOnScreen.Contains(pt))
return pageNo;
}
return -1;
}
int DisplayModel::GetPageNextToPoint(PointI pt)
{
if (zoomReal <= 0)
return startPage;
unsigned int maxDist = UINT_MAX;
int closest = startPage;
for (int pageNo = 1; pageNo <= PageCount(); ++pageNo) {
PageInfo *pageInfo = GetPageInfo(pageNo);
AssertCrash(0.0 == pageInfo->visibleRatio || pageInfo->shown);
if (!pageInfo->shown)
continue;
if (pageInfo->pageOnScreen.Contains(pt))
return pageNo;
unsigned int dist = distSq(pt.x - pageInfo->pageOnScreen.x - pageInfo->pageOnScreen.dx / 2,
pt.y - pageInfo->pageOnScreen.y - pageInfo->pageOnScreen.dy / 2);
if (dist < maxDist) {
closest = pageNo;
maxDist = dist;
}
}
return closest;
}
PointI DisplayModel::CvtToScreen(int pageNo, PointD pt)
{
PageInfo *pageInfo = GetPageInfo(pageNo);
CrashIf(!pageInfo);
if (!pageInfo)
return PointI();
PointD p = engine->Transform(pt, pageNo, zoomReal, rotation);
// don't add the full 0.5 for rounding to account for precision errors
p.x += 0.499 + pageInfo->pageOnScreen.x;
p.y += 0.499 + pageInfo->pageOnScreen.y;
return p.ToInt();
}
RectI DisplayModel::CvtToScreen(int pageNo, RectD r)
{
PointI TL = CvtToScreen(pageNo, r.TL());
PointI BR = CvtToScreen(pageNo, r.BR());
return RectI::FromXY(TL, BR);
}
PointD DisplayModel::CvtFromScreen(PointI pt, int pageNo)
{
if (!ValidPageNo(pageNo))
pageNo = GetPageNextToPoint(pt);
const PageInfo *pageInfo = GetPageInfo(pageNo);
CrashIf(!pageInfo);
if (!pageInfo)
return PointD();
// don't add the full 0.5 for rounding to account for precision errors
PointD p = PointD(pt.x - 0.499 - pageInfo->pageOnScreen.x,
pt.y - 0.499 - pageInfo->pageOnScreen.y);
return engine->Transform(p, pageNo, zoomReal, rotation, true);
}
RectD DisplayModel::CvtFromScreen(RectI r, int pageNo)
{
if (!ValidPageNo(pageNo))
pageNo = GetPageNextToPoint(r.TL());
PointD TL = CvtFromScreen(r.TL(), pageNo);
PointD BR = CvtFromScreen(r.BR(), pageNo);
return RectD::FromXY(TL, BR);
}
/* Given position 'x'/'y' in the draw area, returns a structure describing
a link or nullptr if there is no link at this position. */
PageElement *DisplayModel::GetElementAtPos(PointI pt)
{
int pageNo = GetPageNoByPoint(pt);
if (!ValidPageNo(pageNo))
return nullptr;
// only return visible elements (for cursor interaction)
if (!RectI(PointI(), viewPort.Size()).Contains(pt))
return nullptr;
PointD pos = CvtFromScreen(pt, pageNo);
return engine->GetElementAtPos(pageNo, pos);
}
// note: returns false for pages that haven't been rendered yet
bool DisplayModel::IsOverText(PointI pt)
{
int pageNo = GetPageNoByPoint(pt);
if (!ValidPageNo(pageNo))
return false;
// only return visible elements (for cursor interaction)
if (!RectI(PointI(), viewPort.Size()).Contains(pt))
return false;
if (!textCache->HasData(pageNo))
return false;
PointD pos = CvtFromScreen(pt, pageNo);
return textSelection->IsOverGlyph(pageNo, pos.x, pos.y);
}
void DisplayModel::RenderVisibleParts()
{
int firstVisiblePage = 0;
int lastVisiblePage = 0;
for (int pageNo = 1; pageNo <= PageCount(); ++pageNo) {
PageInfo *pageInfo = GetPageInfo(pageNo);
if (pageInfo->visibleRatio > 0.0) {
assert(pageInfo->shown);
if (0 == firstVisiblePage)
firstVisiblePage = pageNo;
lastVisiblePage = pageNo;
}
}
// no page is visible if e.g. the window is resized
// vertically until only the title bar remains visible
if (0 == firstVisiblePage)
return;
// rendering happens LIFO except if the queue is currently
// empty, so request the visible pages first and last to
// make sure they're rendered before the predicted pages
for (int pageNo = firstVisiblePage; pageNo <= lastVisiblePage; pageNo++) {
cb->RequestRendering(pageNo);
}
if (gPredictiveRender) {
// prerender two more pages in facing and book view modes
// if the rendering queue still has place for them
if (!IsSingle(GetDisplayMode())) {
if (firstVisiblePage > 2)
cb->RequestRendering(firstVisiblePage - 2);
if (lastVisiblePage + 1 < PageCount())
cb->RequestRendering(lastVisiblePage + 2);
}
if (firstVisiblePage > 1)
cb->RequestRendering(firstVisiblePage - 1);
if (lastVisiblePage < PageCount())
cb->RequestRendering(lastVisiblePage + 1);
}
// request the visible pages last so that the above requested
// invisible pages are not rendered if the queue fills up
for (int pageNo = lastVisiblePage; pageNo >= firstVisiblePage; pageNo--) {
cb->RequestRendering(pageNo);
}
}
void DisplayModel::SetViewPortSize(SizeI newViewPortSize)
{
ScrollState ss;
bool isDocReady = ValidPageNo(startPage) && zoomReal != 0;
if (isDocReady)
ss = GetScrollState();
totalViewPortSize = newViewPortSize;
Relayout(zoomVirtual, rotation);
if (isDocReady) {
// when fitting to content, let GoToPage do the necessary scrolling
if (zoomVirtual != ZOOM_FIT_CONTENT)
SetScrollState(ss);
else
GoToPage(ss.page, 0);
} else {
RecalcVisibleParts();
RenderVisibleParts();
cb->UpdateScrollbars(canvasSize);
}
}
RectD DisplayModel::GetContentBox(int pageNo, RenderTarget target)
{
RectD cbox;
// we cache the contentBox for the View target
if (Target_View == target) {
PageInfo *pageInfo = GetPageInfo(pageNo);
if (pageInfo->contentBox.IsEmpty())
pageInfo->contentBox = engine->PageContentBox(pageNo);
cbox = pageInfo->contentBox;
}
else
cbox = engine->PageContentBox(pageNo, target);
return engine->Transform(cbox, pageNo, zoomReal, rotation);
}
/* get the (screen) coordinates of the point where a page's actual
content begins (relative to the page's top left corner) */
PointI DisplayModel::GetContentStart(int pageNo)
{
RectD contentBox = GetContentBox(pageNo);
if (contentBox.IsEmpty())
return PointI(0, 0);
return contentBox.TL().ToInt();
}
// TODO: what's GoToPage supposed to do for Facing at 400% zoom?
void DisplayModel::GoToPage(int pageNo, int scrollY, bool addNavPt, int scrollX)
{
assert(ValidPageNo(pageNo));
if (!ValidPageNo(pageNo))
return;
if (addNavPt)
AddNavPoint();
/* in facing mode only start at odd pages (odd because page
numbering starts with 1, so odd is really an even page) */
bool scrollToNextPage = false;
if (!IsSingle(GetDisplayMode())) {
int actualPageNo = pageNo;
pageNo = FirstPageInARowNo(pageNo, ColumnsFromDisplayMode(GetDisplayMode()), IsBookView(GetDisplayMode()));
scrollToNextPage = pageNo == actualPageNo - 1;
}
if (!IsContinuous(GetDisplayMode())) {
/* in single page mode going to another page involves recalculating
the size of canvas */
ChangeStartPage(pageNo);
} else if (ZOOM_FIT_CONTENT == zoomVirtual) {
// make sure that CalcZoomVirtual uses the correct page to calculate
// the zoom level for (visibility will be recalculated below anyway)
for (int i = PageCount(); i > 0; i--)
GetPageInfo(i)->visibleRatio = (i == pageNo ? 1.0f : 0);
Relayout(zoomVirtual, rotation);
}
//lf("DisplayModel::GoToPage(pageNo=%d, scrollY=%d)", pageNo, scrollY);
PageInfo * pageInfo = GetPageInfo(pageNo);
// intentionally ignore scrollX and scrollY when fitting to content
if (ZOOM_FIT_CONTENT == zoomVirtual) {
// scroll down to where the actual content starts
PointI start = GetContentStart(pageNo);
scrollX = start.x;
scrollY = start.y;
if (ColumnsFromDisplayMode(GetDisplayMode()) > 1) {
int lastPageNo = LastPageInARowNo(pageNo, ColumnsFromDisplayMode(GetDisplayMode()), IsBookView(GetDisplayMode()), PageCount());
PointI second = GetContentStart(lastPageNo);
scrollY = std::min(scrollY, second.y);
}
viewPort.x = scrollX + pageInfo->pos.x - windowMargin.left;
}
else if (-1 != scrollX)
viewPort.x = scrollX;
// make sure to not display the blank space beside the first page in cover mode
else if (-1 == scrollX && 1 == pageNo && IsBookView(GetDisplayMode()))
viewPort.x = pageInfo->pos.x - windowMargin.left;
// make sure that at least part of the page is visible
else if (viewPort.x >= pageInfo->pos.x + pageInfo->pos.dx)
viewPort.x = pageInfo->pos.x;
// make sure to scroll to the correct page
if (-1 != scrollX && scrollToNextPage)
viewPort.x += pageInfo->pos.dx;
/* Hack: if an image is smaller in Y axis than the draw area, then we center
the image by setting pageInfo->currPos.y in RecalcPagesInfo. So we shouldn't
scroll (adjust viewPort.y) there because it defeats the purpose.
TODO: is there a better way of y-centering? */
viewPort.y = scrollY;
// Move the next page to the top (unless the remaining pages fit onto a single screen)
if (IsContinuous(GetDisplayMode()))
viewPort.y = pageInfo->pos.y - windowMargin.top + scrollY;
viewPort.x = limitValue(viewPort.x, 0, canvasSize.dx - viewPort.dx);
viewPort.y = limitValue(viewPort.y, 0, canvasSize.dy - viewPort.dy);
RecalcVisibleParts();
RenderVisibleParts();
cb->UpdateScrollbars(canvasSize);
cb->PageNoChanged(this, pageNo);