forked from sumatrapdfreader/sumatrapdf
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathRenderCache.cpp
More file actions
766 lines (664 loc) · 27.4 KB
/
Copy pathRenderCache.cpp
File metadata and controls
766 lines (664 loc) · 27.4 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
/* Copyright 2015 the SumatraPDF project authors (see AUTHORS file).
License: GPLv3 */
// 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 "RenderCache.h"
#include "TextSelection.h"
#pragma warning(disable: 28159) // silence /analyze: Consider using 'GetTickCount64' instead of 'GetTickCount'
// TODO: remove this and always conserve memory?
/* Define if you want to conserve memory by always freeing cached bitmaps
for pages not visible. Disabling this might lead to pages not rendering
due to insufficient (GDI) memory. */
#define CONSERVE_MEMORY
// define to view the tile boundaries
#undef SHOW_TILE_LAYOUT
RenderCache::RenderCache()
: cacheCount(0), requestCount(0),
maxTileSize(GetSystemMetrics(SM_CXSCREEN), GetSystemMetrics(SM_CYSCREEN)),
isRemoteSession(GetSystemMetrics(SM_REMOTESESSION))
{
textColor = WIN_COL_BLACK;
backgroundColor = WIN_COL_WHITE;
InitializeCriticalSection(&cacheAccess);
InitializeCriticalSection(&requestAccess);
startRendering = CreateEvent(nullptr, FALSE, FALSE, nullptr);
renderThread = CreateThread(nullptr, 0, RenderCacheThread, this, 0, 0);
assert(nullptr != renderThread);
}
RenderCache::~RenderCache()
{
EnterCriticalSection(&requestAccess);
EnterCriticalSection(&cacheAccess);
CloseHandle(renderThread);
CloseHandle(startRendering);
assert(!curReq && 0 == requestCount && 0 == cacheCount);
LeaveCriticalSection(&cacheAccess);
DeleteCriticalSection(&cacheAccess);
LeaveCriticalSection(&requestAccess);
DeleteCriticalSection(&requestAccess);
}
/* Find a bitmap for a page defined by <dm> and <pageNo> and optionally also
<rotation> and <zoom> in the cache - call DropCacheEntry when you
no longer need a found entry. */
BitmapCacheEntry *RenderCache::Find(DisplayModel *dm, int pageNo, int rotation, float zoom, TilePosition *tile)
{
ScopedCritSec scope(&cacheAccess);
rotation = NormalizeRotation(rotation);
for (int i = 0; i < cacheCount; i++) {
BitmapCacheEntry *entry = cache[i];
if ((dm == entry->dm) && (pageNo == entry->pageNo) && (rotation == entry->rotation) &&
(INVALID_ZOOM == zoom || zoom == entry->zoom) && (!tile || entry->tile == *tile)) {
entry->refs++;
return entry;
}
}
return nullptr;
}
bool RenderCache::Exists(DisplayModel *dm, int pageNo, int rotation, float zoom, TilePosition *tile)
{
BitmapCacheEntry *entry = Find(dm, pageNo, rotation, zoom, tile);
if (entry)
DropCacheEntry(entry);
return entry != nullptr;
}
void RenderCache::DropCacheEntry(BitmapCacheEntry *entry)
{
ScopedCritSec scope(&cacheAccess);
assert(entry);
if (!entry) return;
if (0 == --entry->refs) {
delete entry;
}
}
void RenderCache::Add(PageRenderRequest &req, RenderedBitmap *bitmap)
{
ScopedCritSec scope(&cacheAccess);
assert(req.dm);
req.rotation = NormalizeRotation(req.rotation);
assert(cacheCount <= MAX_BITMAPS_CACHED);
/* It's possible there still is a cached bitmap with different zoom/rotation */
FreePage(req.dm, req.pageNo, &req.tile);
if (cacheCount >= MAX_BITMAPS_CACHED) {
// free an invisible page of the same DisplayModel ...
for (int i = 0; i < cacheCount; i++) {
if (cache[i]->dm == req.dm && !req.dm->PageVisibleNearby(cache[i]->pageNo)) {
DropCacheEntry(cache[i]);
cacheCount--;
memmove(&cache[i], &cache[i + 1], (cacheCount - i) * sizeof(cache[0]));
break;
}
}
// ... or just the oldest cached page
if (cacheCount >= MAX_BITMAPS_CACHED) {
DropCacheEntry(cache[0]);
cacheCount--;
memmove(&cache[0], &cache[1], cacheCount * sizeof(cache[0]));
}
}
// Copy the PageRenderRequest as it will be reused
cache[cacheCount] = new BitmapCacheEntry(req.dm, req.pageNo, req.rotation, req.zoom, req.tile, bitmap);
CrashIf(!cache[cacheCount]);
if (!cache[cacheCount])
delete bitmap;
else
cacheCount++;
}
static RectD GetTileRect(RectD pagerect, TilePosition tile)
{
CrashIf(tile.res > 30);
RectD rect;
rect.dx = pagerect.dx / (1ULL << tile.res);
rect.dy = pagerect.dy / (1ULL << tile.res);
rect.x = pagerect.x + tile.col * rect.dx;
rect.y = pagerect.y + ((1ULL << tile.res) - tile.row - 1) * rect.dy;
return rect;
}
// get the coordinates of a specific tile
static RectI GetTileRectDevice(BaseEngine *engine, int pageNo, int rotation, float zoom, TilePosition tile)
{
RectD mediabox = engine->PageMediabox(pageNo);
if (tile.res > 0 && tile.res != INVALID_TILE_RES)
mediabox = GetTileRect(mediabox, tile);
RectD pixelbox = engine->Transform(mediabox, pageNo, zoom, rotation);
return pixelbox.Round();
}
static RectD GetTileRectUser(BaseEngine *engine, int pageNo, int rotation, float zoom, TilePosition tile)
{
RectI pixelbox = GetTileRectDevice(engine, pageNo, rotation, zoom, tile);
return engine->Transform(pixelbox.Convert<double>(), pageNo, zoom, rotation, true);
}
static RectI GetTileOnScreen(BaseEngine *engine, int pageNo, int rotation, float zoom, TilePosition tile, RectI pageOnScreen)
{
RectI bbox = GetTileRectDevice(engine, pageNo, rotation, zoom, tile);
bbox.Offset(pageOnScreen.x, pageOnScreen.y);
return bbox;
}
static bool IsTileVisible(DisplayModel *dm, int pageNo, TilePosition tile, float fuzz=0)
{
if (!dm) return false;
PageInfo *pageInfo = dm->GetPageInfo(pageNo);
if (!dm->GetEngine() || !pageInfo) return false;
RectI tileOnScreen = GetTileOnScreen(dm->GetEngine(), pageNo, dm->GetRotation(), dm->GetZoomReal(), tile, pageInfo->pageOnScreen);
// consider nearby tiles visible depending on the fuzz factor
tileOnScreen.x -= (int)(tileOnScreen.dx * fuzz * 0.5);
tileOnScreen.dx = (int)(tileOnScreen.dx * (fuzz + 1));
tileOnScreen.y -= (int)(tileOnScreen.dy * fuzz * 0.5);
tileOnScreen.dy = (int)(tileOnScreen.dy * (fuzz + 1));
RectI screen(PointI(), dm->GetViewPort().Size());
return !tileOnScreen.Intersect(screen).IsEmpty();
}
/* Free all bitmaps in the cache that are of a specific page (or all pages
of the given DisplayModel, or even all invisible pages). */
void RenderCache::FreePage(DisplayModel *dm, int pageNo, TilePosition *tile)
{
ScopedCritSec scope(&cacheAccess);
int cacheCountTmp = cacheCount;
int curPos = 0;
for (int i = 0; i < cacheCountTmp; i++) {
BitmapCacheEntry* entry = cache[i];
bool shouldFree;
if (dm && pageNo != INVALID_PAGE_NO) {
// a specific page
shouldFree = (entry->dm == dm) && (entry->pageNo == pageNo);
if (tile) {
// a given tile of the page or all tiles not rendered at a given resolution
// (and at resolution 0 for quick zoom previews)
shouldFree = shouldFree && (entry->tile == *tile ||
tile->row == (USHORT)-1 && entry->tile.res > 0 && entry->tile.res != tile->res ||
tile->row == (USHORT)-1 && entry->tile.res == 0 && entry->outOfDate);
}
} else if (dm) {
// all pages of this DisplayModel
shouldFree = (cache[i]->dm == dm);
} else {
// all invisible pages resp. page tiles
shouldFree = !entry->dm->PageVisibleNearby(entry->pageNo);
if (!shouldFree && entry->tile.res > 1)
shouldFree = !IsTileVisible(entry->dm, entry->pageNo, entry->tile, 2.0);
}
if (shouldFree) {
DropCacheEntry(entry);
cache[i] = nullptr;
cacheCount--;
}
if (curPos != i)
cache[curPos] = cache[i];
if (!shouldFree)
curPos++;
}
}
// keep the cached bitmaps for visible pages to avoid flickering during a reload.
// mark invisible pages as out-of-date to prevent inconsistencies
void RenderCache::KeepForDisplayModel(DisplayModel *oldDm, DisplayModel *newDm)
{
ScopedCritSec scope(&cacheAccess);
for (int i = 0; i < cacheCount; i++) {
if (cache[i]->dm == oldDm) {
if (oldDm->PageVisible(cache[i]->pageNo))
cache[i]->dm = newDm;
// make sure that the page is rerendered eventually
cache[i]->zoom = INVALID_ZOOM;
cache[i]->outOfDate = true;
}
}
}
// marks all tiles containing rect of pageNo as out of date
void RenderCache::Invalidate(DisplayModel *dm, int pageNo, RectD rect)
{
ScopedCritSec scopeReq(&requestAccess);
ClearQueueForDisplayModel(dm, pageNo);
if (curReq && curReq->dm == dm && curReq->pageNo == pageNo)
AbortCurrentRequest();
ScopedCritSec scopeCache(&cacheAccess);
RectD mediabox = dm->GetEngine()->PageMediabox(pageNo);
for (int i = 0; i < cacheCount; i++) {
if (cache[i]->dm == dm && cache[i]->pageNo == pageNo &&
!GetTileRect(mediabox, cache[i]->tile).Intersect(rect).IsEmpty()) {
cache[i]->zoom = INVALID_ZOOM;
cache[i]->outOfDate = true;
}
}
}
// determine the count of tiles required for a page at a given zoom level
USHORT RenderCache::GetTileRes(DisplayModel *dm, int pageNo)
{
RectD mediabox = dm->GetEngine()->PageMediabox(pageNo);
RectD pixelbox = dm->GetEngine()->Transform(mediabox, pageNo, dm->GetZoomReal(), dm->GetRotation());
float factorW = (float)pixelbox.dx / (maxTileSize.dx + 1);
float factorH = (float)pixelbox.dy / (maxTileSize.dy + 1);
// using the geometric mean instead of the maximum factor
// so that the tile area doesn't get too small in comparison
// to maxTileSize (but remains smaller)
float factorAvg = sqrtf(factorW * factorH);
// use larger tiles when fitting page or width or when a page is smaller
// than the visible canvas width/height or when rendering pages
// without clipping optimizations
if (dm->GetZoomVirtual() == ZOOM_FIT_PAGE || dm->GetZoomVirtual() == ZOOM_FIT_WIDTH ||
pixelbox.dx <= dm->GetViewPort().dx || pixelbox.dy < dm->GetViewPort().dy ||
!dm->GetEngine()->HasClipOptimizations(pageNo)) {
factorAvg /= 2.0;
}
USHORT res = 0;
if (factorAvg > 1.5)
res = (USHORT)ceilf(log(factorAvg) / log(2.0f));
// limit res to 30, so that (1 << res) doesn't overflow for 32-bit signed int
return std::min(res, (USHORT)30);
}
// get the maximum resolution available for the given page
USHORT RenderCache::GetMaxTileRes(DisplayModel *dm, int pageNo, int rotation)
{
ScopedCritSec scope(&cacheAccess);
USHORT maxRes = 0;
for (int i = 0; i < cacheCount; i++) {
if (cache[i]->dm == dm && cache[i]->pageNo == pageNo &&
cache[i]->rotation == rotation) {
maxRes = std::max(cache[i]->tile.res, maxRes);
}
}
return maxRes;
}
// reduce the size of tiles in order to hopefully use less memory overall
bool RenderCache::ReduceTileSize()
{
fprintf(stderr, "RenderCache: reducing tile size (current: %d x %d)\n", maxTileSize.dx, maxTileSize.dy);
if (maxTileSize.dx < 200 || maxTileSize.dy < 200)
return false;
ScopedCritSec scope1(&requestAccess);
ScopedCritSec scope2(&cacheAccess);
if (maxTileSize.dx > maxTileSize.dy)
maxTileSize.dx /= 2;
else
maxTileSize.dy /= 2;
// invalidate all rendered bitmaps and all requests
while (cacheCount > 0)
FreeForDisplayModel(cache[0]->dm);
while (requestCount > 0)
ClearQueueForDisplayModel(requests[0].dm);
AbortCurrentRequest();
return true;
}
void RenderCache::RequestRendering(DisplayModel *dm, int pageNo)
{
TilePosition tile(GetTileRes(dm, pageNo), 0, 0);
// only honor the request if there's a good chance that the
// rendered tile will actually be used
if (tile.res > 1)
return;
RequestRendering(dm, pageNo, tile);
// render both tiles of the first row when splitting a page in four
// (which always happens on larger displays for Fit Width)
if (tile.res == 1 && !IsRenderQueueFull()) {
tile.col = 1;
RequestRendering(dm, pageNo, tile, false);
}
}
/* Render a bitmap for page <pageNo> in <dm>. */
void RenderCache::RequestRendering(DisplayModel *dm, int pageNo, TilePosition tile, bool clearQueueForPage)
{
ScopedCritSec scope(&requestAccess);
assert(dm);
if (!dm || dm->dontRenderFlag)
return;
int rotation = NormalizeRotation(dm->GetRotation());
float zoom = dm->GetZoomReal(pageNo);
if (curReq && (curReq->pageNo == pageNo) && (curReq->dm == dm) && (curReq->tile == tile)) {
if ((curReq->zoom == zoom) && (curReq->rotation == rotation)) {
/* we're already rendering exactly the same page */
return;
}
/* Currently rendered page is for the same page but with different zoom
or rotation, so abort it */
AbortCurrentRequest();
}
// clear requests for tiles of different resolution and invisible tiles
if (clearQueueForPage)
ClearQueueForDisplayModel(dm, pageNo, &tile);
for (int i = 0; i < requestCount; i++) {
PageRenderRequest* req = &(requests[i]);
if ((req->pageNo == pageNo) && (req->dm == dm) && (req->tile == tile)) {
if ((req->zoom == zoom) && (req->rotation == rotation)) {
/* Request with exactly the same parameters already queued for
rendering. Move it to the top of the queue so that it'll
be rendered faster. */
PageRenderRequest tmp;
tmp = requests[requestCount-1];
requests[requestCount-1] = *req;
*req = tmp;
} else {
/* There was a request queued for the same page but with different
zoom or rotation, so only replace this request */
req->zoom = zoom;
req->rotation = rotation;
}
return;
}
}
if (Exists(dm, pageNo, rotation, zoom, &tile)) {
/* This page has already been rendered in the correct dimensions
and isn't about to be rerendered in different dimensions */
return;
}
Render(dm, pageNo, rotation, zoom, &tile);
}
void RenderCache::Render(DisplayModel *dm, int pageNo, int rotation, float zoom, RectD pageRect, RenderingCallback& callback)
{
bool ok = Render(dm, pageNo, rotation, zoom, nullptr, &pageRect, &callback);
if (!ok)
callback.Callback();
}
bool RenderCache::Render(DisplayModel *dm, int pageNo, int rotation, float zoom,
TilePosition *tile, RectD *pageRect, RenderingCallback *renderCb)
{
assert(dm);
if (!dm || dm->dontRenderFlag)
return false;
assert(tile || pageRect && renderCb);
if (!tile && !(pageRect && renderCb))
return false;
ScopedCritSec scope(&requestAccess);
PageRenderRequest* newRequest;
/* add request to the queue */
if (requestCount == MAX_PAGE_REQUESTS) {
/* queue is full -> remove the oldest items on the queue */
if (requests[0].renderCb)
requests[0].renderCb->Callback();
memmove(&(requests[0]), &(requests[1]), sizeof(PageRenderRequest) * (MAX_PAGE_REQUESTS - 1));
newRequest = &(requests[MAX_PAGE_REQUESTS-1]);
} else {
newRequest = &(requests[requestCount]);
requestCount++;
}
assert(requestCount <= MAX_PAGE_REQUESTS);
newRequest->dm = dm;
newRequest->pageNo = pageNo;
newRequest->rotation = rotation;
newRequest->zoom = zoom;
if (tile) {
newRequest->pageRect = GetTileRectUser(dm->GetEngine(), pageNo, rotation, zoom, *tile);
newRequest->tile = *tile;
}
else if (pageRect) {
newRequest->pageRect = *pageRect;
// can't cache bitmaps that aren't for a given tile
assert(renderCb);
}
else
assert(0);
newRequest->abort = false;
newRequest->abortCookie = nullptr;
newRequest->timestamp = GetTickCount();
newRequest->renderCb = renderCb;
SetEvent(startRendering);
return true;
}
UINT RenderCache::GetRenderDelay(DisplayModel *dm, int pageNo, TilePosition tile)
{
ScopedCritSec scope(&requestAccess);
if (curReq && curReq->pageNo == pageNo && curReq->dm == dm && curReq->tile == tile)
return GetTickCount() - curReq->timestamp;
for (int i = 0; i < requestCount; i++)
if (requests[i].pageNo == pageNo && requests[i].dm == dm && requests[i].tile == tile)
return GetTickCount() - requests[i].timestamp;
return RENDER_DELAY_UNDEFINED;
}
bool RenderCache::GetNextRequest(PageRenderRequest *req)
{
ScopedCritSec scope(&requestAccess);
if (requestCount == 0)
return false;
assert(requestCount > 0);
assert(requestCount <= MAX_PAGE_REQUESTS);
requestCount--;
*req = requests[requestCount];
curReq = req;
assert(requestCount >= 0);
assert(!req->abort);
return true;
}
bool RenderCache::ClearCurrentRequest()
{
ScopedCritSec scope(&requestAccess);
if (curReq)
delete curReq->abortCookie;
curReq = nullptr;
bool isQueueEmpty = requestCount == 0;
return isQueueEmpty;
}
/* Wait until rendering of a page beloging to <dm> has finished. */
/* TODO: this might take some time, would be good to show a dialog to let the
user know he has to wait until we finish */
void RenderCache::CancelRendering(DisplayModel *dm)
{
ClearQueueForDisplayModel(dm);
for (;;) {
EnterCriticalSection(&requestAccess);
if (!curReq || (curReq->dm != dm)) {
// to be on the safe side
ClearQueueForDisplayModel(dm);
LeaveCriticalSection(&requestAccess);
return;
}
AbortCurrentRequest();
LeaveCriticalSection(&requestAccess);
/* TODO: busy loop is not good, but I don't have a better idea */
Sleep(50);
}
}
void RenderCache::ClearQueueForDisplayModel(DisplayModel *dm, int pageNo, TilePosition *tile)
{
ScopedCritSec scope(&requestAccess);
int reqCount = requestCount;
int curPos = 0;
for (int i = 0; i < reqCount; i++) {
PageRenderRequest *req = &(requests[i]);
bool shouldRemove = req->dm == dm && (pageNo == INVALID_PAGE_NO || req->pageNo == pageNo) &&
(!tile || req->tile.res != tile->res || !IsTileVisible(dm, req->pageNo, *tile, 0.5));
if (i != curPos)
requests[curPos] = requests[i];
if (shouldRemove) {
if (req->renderCb)
req->renderCb->Callback();
requestCount--;
} else
curPos++;
}
}
void RenderCache::AbortCurrentRequest()
{
ScopedCritSec scope(&requestAccess);
if (!curReq)
return;
if (curReq->abortCookie)
curReq->abortCookie->Abort();
curReq->abort = true;
}
DWORD WINAPI RenderCache::RenderCacheThread(LPVOID data)
{
RenderCache *cache = (RenderCache *)data;
PageRenderRequest req;
RenderedBitmap * bmp;
for (;;) {
if (cache->ClearCurrentRequest()) {
DWORD waitResult = WaitForSingleObject(cache->startRendering, INFINITE);
// Is it not a page render request?
if (WAIT_OBJECT_0 != waitResult)
continue;
}
if (!cache->GetNextRequest(&req))
continue;
if (!req.dm->PageVisibleNearby(req.pageNo) && !req.renderCb)
continue;
if (req.dm->dontRenderFlag) {
if (req.renderCb)
req.renderCb->Callback();
continue;
}
// make sure that we have extracted page text for
// all rendered pages to allow text selection and
// searching without any further delays
if (!req.dm->textCache->HasData(req.pageNo))
req.dm->textCache->GetData(req.pageNo);
CrashIf(req.abortCookie != nullptr);
bmp = req.dm->GetEngine()->RenderBitmap(req.pageNo, req.zoom, req.rotation, &req.pageRect, Target_View, &req.abortCookie);
if (req.abort) {
delete bmp;
if (req.renderCb)
req.renderCb->Callback();
continue;
}
if (req.renderCb) {
// the callback must free the RenderedBitmap
req.renderCb->Callback(bmp);
req.renderCb = (RenderingCallback *)1; // will crash if accessed again, which should not happen
}
else {
// don't replace colors for individual images
if (bmp && !req.dm->GetEngine()->IsImageCollection())
UpdateBitmapColors(bmp->GetBitmap(), cache->textColor, cache->backgroundColor);
cache->Add(req, bmp);
req.dm->RepaintDisplay();
}
}
}
// TODO: conceptually, RenderCache is not the right place for code that paints
// (this is the only place that knows about Tiles, though)
UINT RenderCache::PaintTile(HDC hdc, RectI bounds, DisplayModel *dm, int pageNo,
TilePosition tile, RectI tileOnScreen, bool renderMissing,
bool *renderOutOfDateCue, bool *renderedReplacement)
{
BitmapCacheEntry *entry = Find(dm, pageNo, dm->GetRotation(), dm->GetZoomReal(), &tile);
UINT renderDelay = 0;
if (!entry) {
if (!isRemoteSession) {
if (renderedReplacement)
*renderedReplacement = true;
entry = Find(dm, pageNo, dm->GetRotation(), INVALID_ZOOM, &tile);
}
renderDelay = GetRenderDelay(dm, pageNo, tile);
if (renderMissing && RENDER_DELAY_UNDEFINED == renderDelay && !IsRenderQueueFull())
RequestRendering(dm, pageNo, tile);
}
RenderedBitmap *renderedBmp = entry ? entry->bitmap : nullptr;
HBITMAP hbmp = renderedBmp ? renderedBmp->GetBitmap() : nullptr;
if (!hbmp) {
if (entry && !(renderedBmp && ReduceTileSize()))
renderDelay = RENDER_DELAY_FAILED;
else if (0 == renderDelay)
renderDelay = 1;
if (entry)
DropCacheEntry(entry);
return renderDelay;
}
HDC bmpDC = CreateCompatibleDC(hdc);
if (bmpDC) {
SizeI bmpSize = renderedBmp->Size();
int xSrc = -std::min(tileOnScreen.x, 0);
int ySrc = -std::min(tileOnScreen.y, 0);
float factor = std::min(1.0f * bmpSize.dx / tileOnScreen.dx, 1.0f * bmpSize.dy / tileOnScreen.dy);
HGDIOBJ prevBmp = SelectObject(bmpDC, hbmp);
if (factor != 1.0f)
StretchBlt(hdc, bounds.x, bounds.y, bounds.dx, bounds.dy,
bmpDC, (int)(xSrc * factor), (int)(ySrc * factor),
(int)(bounds.dx * factor), (int)(bounds.dy * factor), SRCCOPY);
else
BitBlt(hdc, bounds.x, bounds.y, bounds.dx, bounds.dy,
bmpDC, xSrc, ySrc, SRCCOPY);
SelectObject(bmpDC, prevBmp);
DeleteDC(bmpDC);
#ifdef SHOW_TILE_LAYOUT
HPEN pen = CreatePen(PS_SOLID, 1, RGB(0xff, 0xff, 0x00));
HGDIOBJ oldPen = SelectObject(hdc, pen);
PaintRect(hdc, bounds);
DeletePen(SelectObject(hdc, oldPen));
#endif
}
if (entry->outOfDate) {
if (renderOutOfDateCue)
*renderOutOfDateCue = true;
CrashIf(renderedReplacement && !*renderedReplacement);
}
DropCacheEntry(entry);
return 0;
}
static int cmpTilePosition(const void *a, const void *b)
{
const TilePosition *ta = (const TilePosition *)a, *tb = (const TilePosition *)b;
return ta->res != tb->res ? ta->res - tb->res :
ta->row != tb->row ? ta->row - tb->row :
ta->col - tb->col;
}
UINT RenderCache::Paint(HDC hdc, RectI bounds, DisplayModel *dm, int pageNo,
PageInfo *pageInfo, bool *renderOutOfDateCue)
{
assert(pageInfo->shown && 0.0 != pageInfo->visibleRatio);
if (!dm->ShouldCacheRendering(pageNo)) {
int rotation = dm->GetRotation();
float zoom = dm->GetZoomReal(pageNo);
bounds = pageInfo->pageOnScreen.Intersect(bounds);
RectD area = bounds.Convert<double>();
area.Offset(-pageInfo->pageOnScreen.x, -pageInfo->pageOnScreen.y);
area = dm->GetEngine()->Transform(area, pageNo, zoom, rotation, true);
RenderedBitmap *bmp = dm->GetEngine()->RenderBitmap(pageNo, zoom, rotation, &area);
bool success = bmp && bmp->GetBitmap() && bmp->StretchDIBits(hdc, bounds);
delete bmp;
return success ? 0 : RENDER_DELAY_FAILED;
}
int rotation = dm->GetRotation();
float zoom = dm->GetZoomReal();
USHORT targetRes = GetTileRes(dm, pageNo);
USHORT maxRes = GetMaxTileRes(dm, pageNo, rotation);
if (maxRes < targetRes)
maxRes = targetRes;
Vec<TilePosition> queue;
queue.Append(TilePosition(0, 0, 0));
UINT renderDelayMin = RENDER_DELAY_UNDEFINED;
bool neededScaling = false;
while (queue.Count() > 0) {
TilePosition tile = queue.PopAt(0);
RectI tileOnScreen = GetTileOnScreen(dm->GetEngine(), pageNo, rotation, zoom, tile, pageInfo->pageOnScreen);
if (tileOnScreen.IsEmpty()) {
// display an error message when only empty tiles should be drawn (i.e. on page loading errors)
renderDelayMin = std::min(RENDER_DELAY_FAILED, renderDelayMin);
continue;
}
tileOnScreen = pageInfo->pageOnScreen.Intersect(tileOnScreen);
RectI isect = bounds.Intersect(tileOnScreen);
if (isect.IsEmpty())
continue;
bool isTargetRes = tile.res == targetRes;
UINT renderDelay = PaintTile(hdc, isect, dm, pageNo, tile, tileOnScreen, isTargetRes,
renderOutOfDateCue, isTargetRes ? &neededScaling : nullptr);
if (!(isTargetRes && 0 == renderDelay) && tile.res < maxRes) {
queue.Append(TilePosition(tile.res + 1, tile.row * 2, tile.col * 2));
queue.Append(TilePosition(tile.res + 1, tile.row * 2, tile.col * 2 + 1));
queue.Append(TilePosition(tile.res + 1, tile.row * 2 + 1, tile.col * 2));
queue.Append(TilePosition(tile.res + 1, tile.row * 2 + 1, tile.col * 2 + 1));
}
if (isTargetRes && renderDelay > 0)
neededScaling = true;
renderDelayMin = std::min(renderDelay, renderDelayMin);
// paint tiles from left to right from top to bottom
if (tile.res > 0 && queue.Count() > 0 && tile.res < queue.At(0).res)
queue.Sort(cmpTilePosition);
}
#ifdef CONSERVE_MEMORY
if (!neededScaling) {
if (renderOutOfDateCue)
*renderOutOfDateCue = false;
// free tiles with different resolution
TilePosition tile(targetRes, (USHORT)-1, 0);
FreePage(dm, pageNo, &tile);
}
FreeNotVisible();
#endif
return renderDelayMin;
}