forked from sumatrapdfreader/sumatrapdf
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathEngineMupdf.cpp
More file actions
4665 lines (4159 loc) · 138 KB
/
Copy pathEngineMupdf.cpp
File metadata and controls
4665 lines (4159 loc) · 138 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 2022 the SumatraPDF project authors (see AUTHORS file).
License: GPLv3 */
extern "C" {
#include <mupdf/fitz.h>
#include <mupdf/pdf.h>
#include <mupdf/helpers/pkcs7-windows.h>
#include "../mupdf/source/fitz/color-imp.h"
}
#include "utils/BaseUtil.h"
#include "utils/Archive.h"
#include "utils/ScopedWin.h"
#include "utils/FileUtil.h"
#include "utils/GdiPlusUtil.h"
#include "utils/GuessFileType.h"
#include "utils/WinUtil.h"
#include "utils/ZipUtil.h"
#include "utils/Timer.h"
#include "wingui/UIModels.h"
#include "Annotation.h"
#include "DocProperties.h"
#include "DocController.h"
#include "EngineBase.h"
#include "EngineMupdf.h"
#include "EngineAll.h"
#include "EbookBase.h"
#include "EbookDoc.h"
#include "SumatraConfig.h"
#include "Settings.h"
#include "utils/Log.h"
// A5
static float layoutA5DxPt = 420.F;
static float layoutA5DyPt = 595.F;
// A4
static float layoutA4DxPt = 595.F;
static float layoutA4DyPt = 842.F;
static float layoutFontEm = 11.F;
// in mupdf_load_system_font.c
extern "C" void install_load_windows_font_funcs(fz_context* ctx);
static AnnotationType AnnotationTypeFromPdfAnnot(enum pdf_annot_type tp) {
return (AnnotationType)tp;
}
Kind kindEngineMupdf = "enginePdf";
EngineMupdf* AsEngineMupdf(EngineBase* engine) {
if (!engine || !IsOfKind(engine, kindEngineMupdf)) {
return nullptr;
}
return (EngineMupdf*)engine;
}
class FitzAbortCookie : public AbortCookie {
public:
fz_cookie cookie;
FitzAbortCookie() { memset(&cookie, 0, sizeof(cookie)); }
void Abort() override { cookie.abort = 1; }
void* GetData() override { return (void*)&cookie; }
};
// copy of fz_is_external_link without ctx
static bool IsExternalLink(const char* uri) {
if (!uri) {
return false;
}
while (*uri >= 'a' && *uri <= 'z') {
++uri;
}
return uri[0] == ':';
}
static char* FzGetURL(fz_link* link, fz_outline* outline) {
if (link) {
return link->uri;
}
return outline->uri;
}
struct PageDestinationMupdf : IPageDestination {
fz_outline* outline = nullptr;
fz_link* link = nullptr;
char* value = nullptr;
char* name = nullptr;
// anchor (x, y) on the destination page resolved from the link URI;
// -1 means "not resolved" (e.g. external URL or file launch).
float destX = -1.f;
float destY = -1.f;
// /XYZ zoom level requested by the link (1.0 = 100%). 0 means
// "not specified" — caller should use document default.
float destZoom = 0.f;
PageDestinationMupdf(fz_link* l, fz_outline* o) {
// exactly one must be provided
kind = kindDestinationMupdf;
link = l;
outline = o;
}
RectF GetRect2() override {
if (outline) {
// needed for -named-dest called from LinkHandler::ScrollTo
RectF r{outline->x, outline->y, 0, 0};
return r;
}
return rect;
}
RectF GetDestPoint2() override {
if (outline) {
return RectF{outline->x, outline->y, 0, 0};
}
if (destY >= 0.f) {
return RectF{destX, destY, 0, 0};
}
return {};
}
float GetZoom2() override {
return destZoom;
}
~PageDestinationMupdf() override {
str::Free(value);
str::Free(name);
}
char* GetValue2() override;
char* GetName2() override;
};
char* PageDestinationMupdf ::GetValue2() {
if (value) {
return value;
}
char* uri = FzGetURL(link, outline);
if (uri && IsExternalLink(uri)) {
value = str::Dup(uri);
}
return value;
}
char* PageDestinationMupdf ::GetName2() {
if (name) {
return name;
}
if (outline && outline->title) {
name = str::Dup(outline->title);
}
return name;
}
static NO_INLINE RectF FzGetRectF(fz_link* link, fz_outline* outline) {
if (link) {
return ToRectF(link->rect);
}
return {};
}
static int ResolveLink(fz_context* ctx, fz_document* doc, const char* uri, float* xp, float* yp,
float* zoomp = nullptr) {
if (!uri) {
return -1;
}
int pageNo = -1;
fz_link_dest ldest{};
fz_var(ldest);
fz_var(pageNo);
fz_try(ctx) {
ldest = fz_resolve_link_dest(ctx, doc, uri);
pageNo = fz_page_number_from_location(ctx, doc, ldest.loc);
}
fz_catch(ctx) {
fz_warn(ctx, "fz_resolve_link_dest failed");
fz_report_error(ctx);
pageNo = -1;
}
if (pageNo < 0) {
return -1;
}
if (xp) {
*xp = isnan(ldest.x) ? 0.f : ldest.x;
}
if (yp) {
*yp = isnan(ldest.y) ? 0.f : ldest.y;
}
if (zoomp) {
float z = isnan(ldest.zoom) ? 0.f : ldest.zoom;
// mupdf reports zoom as percentage (100 = 100%); we use 1.0 as 100%.
*zoomp = z / 100.f;
}
return pageNo + 1;
}
static int FzGetPageNo(fz_context* ctx, fz_document* doc, fz_link* link, fz_outline* outline) {
float x, y;
const char* uri = link ? link->uri : outline ? outline->uri : nullptr;
int pageNo = ResolveLink(ctx, doc, uri, &x, &y);
return pageNo;
}
static IPageDestination* NewPageDestinationMupdf(fz_context* ctx, fz_document* doc, fz_link* link,
fz_outline* outline) {
ReportIf(link && outline);
ReportIf(!link && !outline);
char* uri = FzGetURL(link, outline);
const char* maybePath = (const char*)uri;
if (str::Skip(maybePath, "file:")) {
// decode: file:path%20to_file.pdf#page=1
// this is to handle file:// and
// file:/// (which I assume is a mistake in PDF)
str::Skip(maybePath, "/");
str::Skip(maybePath, "/");
str::Skip(maybePath, "/");
TempStr path = str::DupTemp(maybePath);
TempStr dest = str::FindChar(path, '#');
if (dest) {
*dest = 0;
dest++;
}
// mupdf url-encodes paths so we un-decode them
fz_urldecode(path);
fz_cleanname(path);
// mupdf does unix path, we want windows
path = str::ReplaceTemp(path, "/", "\\");
if (dest) {
fz_urldecode(dest);
}
logf("NewPageDestinationMupdf: path='%s', dest='%s'\n", path, dest);
auto res = new PageDestinationFile(path, dest);
res->rect = FzGetRectF(link, outline);
return res;
}
if (IsExternalUrl(uri)) {
auto res = new PageDestinationURL(uri);
res->rect = FzGetRectF(link, outline);
return res;
}
auto dest = new PageDestinationMupdf(link, outline);
dest->rect = FzGetRectF(link, outline);
{
float x = 0, y = 0, z = 0;
const char* destUri = link ? link->uri : (outline ? outline->uri : nullptr);
dest->pageNo = ResolveLink(ctx, doc, destUri, &x, &y, &z);
dest->destX = x;
dest->destY = y;
dest->destZoom = z;
}
return dest;
}
static PageElementDestination* NewLinkDestination(int srcPageNo, fz_context* ctx, fz_document* doc, fz_link* link,
fz_outline* outline) {
auto dest = NewPageDestinationMupdf(ctx, doc, link, outline);
auto res = new PageElementDestination(dest);
res->pageNo = srcPageNo;
res->rect = dest->rect;
return res;
}
struct LinkRectList {
StrVec links;
Vec<fz_rect> coords;
};
fz_rect ToFzRect(RectF rect) {
fz_rect result = {(float)rect.x, (float)rect.y, (float)(rect.x + rect.dx), (float)(rect.y + rect.dy)};
return result;
}
RectF ToRectF(fz_rect rect) {
return RectF::FromXY(rect.x0, rect.y0, rect.x1, rect.y1);
}
static bool IsPointInRect(fz_rect rect, fz_point pt) {
return ToRectF(rect).Contains(PointF(pt.x, pt.y));
}
fz_matrix FzCreateViewCtm(fz_rect mediabox, float zoom, int rotation) {
fz_matrix ctm = fz_pre_scale(fz_rotate((float)rotation), zoom, zoom);
// TODO: this is happening quite often so don't report it
// not sure if it indicates an actual issue
// ReportIf(0 != mediabox.x0 || 0 != mediabox.y0);
rotation = (rotation + 360) % 360;
if (90 == rotation) {
ctm = fz_pre_translate(ctm, 0, -mediabox.y1);
} else if (180 == rotation) {
ctm = fz_pre_translate(ctm, -mediabox.x1, -mediabox.y1);
} else if (270 == rotation) {
ctm = fz_pre_translate(ctm, -mediabox.x1, 0);
}
ReportIf(fz_matrix_expansion(ctm) <= 0);
if (fz_matrix_expansion(ctm) == 0) {
return fz_identity;
}
return ctm;
}
// TODO: maybe make dpi a float as well
static float DpiScale(float x, int dpi) {
ReportIf(dpi < 70.F);
// TODO: maybe implement step scaling like mupdf
float res = x * (float)dpi;
res = res / 96.F;
return res;
}
static float FzRectOverlap(fz_rect r1, fz_rect r2) {
if (fz_is_empty_rect(r1)) {
return 0.0F;
}
fz_rect isect = fz_intersect_rect(r1, r2);
return (isect.x1 - isect.x0) * (isect.y1 - isect.y0) / ((r1.x1 - r1.x0) * (r1.y1 - r1.y0));
}
static float FzRectOverlap(fz_rect r1, RectF r2f) {
if (fz_is_empty_rect(r1)) {
return 0.0F;
}
fz_rect r2 = ToFzRect(r2f);
fz_rect isect = fz_intersect_rect(r1, r2);
return (isect.x1 - isect.x0) * (isect.y1 - isect.y0) / ((r1.x1 - r1.x0) * (r1.y1 - r1.y0));
}
static TempWStr PdfToWStrTemp(fz_context* ctx, pdf_obj* obj) {
char* s = pdf_new_utf8_from_pdf_string_obj(ctx, obj);
WCHAR* res = ToWStrTemp(s);
fz_free(ctx, s);
return res;
}
static TempStr PdfToUtf8Temp(fz_context* ctx, pdf_obj* obj) {
char* s = pdf_new_utf8_from_pdf_string_obj(ctx, obj);
TempStr res = str::DupTemp(s);
fz_free(ctx, s);
return res;
}
// some PDF documents contain control characters in outline titles or /Info properties
// we replace them with spaces and cleanup for display with NormalizeWSInPlace()
static WCHAR* PdfCleanStringInPlace(WCHAR* s) {
if (!s) {
return nullptr;
}
WCHAR* curr = s;
while (*curr) {
WCHAR c = *curr;
if (c < 0x20) {
*curr = ' ';
} else if (c == 0xfffd) {
// https://github.com/sumatrapdfreader/sumatrapdf/issues/4965
// TODO: was there mupdf change that caused this?
*curr = 0;
break;
}
curr++;
}
str::NormalizeWSInPlace(s);
return s;
}
struct istream_filter {
IStream* stream;
u8 buf[4096];
};
extern "C" int next_istream(fz_context* ctx, fz_stream* stm, size_t) {
istream_filter* state = (istream_filter*)stm->state;
ULONG cbRead = sizeof(state->buf);
HRESULT res = state->stream->Read(state->buf, sizeof(state->buf), &cbRead);
if (FAILED(res)) {
fz_throw(ctx, FZ_ERROR_GENERIC, "IStream read error: %x", res);
}
stm->rp = state->buf;
stm->wp = stm->rp + cbRead;
stm->pos += cbRead;
return cbRead > 0 ? *stm->rp++ : EOF;
}
extern "C" void seek_istream(fz_context* ctx, fz_stream* stm, i64 offset, int whence) {
istream_filter* state = (istream_filter*)stm->state;
LARGE_INTEGER off;
ULARGE_INTEGER n;
off.QuadPart = offset;
HRESULT res = state->stream->Seek(off, whence, &n);
if (FAILED(res)) {
fz_throw(ctx, FZ_ERROR_GENERIC, "IStream seek error: %x", res);
}
if (n.HighPart != 0 || n.LowPart > INT_MAX) {
fz_throw(ctx, FZ_ERROR_GENERIC, "documents beyond 2GB aren't supported");
}
stm->pos = n.LowPart;
stm->rp = stm->wp = state->buf;
}
extern "C" void drop_istream(fz_context* ctx, void* state_) {
istream_filter* state = (istream_filter*)state_;
state->stream->Release();
fz_free(ctx, state);
}
static fz_stream* FzOpenIStream(fz_context* ctx, IStream* stream) {
if (!stream) {
return nullptr;
}
LARGE_INTEGER zero{};
HRESULT res = stream->Seek(zero, STREAM_SEEK_SET, nullptr);
if (FAILED(res)) {
fz_throw(ctx, FZ_ERROR_GENERIC, "IStream seek error: %x", res);
}
istream_filter* state = fz_malloc_struct(ctx, istream_filter);
state->stream = stream;
stream->AddRef();
fz_stream* stm = fz_new_stream(ctx, state, next_istream, drop_istream);
stm->seek = seek_istream;
return stm;
}
static void* FzMemdup(fz_context* ctx, void* p, size_t size) {
void* res = fz_malloc_no_throw(ctx, size);
if (!res) {
return nullptr;
}
memcpy(res, p, size);
return res;
}
static fz_stream* FzStreamFromData(fz_context* ctx, const u8* data, int size) {
fz_stream* stm = nullptr;
// TODO: we copy so that the memory ends up in chunk allocated
// by libmupdf so that it works across dll boundaries.
// We can either use fz_new_buffer_from_shared_data
// and free the data on the side or create Allocator that
// uses fz_malloc_no_throw and pass it to ReadFileWithAllocator
void* dataCopy = FzMemdup(ctx, (void*)data, size);
if (!dataCopy) {
return nullptr;
}
fz_buffer* buf = fz_new_buffer_from_data(ctx, (u8*)dataCopy, size);
fz_var(buf);
fz_try(ctx) {
stm = fz_open_buffer(ctx, buf);
}
fz_always(ctx) {
fz_drop_buffer(ctx, buf);
}
fz_catch(ctx) {
stm = nullptr;
fz_report_error(ctx);
}
return stm;
}
// maximum size of a file that's entirely loaded into memory before parsed
// and displayed; larger files will be kept open while they're displayed
// so that their content can be loaded on demand in order to preserve memory
constexpr i64 kMaxMemoryFileSize = 32 * 1024 * 1024;
static fz_stream* FzReadFileIfSmall(fz_context* ctx, const char* path) {
fz_stream* stm = nullptr;
i64 fileSize = file::GetSize(path);
// load small files entirely into memory so that they can be
// overwritten even by programs that don't open files with FILE_SHARE_READ
bool isSmallFile = fileSize > 0 && fileSize < kMaxMemoryFileSize;
if (!isSmallFile) {
return nullptr;
}
ByteSlice d = file::ReadFile(path);
if (d.empty()) {
// failed to read
return nullptr;
}
stm = FzStreamFromData(ctx, d.data(), d.Size());
d.Free();
return stm;
}
/*
https://github.com/sumatrapdfreader/sumatrapdf/issues/4514
Some PDF files have garbage at the beginning, before the %PDF- marker
Sometimes removing this garbage fixes the file for mupdf
*/
static fz_stream* FzReadMaybeFixPDF(fz_context* ctx, const char* path) {
fz_stream* stm;
// fast fail: read enough to check if this is PDF file with garbage
char buf[1024];
size_t bufSize = dimof(buf);
int n = file::ReadN(path, buf, bufSize);
if (n < 1024) {
return nullptr;
}
n = str::BufFind(buf, (int)bufSize, "%PDF-");
if (n <= 0) {
// not PDF or no garbage at the beginning
return nullptr;
}
ByteSlice d = file::ReadFile(path);
if (d.empty()) {
// failed to read
return nullptr;
}
// strip garbage
const u8* data = d.data() + n;
int size = d.Size() - n;
stm = FzStreamFromData(ctx, data, size);
d.Free();
return stm;
}
static fz_stream* FzOpenOrReadFile(fz_context* ctx, const char* path) {
fz_stream* stm = FzReadFileIfSmall(ctx, path);
if (stm) {
return stm;
}
WCHAR* pathW = ToWStrTemp(path);
fz_try(ctx) {
stm = fz_open_file_w(ctx, pathW);
}
fz_catch(ctx) {
stm = nullptr;
fz_report_error(ctx);
}
return stm;
}
static void FzStreamFingerprint(fz_context* ctx, fz_stream* stm, u8 digest[16]) {
i64 fileLen = -1;
fz_buffer* buf = nullptr;
fz_try(ctx) {
fz_seek(ctx, stm, 0, 2);
fileLen = fz_tell(ctx, stm);
fz_seek(ctx, stm, 0, 0);
buf = fz_read_all(ctx, stm, fileLen);
}
fz_catch(ctx) {
fz_warn(ctx, "couldn't read stream data, using a nullptr fingerprint instead");
ZeroMemory(digest, 16);
fz_report_error(ctx);
return;
}
ReportIf(nullptr == buf);
u8* data;
size_t size = fz_buffer_extract(ctx, buf, &data);
ReportIf((size_t)fileLen != size);
fz_drop_buffer(ctx, buf);
fz_md5 md5;
fz_md5_init(&md5);
fz_md5_update(&md5, data, size);
fz_md5_final(&md5, digest);
}
static ByteSlice FzExtractStreamData(fz_context* ctx, fz_stream* stream) {
fz_seek(ctx, stream, 0, 2);
i64 fileLen = fz_tell(ctx, stream);
fz_seek(ctx, stream, 0, 0);
fz_buffer* buf = fz_read_all(ctx, stream, fileLen);
u8* data = nullptr;
size_t size = fz_buffer_extract(ctx, buf, &data);
ReportIf((size_t)fileLen != size);
fz_drop_buffer(ctx, buf);
if (!data || size == 0) {
return {};
}
// this was allocated inside mupdf, make a copy that can be free()d
u8* res = (u8*)memdup(data, size);
fz_free(ctx, data);
return {res, size};
}
static inline int WcharsPerRune(int rune) {
if (rune & 0x1F0000) {
return 2;
}
return 1;
}
static void AddChar(fz_stext_line* line, fz_stext_char* c, WStrBuilder& s, Vec<Rect>& rects) {
fz_rect bbox = fz_rect_from_quad(c->quad);
Rect r = ToRectF(bbox).Round();
int n = WcharsPerRune(c->c);
if (n == 2) {
WCHAR tmp[2];
tmp[0] = 0xD800 | ((c->c - 0x10000) >> 10) & 0x3FF;
tmp[1] = 0xDC00 | (c->c - 0x10000) & 0x3FF;
s.Append(tmp, 2);
rects.Append(r);
rects.Append(r);
return;
}
WCHAR wc = c->c;
bool isNonPrintable = (wc <= 32) || str::IsNonCharacter(wc);
if (!isNonPrintable) {
s.AppendChar(wc);
rects.Append(r);
return;
}
// non-printable or whitespace
if (!str::IsWs(wc)) {
s.AppendChar(L'?');
rects.Append(r);
return;
}
// collapse multiple whitespace characters into one
WCHAR prev = s.LastChar();
if (!str::IsWs(prev)) {
s.AppendChar(L' ');
rects.Append(r);
}
}
static void AddLineSep(WStrBuilder& s, Vec<Rect>& rects, const WCHAR* lineSep, size_t lineSepLen) {
if (lineSepLen == 0) {
return;
}
// remove trailing spaces
if (str::IsWs(s.LastChar())) {
s.RemoveLast();
rects.RemoveLast();
}
s.Append(lineSep);
for (size_t i = 0; i < lineSepLen; i++) {
rects.Append(Rect());
}
}
// UTF-8 variant: append `c` as up to 4 UTF-8 bytes to `s` and the same
// rect `r` for each byte, so rects.size() == s.size() holds.
static void AddCharUtf8(fz_stext_line*, fz_stext_char* c, StrBuilder& s, Vec<Rect>& rects) {
fz_rect bbox = fz_rect_from_quad(c->quad);
Rect r = ToRectF(bbox).Round();
int rune = c->c;
bool isWhitespace = rune > 0 && rune <= 0x7f && str::IsWs((WCHAR)rune);
bool isNonPrintable = rune <= 32 || str::IsNonCharacter((WCHAR)rune);
if (isNonPrintable && !isWhitespace) {
s.AppendChar('?');
rects.Append(r);
return;
}
if (isWhitespace) {
// collapse multiple whitespace characters into one
char prev = s.IsEmpty() ? 0 : s.LastChar();
if (prev == ' ' || prev == '\t' || prev == '\n' || prev == '\r') {
return;
}
s.AppendChar(' ');
rects.Append(r);
return;
}
char buf[4];
int n = fz_runetochar(buf, rune);
s.Append(buf, (size_t)n);
for (int i = 0; i < n; i++) {
rects.Append(r);
}
}
static void AddLineSepUtf8(StrBuilder& s, Vec<Rect>& rects, const char* lineSep) {
size_t lineSepLen = str::Len(lineSep);
if (lineSepLen == 0) {
return;
}
// remove trailing space
if (!s.IsEmpty() && s.LastChar() == ' ') {
s.RemoveLast();
rects.RemoveLast();
}
s.Append(lineSep);
for (size_t i = 0; i < lineSepLen; i++) {
rects.Append(Rect());
}
}
static char* FzTextPageToUtf8(fz_stext_page* text, Rect** coordsOut) {
const char* lineSep = "\n";
StrBuilder content;
Vec<Rect> rects;
fz_stext_block* block = text->first_block;
while (block) {
if (block->type != FZ_STEXT_BLOCK_TEXT) {
block = block->next;
continue;
}
fz_stext_line* line = block->u.t.first_line;
while (line) {
fz_stext_char* c = line->first_char;
while (c) {
AddCharUtf8(line, c, content, rects);
c = c->next;
}
AddLineSepUtf8(content, rects, lineSep);
line = line->next;
}
block = block->next;
}
ReportIf(content.size() != rects.size());
if (coordsOut) {
*coordsOut = rects.StealData();
}
return content.StealData();
}
static WCHAR* FzTextPageToStr(fz_stext_page* text, Rect** coordsOut) {
const WCHAR* lineSep = L"\n";
size_t lineSepLen = str::Len(lineSep);
WStrBuilder content;
// coordsOut is optional but we ask for it by default so we simplify the code
// by always calculating it
Vec<Rect> rects;
fz_stext_block* block = text->first_block;
while (block) {
if (block->type != FZ_STEXT_BLOCK_TEXT) {
block = block->next;
continue;
}
fz_stext_line* line = block->u.t.first_line;
while (line) {
fz_stext_char* c = line->first_char;
while (c) {
AddChar(line, c, content, rects);
c = c->next;
}
AddLineSep(content, rects, lineSep, lineSepLen);
line = line->next;
}
block = block->next;
}
ReportIf(content.size() != rects.size());
if (coordsOut) {
*coordsOut = rects.StealData();
}
return content.StealData();
}
static fz_stext_options NewTextPageOptions(int flags = 0) {
fz_stext_options opts{};
// Use glyph outline bounds so text selection rectangles match visible text
// instead of the looser line-height boxes from default MuPDF extraction.
opts.flags = flags | FZ_STEXT_ACCURATE_BBOXES;
return opts;
}
static bool LinkifyCheckMultiline(const WCHAR* pageText, const WCHAR* pos, Rect* coords) {
// multiline links end in a non-alphanumeric character and continue on a line
// that starts left and only slightly below where the current line ended
// (and that doesn't start with http or a footnote numeral)
return '\n' == *pos && pos > pageText && *(pos + 1) && !iswalnum(pos[-1]) && !str::IsWs(pos[1]) &&
coords[pos - pageText + 1].BR().y > coords[pos - pageText - 1].y &&
coords[pos - pageText + 1].y <= coords[pos - pageText - 1].BR().y + coords[pos - pageText - 1].dy * 0.35 &&
coords[pos - pageText + 1].x < coords[pos - pageText - 1].BR().x &&
coords[pos - pageText + 1].dy >= coords[pos - pageText - 1].dy * 0.85 &&
coords[pos - pageText + 1].dy <= coords[pos - pageText - 1].dy * 1.2 && !str::StartsWith(pos + 1, L"http");
}
static bool EndsURL(WCHAR c) {
if (c == 0 || str::IsWs(c)) {
return true;
}
// https://github.com/sumatrapdfreader/sumatrapdf/issues/1313
// 0xff0c is ","
if (c == (WCHAR)0xff0c) {
return true;
}
return false;
}
static const WCHAR* LinkifyFindEnd(const WCHAR* start, WCHAR prevChar) {
const WCHAR* quote = nullptr;
// look for the end of the URL (ends in a space preceded maybe by interpunctuation)
const WCHAR* end = start;
while (!EndsURL(*end)) {
end++;
}
char prev = 0;
if (end > start) {
prev = end[-1];
}
if (',' == prev || '.' == prev || '?' == prev || '!' == prev) {
end--;
}
prev = 0;
if (end > start) {
prev = end[-1];
}
// also ignore a closing parenthesis, if the URL doesn't contain any opening one
if (')' == prev && (!str::FindChar(start, '(') || str::FindChar(start, '(') >= end)) {
end--;
}
// cut the link at the first quotation mark, if it's also preceded by one
if (('"' == prevChar || '\'' == prevChar) && (quote = str::FindChar(start, prevChar)) != nullptr && quote < end) {
end = quote;
}
return end;
}
static const WCHAR* LinkifyMultilineText(LinkRectList* list, const WCHAR* pageText, const WCHAR* start,
const WCHAR* next, Rect* coords) {
int lastIx = list->coords.Size() - 1;
char* uri = list->links.At(lastIx);
const WCHAR* end = next;
bool multiline = false;
do {
end = LinkifyFindEnd(next, start > pageText ? start[-1] : ' ');
multiline = LinkifyCheckMultiline(pageText, end, coords);
char* part = ToUtf8Temp(next, end - next);
uri = str::JoinTemp(uri, part);
Rect bbox = coords[next - pageText].Union(coords[end - pageText - 1]);
list->coords.Append(ToFzRect(ToRectF(bbox)));
next = end + 1;
} while (multiline);
// update the link URL for all partial links
list->links.SetAt(lastIx, uri);
for (int i = lastIx + 1; i < list->coords.Size(); i++) {
list->links.Append(uri);
}
return end;
}
// cf. http://weblogs.mozillazine.org/gerv/archives/2011/05/html5_email_address_regexp.html
inline bool IsEmailUsernameChar(WCHAR c) {
// explicitly excluding the '/' from the list, as it is more
// often part of a URL or path than of an email address
return iswalnum(c) || c && str::FindChar(L".!#$%&'*+=?^_`{|}~-", c);
}
inline bool IsEmailDomainChar(WCHAR c) {
return iswalnum(c) || '-' == c;
}
static const WCHAR* LinkifyFindEmail(const WCHAR* pageText, const WCHAR* at) {
const WCHAR* start;
for (start = at; start > pageText && IsEmailUsernameChar(*(start - 1)); start--) {
// do nothing
}
return start != at ? start : nullptr;
}
static const WCHAR* LinkifyEmailAddress(const WCHAR* start) {
const WCHAR* end;
for (end = start; IsEmailUsernameChar(*end); end++) {
;
}
if (end == start || *end != '@' || !IsEmailDomainChar(*(end + 1))) {
return nullptr;
}
for (end++; IsEmailDomainChar(*end); end++) {
;
}
if ('.' != *end || !IsEmailDomainChar(*(end + 1))) {
return nullptr;
}
do {
for (end++; IsEmailDomainChar(*end); end++) {
;
}
} while ('.' == *end && IsEmailDomainChar(*(end + 1)));
return end;
}
// caller needs to delete the result
// TODO: return Vec<IPageElement*> directly
static LinkRectList* LinkifyText(const WCHAR* pageText, Rect* coords) {
LinkRectList* list = new LinkRectList;
for (const WCHAR* start = pageText; *start; start++) {
const WCHAR* end = nullptr;
bool multiline = false;
const WCHAR* protocol = nullptr;
if ('@' == *start) {
// potential email address without mailto:
const WCHAR* email = LinkifyFindEmail(pageText, start);
end = email ? LinkifyEmailAddress(email) : nullptr;
protocol = L"mailto:";
if (end != nullptr) {
start = email;
}
} else if (start > pageText && ('/' == start[-1] || iswalnum(start[-1]))) {
// hyperlinks must not be preceded by a slash (indicates a different protocol)
// or an alphanumeric character (indicates part of a different protocol)
} else if ('h' == *start && str::Parse(start, L"http%?s://")) {
end = LinkifyFindEnd(start, start > pageText ? start[-1] : ' ');
multiline = LinkifyCheckMultiline(pageText, end, coords);
} else if ('w' == *start && str::StartsWith(start, L"www.")) {
end = LinkifyFindEnd(start, start > pageText ? start[-1] : ' ');
multiline = LinkifyCheckMultiline(pageText, end, coords);
protocol = L"http://";
// ignore www. links without a top-level domain
if (end - start <= 4 || !multiline && (!wcschr(start + 5, '.') || wcschr(start + 5, '.') >= end)) {
end = nullptr;
}
} else if ('m' == *start && str::StartsWith(start, L"mailto:")) {
end = LinkifyEmailAddress(start + 7);
}
if (!end) {
continue;
}
char* part = ToUtf8Temp(start, end - start);
char* uri = part;
if (protocol) {
char* proto = ToUtf8Temp(protocol);
uri = str::JoinTemp(proto, part);
}
list->links.Append(uri);
Rect bbox = coords[start - pageText].Union(coords[end - pageText - 1]);
list->coords.Append(ToFzRect(ToRectF(bbox)));
if (multiline) {
end = LinkifyMultilineText(list, pageText, start, end + 1, coords);
}
start = end;
}
return list;
}
// try to produce an 8-bit palette for saving some memory
static RenderedBitmap* TryRenderAsPaletteImage(fz_pixmap* pixmap) {
int w = pixmap->w;
int h = pixmap->h;
int stride = ((w + 3) / 4) * 4;
size_t sz = sizeof(BITMAPINFO) + (255 * sizeof(RGBQUAD));
ScopedMem<BITMAPINFO> bmi((BITMAPINFO*)calloc(1, sz));
if (!bmi.Get()) {
return nullptr;
}
BITMAPINFOHEADER* bmih = &bmi.Get()->bmiHeader;
bmih->biSize = sizeof(*bmih);
bmih->biWidth = w;
bmih->biHeight = -h;
bmih->biPlanes = 1;
bmih->biCompression = BI_RGB;
bmih->biBitCount = 8;
bmih->biSizeImage = h * stride;
bmih->biClrUsed = 256;
void* data = nullptr;
HANDLE hMap = CreateFileMapping(INVALID_HANDLE_VALUE, nullptr, PAGE_READWRITE, 0, bmih->biSizeImage, nullptr);
HBITMAP hbmp = CreateDIBSection(nullptr, bmi, DIB_RGB_COLORS, &data, hMap, 0);
if (!hbmp) {
if (hMap) {