forked from sumatrapdfreader/sumatrapdf
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathEngineEbook.cpp
1787 lines (1527 loc) · 51.9 KB
/
EngineEbook.cpp
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 2021 the SumatraPDF project authors (see AUTHORS file).
License: GPLv3 */
// engines which render flowed ebook formats into fixed pages through the EngineBase API
// (pages are mostly layed out the same as for a "B Format" paperback: 5.12" x 7.8")
#include "utils/BaseUtil.h"
#include "utils/ScopedWin.h"
#include "utils/Archive.h"
#include "utils/Dpi.h"
#include "utils/FileUtil.h"
#include "utils/GdiPlusUtil.h"
#include "utils/HtmlParserLookup.h"
#include "utils/HtmlPullParser.h"
#include "mui/Mui.h"
#include "utils/TrivialHtmlParser.h"
#include "utils/WinUtil.h"
#include "utils/ZipUtil.h"
#include "wingui/TreeModel.h"
#include "DisplayMode.h"
#include "Controller.h"
#include "FzImgReader.h"
#include "EngineBase.h"
#include "EngineAll.h"
#include "EbookBase.h"
#include "PalmDbReader.h"
#include "EbookDoc.h"
#include "HtmlFormatter.h"
#include "EbookFormatter.h"
Kind kindEngineEpub = "engineEpub";
Kind kindEngineFb2 = "engineFb2";
Kind kindEngineMobi = "engineMobi";
Kind kindEnginePdb = "enginePdb";
Kind kindEngineChm = "engineChm";
Kind kindEngineHtml = "engineHtml";
Kind kindEngineTxt = "engineTxt";
static AutoFreeWstr gDefaultFontName;
static float gDefaultFontSize = 10.f;
static const WCHAR* GetDefaultFontName() {
return gDefaultFontName.Get() ? gDefaultFontName.Get() : L"Georgia";
}
static float GetDefaultFontSize() {
// fonts are scaled at higher DPI settings,
// undo this here for (mostly) consistent results
return gDefaultFontSize * 96.0f / (float)DpiGetForHwnd(HWND_DESKTOP);
}
void SetDefaultEbookFont(const WCHAR* name, float size) {
// intentionally don't validate the input
if (str::Eq(name, L"default")) {
// "default" is used for mupdf engine to indicate
// we should use the font as given in css
name = L"Georgia";
}
gDefaultFontName.SetCopy(name);
// use a somewhat smaller size than in the EbookUI, since fit page/width
// is likely to be above 100% for the paperback page dimensions
gDefaultFontSize = size * 0.8f;
}
/* common classes for EPUB, FictionBook2, Mobi, PalmDOC, CHM, HTML and TXT engines */
struct PageAnchor {
DrawInstr* instr;
int pageNo;
explicit PageAnchor(DrawInstr* instr = nullptr, int pageNo = -1) : instr(instr), pageNo(pageNo) {
}
};
class EbookAbortCookie : public AbortCookie {
public:
bool abort{false};
EbookAbortCookie() {
}
void Abort() override {
abort = true;
}
};
class EngineEbook : public EngineBase {
public:
EngineEbook();
~EngineEbook() override;
RectF PageMediabox(int pageNo) override;
RectF PageContentBox(int pageNo, RenderTarget target = RenderTarget::View) override;
RenderedBitmap* RenderPage(RenderPageArgs& args) override;
RectF Transform(const RectF& rect, int pageNo, float zoom, int rotation, bool inverse = false) override;
ByteSlice GetFileData() override;
bool SaveFileAs(const char* copyFileName) override;
PageText ExtractPageText(int pageNo) override;
// make RenderCache request larger tiles than per default
bool HasClipOptimizations(int pageNo) override;
Vec<IPageElement*> GetElements(int pageNo) override;
IPageElement* GetElementAtPos(int pageNo, PointF pt) override;
bool HandleLink(IPageDestination* dest, ILinkHandler* linkHandler) override {
ReportIf(!dest || !linkHandler);
if (!dest || !linkHandler) {
return false;
}
linkHandler->GotoLink(dest);
return true;
}
IPageDestination* GetNamedDest(const WCHAR* name) override;
RenderedBitmap* GetImageForPageElement(IPageElement* el) override;
bool BenchLoadPage(int pageNo) override;
protected:
Vec<HtmlPage*>* pages = nullptr;
Vec<PageAnchor> anchors;
// contains for each page the last anchor indicating
// a break between two merged documents
Vec<DrawInstr*> baseAnchors;
// needed so that memory allocated by ResolveHtmlEntities isn't leaked
PoolAllocator allocator;
// TODO: still needed?
CRITICAL_SECTION pagesAccess;
// page dimensions can vary between filetypes
RectF pageRect;
float pageBorder;
void GetTransform(Matrix& m, float zoom, int rotation);
bool ExtractPageAnchors();
WCHAR* ExtractFontList();
virtual IPageElement* CreatePageLink(DrawInstr* link, Rect rect, int pageNo);
Vec<DrawInstr>* GetHtmlPage(int pageNo);
};
static IPageElement* NewEbookLink(DrawInstr* link, Rect rect, IPageDestination* dest, int pageNo = 0,
bool showUrl = false) {
if (!dest) {
// TODO: this doesn't make sense
dest = new PageDestination();
dest->kind = kindDestinationLaunchURL;
// TODO: not sure about this
// dest->value = str::Dup(res->value);
dest->rect = ToRectF(rect);
}
auto res = new PageElementDestination(dest);
res->pageNo = pageNo;
res->rect = ToRectF(rect);
#if 0 // TODO: figure out
if (showUrl) {
res->value = strconv::FromHtmlUtf8(link->str.s, link->str.len);
}
#endif
return res;
}
static IPageElement* NewImageDataElement(int pageNo, Rect bbox, int imageID) {
auto res = new PageElementImage();
res->pageNo = pageNo;
res->rect = ToRectF(bbox);
res->imageID = imageID;
return res;
}
static TocItem* newEbookTocItem(TocItem* parent, const WCHAR* title, IPageDestination* dest) {
auto res = new TocItem(parent, title, 0);
res->dest = dest;
if (dest) {
res->pageNo = dest->GetPageNo();
}
return res;
}
EngineEbook::EngineEbook() {
pageCount = 0;
// "B Format" paperback
pageRect = RectF(0, 0, 5.12f * GetFileDPI(), 7.8f * GetFileDPI());
pageBorder = 0.4f * GetFileDPI();
preferredLayout = preferredLayout = PageLayout(PageLayout::Type::Single);
InitializeCriticalSection(&pagesAccess);
}
EngineEbook::~EngineEbook() {
EnterCriticalSection(&pagesAccess);
if (pages) {
DeleteVecMembers(*pages);
}
delete pages;
LeaveCriticalSection(&pagesAccess);
DeleteCriticalSection(&pagesAccess);
}
RectF EngineEbook::PageMediabox(__unused int pageNo) {
return pageRect;
}
RectF EngineEbook::PageContentBox(int pageNo, __unused RenderTarget target) {
RectF mbox = PageMediabox(pageNo);
mbox.Inflate(-pageBorder, -pageBorder);
return mbox;
}
ByteSlice EngineEbook::GetFileData() {
const WCHAR* fileName = FileName();
if (!fileName) {
return {};
}
return file::ReadFile(fileName);
}
bool EngineEbook::SaveFileAs(const char* dstPath) {
const WCHAR* srcPath = FileName();
if (!srcPath) {
return false;
}
auto dstPathW = ToWstrTemp(dstPath);
auto res = file::Copy(dstPathW, srcPath, FALSE);
return res != 0;
}
// make RenderCache request larger tiles than per default
bool EngineEbook::HasClipOptimizations(__unused int pageNo) {
return false;
}
bool EngineEbook::BenchLoadPage(__unused int pageNo) {
return true;
}
void EngineEbook::GetTransform(Matrix& m, float zoom, int rotation) {
GetBaseTransform(m, ToGdipRectF(pageRect), zoom, rotation);
}
Vec<DrawInstr>* EngineEbook::GetHtmlPage(int pageNo) {
CrashIf(pageNo < 1 || PageCount() < pageNo);
if (pageNo < 1 || PageCount() < pageNo) {
return nullptr;
}
return &pages->at(pageNo - 1)->instructions;
}
bool EngineEbook::ExtractPageAnchors() {
ScopedCritSec scope(&pagesAccess);
DrawInstr* baseAnchor = nullptr;
for (int pageNo = 1; pageNo <= pageCount; pageNo++) {
Vec<DrawInstr>* pageInstrs = GetHtmlPage(pageNo);
if (!pageInstrs) {
return false;
}
for (size_t k = 0; k < pageInstrs->size(); k++) {
DrawInstr* i = &pageInstrs->at(k);
if (DrawInstrType::Anchor != i->type) {
continue;
}
anchors.Append(PageAnchor(i, pageNo));
if (k < 2 && str::StartsWith(i->str.s + i->str.len, "\" page_marker />")) {
baseAnchor = i;
}
}
baseAnchors.Append(baseAnchor);
}
CrashIf(baseAnchors.size() != pages->size());
return true;
}
RectF EngineEbook::Transform(const RectF& rect, __unused int pageNo, float zoom, int rotation, bool inverse) {
RectF rcF = rect; // TODO: un-needed conversion
auto p1 = Gdiplus::PointF(rcF.x, rcF.y);
auto p2 = Gdiplus::PointF(rcF.x + rcF.dx, rcF.y + rcF.dy);
Gdiplus::PointF pts[2] = {p1, p2};
Matrix m;
GetTransform(m, zoom, rotation);
if (inverse) {
m.Invert();
}
m.TransformPoints(pts, 2);
return RectF::FromXY(pts[0].X, pts[0].Y, pts[1].X, pts[1].Y);
}
RenderedBitmap* EngineEbook::RenderPage(RenderPageArgs& args) {
auto pageNo = args.pageNo;
auto zoom = args.zoom;
auto rotation = args.rotation;
auto pageRect = args.pageRect;
RectF pageRc = pageRect ? *pageRect : PageMediabox(pageNo);
Rect screen = Transform(pageRc, pageNo, zoom, rotation).Round();
Point screenTL = screen.TL();
screen.Offset(-screen.x, -screen.y);
HANDLE hMap = nullptr;
HBITMAP hbmp = CreateMemoryBitmap(screen.Size(), &hMap);
HDC hDC = CreateCompatibleDC(nullptr);
DeleteObject(SelectObject(hDC, hbmp));
Graphics g(hDC);
mui::InitGraphicsMode(&g);
Color white(0xFF, 0xFF, 0xFF);
SolidBrush tmpBrush(white);
Gdiplus::Rect screenR(ToGdipRect(screen));
screenR.Inflate(1, 1);
g.FillRectangle(&tmpBrush, screenR);
Matrix m;
GetTransform(m, zoom, rotation);
m.Translate((float)-screenTL.x, (float)-screenTL.y, MatrixOrderAppend);
g.SetTransform(&m);
EbookAbortCookie* cookie = nullptr;
if (args.cookie_out) {
cookie = new EbookAbortCookie();
*args.cookie_out = cookie;
}
ScopedCritSec scope(&pagesAccess);
mui::ITextRender* textDraw = mui::TextRenderGdiplus::Create(&g);
DrawHtmlPage(&g, textDraw, GetHtmlPage(pageNo), pageBorder, pageBorder, false, Color((ARGB)Color::Black),
cookie ? &cookie->abort : nullptr);
delete textDraw;
DeleteDC(hDC);
if (cookie && cookie->abort) {
DeleteObject(hbmp);
CloseHandle(hMap);
return nullptr;
}
return new RenderedBitmap(hbmp, screen.Size(), hMap);
}
static Rect GetInstrBbox(DrawInstr& instr, float pageBorder) {
RectF bbox(instr.bbox.x, instr.bbox.y, instr.bbox.dx, instr.bbox.dy);
bbox.Offset(pageBorder, pageBorder);
return bbox.Round();
}
PageText EngineEbook::ExtractPageText(int pageNo) {
const WCHAR* lineSep = L"\n";
ScopedCritSec scope(&pagesAccess);
gAllowAllocFailure++;
defer {
gAllowAllocFailure--;
};
str::WStr content;
Vec<Rect> coords;
bool insertSpace = false;
Vec<DrawInstr>* pageInstrs = GetHtmlPage(pageNo);
for (DrawInstr& i : *pageInstrs) {
Rect bbox = GetInstrBbox(i, pageBorder);
switch (i.type) {
case DrawInstrType::String:
if (coords.size() > 0 &&
(bbox.x < coords.Last().BR().x || bbox.y > coords.Last().y + coords.Last().dy * 0.8)) {
content.Append(lineSep);
coords.AppendBlanks(str::Len(lineSep));
CrashIf(*lineSep && !coords.Last().IsEmpty());
} else if (insertSpace && coords.size() > 0) {
int swidth = bbox.x - coords.Last().BR().x;
if (swidth > 0) {
content.Append(' ');
coords.Append(Rect(bbox.x - swidth, bbox.y, swidth, bbox.dy));
}
}
insertSpace = false;
{
AutoFreeWstr s(strconv::FromHtmlUtf8(i.str.s, i.str.len));
content.Append(s);
size_t len = str::Len(s);
double cwidth = 1.0 * bbox.dx / len;
for (size_t k = 0; k < len; k++) {
coords.Append(Rect((int)(bbox.x + k * cwidth), bbox.y, (int)cwidth, bbox.dy));
}
}
break;
case DrawInstrType::RtlString:
if (coords.size() > 0 &&
(bbox.BR().x > coords.Last().x || bbox.y > coords.Last().y + coords.Last().dy * 0.8)) {
content.Append(lineSep);
coords.AppendBlanks(str::Len(lineSep));
CrashIf(*lineSep && !coords.Last().IsEmpty());
} else if (insertSpace && coords.size() > 0) {
int swidth = coords.Last().x - bbox.BR().x;
if (swidth > 0) {
content.Append(' ');
coords.Append(Rect(bbox.BR().x, bbox.y, swidth, bbox.dy));
}
}
insertSpace = false;
{
AutoFreeWstr s(strconv::FromHtmlUtf8(i.str.s, i.str.len));
content.Append(s);
size_t len = str::Len(s);
double cwidth = 1.0 * bbox.dx / len;
for (size_t k = 0; k < len; k++) {
coords.Append(Rect((int)(bbox.x + (len - k - 1) * cwidth), bbox.y, (int)cwidth, bbox.dy));
}
}
break;
case DrawInstrType::ElasticSpace:
case DrawInstrType::FixedSpace:
insertSpace = true;
break;
}
}
if (content.size() > 0 && !str::EndsWith(content.Get(), lineSep)) {
content.Append(lineSep);
coords.AppendBlanks(str::Len(lineSep));
}
CrashIf(coords.size() != content.size());
PageText res;
res.len = (int)content.size();
res.text = content.StealData();
res.coords = coords.StealData();
return res;
}
IPageElement* EngineEbook::CreatePageLink(DrawInstr* link, Rect rect, int pageNo) {
AutoFreeWstr url(strconv::FromHtmlUtf8(link->str.s, link->str.len));
if (url::IsAbsolute(url)) {
return NewEbookLink(link, rect, nullptr, pageNo);
}
DrawInstr* baseAnchor = baseAnchors.at(pageNo - 1);
if (baseAnchor) {
AutoFree basePath(str::Dup(baseAnchor->str.s, baseAnchor->str.len));
AutoFree relPath(ResolveHtmlEntities(link->str.s, link->str.len));
AutoFree absPath(NormalizeURL(relPath, basePath));
url.Set(strconv::Utf8ToWstr(absPath.Get()));
}
IPageDestination* dest = GetNamedDest(url);
if (!dest) {
return nullptr;
}
return NewEbookLink(link, rect, dest, pageNo);
}
Vec<IPageElement*> EngineEbook::GetElements(int pageNo) {
Vec<IPageElement*> els;
Vec<DrawInstr>* pageInstrs = GetHtmlPage(pageNo);
size_t n = pageInstrs->size();
for (size_t idx = 0; idx < n; idx++) {
DrawInstr& i = pageInstrs->at(idx);
if (DrawInstrType::Image == i.type) {
auto box = GetInstrBbox(i, pageBorder);
auto el = NewImageDataElement(pageNo, box, (int)idx);
els.Append(el);
} else if (DrawInstrType::LinkStart == i.type && !i.bbox.IsEmpty()) {
IPageElement* link = CreatePageLink(&i, GetInstrBbox(i, pageBorder), pageNo);
if (link) {
els.Append(link);
}
}
}
return els;
}
static RenderedBitmap* getImageFromData(ByteSlice imageData) {
HBITMAP hbmp{nullptr};
Bitmap* bmp = BitmapFromData(imageData);
if (!bmp || bmp->GetHBITMAP((ARGB)Color::White, &hbmp) != Ok) {
delete bmp;
return nullptr;
}
Size size(bmp->GetWidth(), bmp->GetHeight());
delete bmp;
return new RenderedBitmap(hbmp, size);
}
RenderedBitmap* EngineEbook::GetImageForPageElement(IPageElement* iel) {
CrashIf(iel->GetKind() != kindPageElementImage);
PageElementImage* el = (PageElementImage*)iel;
int pageNo = el->pageNo;
int idx = el->imageID;
Vec<DrawInstr>* pageInstrs = GetHtmlPage(pageNo);
auto&& i = pageInstrs->at(idx);
CrashIf(i.type != DrawInstrType::Image);
return getImageFromData(i.GetImage());
}
// don't delete the result
IPageElement* EngineEbook::GetElementAtPos(int pageNo, PointF pt) {
auto els = GetElements(pageNo);
for (auto& el : els) {
if (el->GetRect().Contains(pt)) {
return el;
}
}
return nullptr;
}
IPageDestination* EngineEbook::GetNamedDest(const WCHAR* name) {
auto nameA(ToUtf8Temp(name));
const char* id = nameA.Get();
if (str::FindChar(id, '#')) {
id = str::FindChar(id, '#') + 1;
}
// if the name consists of both path and ID,
// try to first skip to the page with the desired
// path before looking for the ID to allow
// for the same ID to be reused on different pages
DrawInstr* baseAnchor = nullptr;
int basePageNo = 0;
if (id > nameA.Get() + 1) {
size_t base_len = id - nameA.Get() - 1;
for (size_t i = 0; i < baseAnchors.size(); i++) {
DrawInstr* anchor = baseAnchors.at(i);
if (anchor && base_len == anchor->str.len && str::EqNI(nameA.Get(), anchor->str.s, base_len)) {
baseAnchor = anchor;
basePageNo = (int)i + 1;
break;
}
}
}
size_t id_len = str::Len(id);
for (size_t i = 0; i < anchors.size(); i++) {
PageAnchor* anchor = &anchors.at(i);
if (baseAnchor) {
if (anchor->instr == baseAnchor) {
baseAnchor = nullptr;
}
continue;
}
// note: at least CHM treats URLs as case-independent
if (id_len == anchor->instr->str.len && str::EqNI(id, anchor->instr->str.s, id_len)) {
RectF rect(0, anchor->instr->bbox.y + pageBorder, pageRect.dx, 10);
rect.Inflate(-pageBorder, 0);
return NewSimpleDest(anchor->pageNo, rect);
}
}
// don't fail if an ID doesn't exist in a merged document
if (basePageNo != 0) {
RectF rect(0, pageBorder, pageRect.dx, 10);
rect.Inflate(-pageBorder, 0);
return NewSimpleDest(basePageNo, rect);
}
return nullptr;
}
WCHAR* EngineEbook::ExtractFontList() {
ScopedCritSec scope(&pagesAccess);
Vec<mui::CachedFont*> seenFonts;
WStrVec fonts;
for (int pageNo = 1; pageNo <= PageCount(); pageNo++) {
Vec<DrawInstr>* pageInstrs = GetHtmlPage(pageNo);
if (!pageInstrs) {
continue;
}
for (DrawInstr& i : *pageInstrs) {
if (DrawInstrType::SetFont != i.type || seenFonts.Contains(i.font)) {
continue;
}
seenFonts.Append(i.font);
FontFamily family;
if (!i.font->font) {
// TODO: handle gdi
CrashIf(!i.font->GetHFont());
continue;
}
Status ok = i.font->font->GetFamily(&family);
if (ok != Ok) {
continue;
}
WCHAR fontName[LF_FACESIZE];
ok = family.GetFamilyName(fontName);
if (ok != Ok || fonts.FindI(fontName) != -1) {
continue;
}
fonts.Append(str::Dup(fontName));
}
}
if (fonts.size() == 0) {
return nullptr;
}
fonts.SortNatural();
return fonts.Join(L"\n");
}
static void AppendTocItem(TocItem*& root, TocItem* item, int level) {
if (!root) {
root = item;
return;
}
// find the last child at each level, until finding the parent of the new item
TocItem* r2 = root;
while (--level > 0) {
for (; r2->next; r2 = r2->next) {
;
}
if (r2->child) {
r2 = r2->child;
} else {
r2->child = item;
return;
}
}
r2->AddSiblingAtEnd(item);
}
class EbookTocBuilder : public EbookTocVisitor {
EngineBase* engine = nullptr;
TocItem* root = nullptr;
int idCounter = 0;
bool isIndex = false;
public:
explicit EbookTocBuilder(EngineBase* engine) {
this->engine = engine;
}
void Visit(const WCHAR* name, const WCHAR* url, int level) override;
TocItem* GetRoot() {
return root;
}
void SetIsIndex(bool value) {
isIndex = value;
}
};
void EbookTocBuilder::Visit(const WCHAR* name, const WCHAR* url, int level) {
IPageDestination* dest;
if (!url) {
dest = nullptr;
} else if (url::IsAbsolute(url)) {
dest = NewSimpleDest(0, RectF(), 0.f, str::Dup(url));
} else {
dest = engine->GetNamedDest(url);
if (!dest && str::FindChar(url, '%')) {
AutoFreeWstr decodedUrl(str::Dup(url));
url::DecodeInPlace(decodedUrl);
dest = engine->GetNamedDest(decodedUrl);
}
}
// TODO; send parent to newEbookTocItem
TocItem* item = newEbookTocItem(nullptr, name, dest);
item->id = ++idCounter;
if (isIndex) {
item->pageNo = 0;
level++;
}
AppendTocItem(root, item, level);
}
/* EngineBase for handling EPUB documents */
class EngineEpub : public EngineEbook {
public:
EngineEpub();
~EngineEpub() override;
EngineBase* Clone() override;
ByteSlice GetFileData() override;
bool SaveFileAs(const char* copyFileName) override;
WCHAR* GetProperty(DocumentProperty prop) override {
return prop != DocumentProperty::FontList ? doc->GetProperty(prop) : ExtractFontList();
}
TocTree* GetToc() override;
static EngineBase* CreateFromFile(const WCHAR* fileName);
static EngineBase* CreateFromStream(IStream* stream);
protected:
EpubDoc* doc = nullptr;
IStream* stream = nullptr;
TocTree* tocTree = nullptr;
bool Load(const WCHAR* fileName);
bool Load(IStream* stream);
bool FinishLoading();
};
EngineEpub::EngineEpub() : EngineEbook() {
kind = kindEngineEpub;
defaultExt = L".epub";
}
EngineEpub::~EngineEpub() {
delete doc;
delete tocTree;
if (stream) {
stream->Release();
}
}
EngineBase* EngineEpub::Clone() {
if (stream) {
return CreateFromStream(stream);
}
if (FileName()) {
return CreateFromFile(FileName());
}
return nullptr;
}
bool EngineEpub::Load(const WCHAR* fileName) {
SetFileName(fileName);
if (dir::Exists(fileName)) {
// load uncompressed documents as a recompressed ZIP stream
ScopedComPtr<IStream> zipStream(OpenDirAsZipStream(fileName, true));
if (!zipStream) {
return false;
}
return Load(zipStream);
}
doc = EpubDoc::CreateFromFile(fileName);
return FinishLoading();
}
bool EngineEpub::Load(IStream* stream) {
stream->AddRef();
this->stream = stream;
doc = EpubDoc::CreateFromStream(stream);
return FinishLoading();
}
bool EngineEpub::FinishLoading() {
if (!doc) {
return false;
}
HtmlFormatterArgs args{};
args.htmlStr = doc->GetHtmlData();
args.pageDx = (float)pageRect.dx - 2 * pageBorder;
args.pageDy = (float)pageRect.dy - 2 * pageBorder;
args.SetFontName(GetDefaultFontName());
args.fontSize = GetDefaultFontSize();
args.textAllocator = &allocator;
args.textRenderMethod = mui::TextRenderMethod::GdiplusQuick;
pages = EpubFormatter(&args, doc).FormatAllPages(false);
// must set pageCount before ExtractPageAnchors
pageCount = (int)pages->size();
if (!ExtractPageAnchors()) {
return false;
}
preferredLayout = PageLayout(PageLayout::Type::Book);
if (doc->IsRTL()) {
preferredLayout.r2l = true;
}
return pageCount > 0;
}
ByteSlice EngineEpub::GetFileData() {
const WCHAR* fileName = FileName();
return GetStreamOrFileData(stream, fileName);
}
bool EngineEpub::SaveFileAs(const char* copyFileName) {
auto dstPath = ToWstrTemp(copyFileName);
if (stream) {
AutoFree d = GetDataFromStream(stream, nullptr);
bool ok = !d.empty() && file::WriteFile(dstPath, d.AsSpan());
if (ok) {
return true;
}
}
const WCHAR* fileName = FileName();
if (!fileName) {
return false;
}
return file::Copy(dstPath, fileName, false);
}
TocTree* EngineEpub::GetToc() {
if (tocTree) {
return tocTree;
}
EbookTocBuilder builder(this);
doc->ParseToc(&builder);
TocItem* root = builder.GetRoot();
if (!root) {
return nullptr;
}
auto realRoot = new TocItem();
realRoot->child = root;
tocTree = new TocTree(realRoot);
return tocTree;
}
EngineBase* EngineEpub::CreateFromFile(const WCHAR* fileName) {
EngineEpub* engine = new EngineEpub();
if (!engine->Load(fileName)) {
delete engine;
return nullptr;
}
return engine;
}
EngineBase* EngineEpub::CreateFromStream(IStream* stream) {
EngineEpub* engine = new EngineEpub();
if (!engine->Load(stream)) {
delete engine;
return nullptr;
}
return engine;
}
EngineBase* CreateEngineEpubFromFile(const WCHAR* fileName) {
return EngineEpub::CreateFromFile(fileName);
}
EngineBase* CreateEngineEpubFromStream(IStream* stream) {
return EngineEpub::CreateFromStream(stream);
}
/* EngineBase for handling FictionBook2 documents */
class EngineFb2 : public EngineEbook {
public:
EngineFb2() : EngineEbook() {
kind = kindEngineFb2;
defaultExt = L".fb2";
}
~EngineFb2() override {
delete tocTree;
delete doc;
}
EngineBase* Clone() override {
const WCHAR* fileName = FileName();
if (!fileName) {
return nullptr;
}
return CreateFromFile(fileName);
}
WCHAR* GetProperty(DocumentProperty prop) override {
return prop != DocumentProperty::FontList ? doc->GetProperty(prop) : ExtractFontList();
}
TocTree* GetToc() override;
static EngineBase* CreateFromFile(const WCHAR* fileName);
static EngineBase* CreateFromStream(IStream* stream);
protected:
Fb2Doc* doc = nullptr;
TocTree* tocTree = nullptr;
bool Load(const WCHAR* fileName);
bool Load(IStream* stream);
bool FinishLoading();
};
bool EngineFb2::Load(const WCHAR* fileName) {
SetFileName(fileName);
doc = Fb2Doc::CreateFromFile(fileName);
return FinishLoading();
}
bool EngineFb2::Load(IStream* stream) {
doc = Fb2Doc::CreateFromStream(stream);
return FinishLoading();
}
bool EngineFb2::FinishLoading() {
if (!doc) {
return false;
}
HtmlFormatterArgs args;
args.htmlStr = doc->GetXmlData();
args.pageDx = (float)pageRect.dx - 2 * pageBorder;
args.pageDy = (float)pageRect.dy - 2 * pageBorder;
args.SetFontName(GetDefaultFontName());
args.fontSize = GetDefaultFontSize();
args.textAllocator = &allocator;
args.textRenderMethod = mui::TextRenderMethod::GdiplusQuick;
if (doc->IsZipped()) {
defaultExt = L".fb2z";
}
pages = Fb2Formatter(&args, doc).FormatAllPages(false);
// must set pageCount before ExtractPageAnchors
pageCount = (int)pages->size();
if (!ExtractPageAnchors()) {
return false;
}
return pageCount > 0;
}
TocTree* EngineFb2::GetToc() {
if (tocTree) {
return tocTree;
}
EbookTocBuilder builder(this);
doc->ParseToc(&builder);
TocItem* root = builder.GetRoot();
if (!root) {
return nullptr;
}
auto realRoot = new TocItem();
realRoot->child = root;
tocTree = new TocTree(realRoot);
return tocTree;
}
EngineBase* EngineFb2::CreateFromFile(const WCHAR* fileName) {
EngineFb2* engine = new EngineFb2();
if (!engine->Load(fileName)) {
delete engine;
return nullptr;
}
return engine;
}
EngineBase* EngineFb2::CreateFromStream(IStream* stream) {
EngineFb2* engine = new EngineFb2();
if (!engine->Load(stream)) {
delete engine;
return nullptr;
}
return engine;
}
EngineBase* CreateEngineFb2FromFile(const WCHAR* fileName) {
return EngineFb2::CreateFromFile(fileName);
}
EngineBase* CreateEngineFb2FromStream(IStream* stream) {
return EngineFb2::CreateFromStream(stream);
}
/* EngineBase for handling Mobi documents */
#include "MobiDoc.h"
class EngineMobi : public EngineEbook {
public:
EngineMobi() : EngineEbook() {
kind = kindEngineMobi;
defaultExt = L".mobi";
}
~EngineMobi() override {
delete tocTree;
delete doc;
}
EngineBase* Clone() override {
const WCHAR* fileName = FileName();
if (!fileName) {
return nullptr;
}
return CreateFromFile(fileName);
}
WCHAR* GetProperty(DocumentProperty prop) override {
return prop != DocumentProperty::FontList ? doc->GetProperty(prop) : ExtractFontList();
}
IPageDestination* GetNamedDest(const WCHAR* name) override;
TocTree* GetToc() override;
static EngineBase* CreateFromFile(const WCHAR* fileName);
static EngineBase* CreateFromStream(IStream* stream);
protected:
MobiDoc* doc = nullptr;
TocTree* tocTree = nullptr;
bool Load(const WCHAR* fileName);