forked from sumatrapdfreader/sumatrapdf
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathHtmlFormatter.cpp
1505 lines (1372 loc) · 49.6 KB
/
HtmlFormatter.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: Simplified BSD (see COPYING.BSD) */
#include "utils/BaseUtil.h"
#include "utils/GdiPlusUtil.h"
#include "utils/HtmlParserLookup.h"
#include "utils/CssParser.h"
#include "utils/HtmlPullParser.h"
#include "mui/Mui.h"
#include "utils/Timer.h"
#include "EbookBase.h"
#include "FzImgReader.h"
#include "HtmlFormatter.h"
#include "utils/Log.h"
/*
Given size of a page, we format html into a set of pages. We handle only a small
subset of html commonly present in ebooks.
Formatting is a delayed affair, divided into 2 stages.
1. We gather elements and their sizes for the current line. When we detect that
adding another element would overflow current line, we position elements in
current line (stage 2) and start a new line. When we detect that adding a new
line would overflow current page, we start a new page.
2. When we position elements in current line, we calculate their x/y positions.
Delaying this calculation until we have all elements of the line is necessary
to implement e.g. justification. It's also simpler to have formatting logic in
2 simpler phases than a single, more complicated step. We still need to make sure
that both stages use the same logic for determining line/page overflow, otherwise
elements will be drawn outside page bounds. This shouldn't be hard because only
stage 1 calculates the sizes of elements.
*/
/*
TODO: Instead of inserting explicit SetFont, StartLink, etc. instructions
at the beginning of every page, DrawHtmlPage could always start with
that page's nextPageStyle.font, etc.
The information that we need to remember:
* font name (if different from default font name, nullptr otherwise)
* font size scale i.e. 1.f means "default font size". This is to allow the user to change
default font size and allow us to relayout from arbitrary page
* font style (bold/italic etc.)
* a link url if we're carrying over a text for a link (nullptr if no link)
* text color (when/if we support changing text color)
* more ?
TODO: fix http://code.google.com/p/sumatrapdf/issues/detail?id=2183
TODO: HtmlFormatter could be split into DrawInstrBuilder which knows pageDx, pageDy
and generates DrawInstr and splits them into pages and a better named class that
does the parsing of the document builds pages by invoking methods on DrawInstrBuilders.
TODO: support <figure> and <figcaption> as e.g in http://ebookarchitects.com/files/BookOfTexas.mobi
TODO: instead of generating list of DrawInstr objects, we could add neccessary
support to mui and use list of Control objects instead (especially if we slim down
Control objects further to make allocating hundreds of them cheaper or introduce some
other base element(s) with less functionality and less overhead).
*/
bool ValidReparseIdx(ptrdiff_t idx, HtmlPullParser* parser) {
return !((idx < 0) || (idx > (int)parser->Len()));
}
DrawInstr DrawInstr::Str(const char* s, size_t len, RectF bbox, bool rtl) {
DrawInstr di(rtl ? DrawInstrType::RtlString : DrawInstrType::String, bbox);
di.str.s = s;
di.str.len = len;
return di;
}
DrawInstr DrawInstr::SetFont(mui::CachedFont* font) {
DrawInstr di(DrawInstrType::SetFont);
di.font = font;
return di;
}
DrawInstr DrawInstr::FixedSpace(float dx) {
DrawInstr di(DrawInstrType::FixedSpace);
di.bbox.dx = dx;
return di;
}
DrawInstr DrawInstr::Image(ByteSlice img, RectF bbox) {
DrawInstr di(DrawInstrType::Image);
di.str.s = (const char*)img.data();
di.str.len = img.size();
di.bbox = bbox;
return di;
}
DrawInstr DrawInstr::LinkStart(const char* s, size_t len) {
DrawInstr di(DrawInstrType::LinkStart);
di.str.s = s;
di.str.len = len;
return di;
}
DrawInstr DrawInstr::Anchor(const char* s, size_t len, RectF bbox) {
DrawInstr di(DrawInstrType::Anchor);
di.str.s = s;
di.str.len = len;
di.bbox = bbox;
return di;
}
// parses size in the form "1em", "3pt" or "15px"
static void ParseSizeWithUnit(const char* s, size_t len, float* size, StyleRule::Unit* unit) {
if (str::Parse(s, len, "%fem", size)) {
*unit = StyleRule::em;
} else if (str::Parse(s, len, "%fin", size)) {
*unit = StyleRule::pt;
*size *= 72; // 1 inch is 72 points
} else if (str::Parse(s, len, "%fpt", size)) {
*unit = StyleRule::pt;
} else if (str::Parse(s, len, "%fpx", size)) {
*unit = StyleRule::px;
} else {
*unit = StyleRule::inherit;
}
}
StyleRule StyleRule::Parse(CssPullParser* parser) {
StyleRule rule;
const CssProperty* prop;
while ((prop = parser->NextProperty()) != nullptr) {
switch (prop->type) {
case Css_Text_Align:
rule.textAlign = FindAlignAttr(prop->s, prop->sLen);
break;
// TODO: some documents use Css_Padding_Left for indentation
case Css_Text_Indent:
ParseSizeWithUnit(prop->s, prop->sLen, &rule.textIndent, &rule.textIndentUnit);
break;
}
}
return rule;
}
StyleRule StyleRule::Parse(const char* s, size_t len) {
CssPullParser parser(s, len);
return Parse(&parser);
}
void StyleRule::Merge(StyleRule& source) {
if (source.textAlign != AlignAttr::NotFound) {
textAlign = source.textAlign;
}
if (source.textIndentUnit != StyleRule::inherit) {
textIndent = source.textIndent;
textIndentUnit = source.textIndentUnit;
}
}
HtmlFormatter::HtmlFormatter(HtmlFormatterArgs* args)
: pageDx(args->pageDx), pageDy(args->pageDy), textAllocator(args->textAllocator) {
currReparseIdx = args->reparseIdx;
htmlParser = new HtmlPullParser((const char*)args->htmlStr.data(), args->htmlStr.size());
htmlParser->SetCurrPosOff(currReparseIdx);
CrashIf(!ValidReparseIdx(currReparseIdx, htmlParser));
gfx = mui::AllocGraphicsForMeasureText();
textMeasure = CreateTextRender(args->textRenderMethod, gfx, 10, 10);
defaultFontName.SetCopy(args->GetFontName());
defaultFontSize = args->fontSize;
DrawStyle style;
style.font = mui::GetCachedFont(defaultFontName, defaultFontSize, FontStyleRegular);
style.align = AlignAttr::Justify;
style.dirRtl = false;
styleStack.Append(style);
nextPageStyle = styleStack.Last();
textMeasure->SetFont(CurrFont());
lineSpacing = textMeasure->GetCurrFontLineSpacing();
spaceDx = CurrFont()->GetSize() / 2.5f; // note: a heuristic
float spaceDx2 = GetSpaceDx(textMeasure);
if (spaceDx2 < spaceDx) {
spaceDx = spaceDx2;
}
EmitNewPage();
}
HtmlFormatter::~HtmlFormatter() {
// delete all pages that were not consumed by the caller
DeleteVecMembers(pagesToSend);
delete currPage;
delete textMeasure;
mui::FreeGraphicsForMeasureText(gfx);
delete htmlParser;
}
void HtmlFormatter::AppendInstr(DrawInstr di) {
currLineInstr.Append(di);
if (-1 == currLineReparseIdx) {
currLineReparseIdx = currReparseIdx;
CrashIf(!ValidReparseIdx(currReparseIdx, htmlParser));
}
}
void HtmlFormatter::SetFont(const WCHAR* fontName, FontStyle fs, float fontSize) {
if (fontSize < 0) {
fontSize = CurrFont()->GetSize();
}
mui::CachedFont* newFont = mui::GetCachedFont(fontName, fontSize, fs);
if (CurrFont() != newFont) {
AppendInstr(DrawInstr::SetFont(newFont));
}
DrawStyle style = styleStack.Last();
style.font = newFont;
styleStack.Append(style);
}
void HtmlFormatter::SetFontBasedOn(mui::CachedFont* font, FontStyle fs, float fontSize) {
const WCHAR* fontName = font->GetName();
if (nullptr == fontName) {
fontName = defaultFontName;
}
SetFont(fontName, fs, fontSize);
}
bool ValidStyleForChangeFontStyle(FontStyle fs) {
return (FontStyleBold == fs) || (FontStyleItalic == fs) || (FontStyleUnderline == fs) || (FontStyleStrikeout == fs);
}
// change the current font by adding (if addStyle is true) or removing
// a given font style from current font style
// TODO: it doesn't corrctly support the case where a style is wrongly nested
// like "<b>fo<i>oo</b>bar</i>" - "bar" should be italic but will be bold
void HtmlFormatter::ChangeFontStyle(FontStyle fs, bool addStyle) {
CrashIf(!ValidStyleForChangeFontStyle(fs));
if (addStyle) {
SetFontBasedOn(CurrFont(), (FontStyle)(fs | CurrFont()->GetStyle()));
} else {
RevertStyleChange();
}
}
void HtmlFormatter::SetAlignment(AlignAttr align) {
DrawStyle style = styleStack.Last();
style.align = align;
styleStack.Append(style);
}
void HtmlFormatter::RevertStyleChange() {
if (styleStack.size() > 1) {
DrawStyle style = styleStack.Pop();
if (style.font != CurrFont()) {
AppendInstr(DrawInstr::SetFont(CurrFont()));
}
dirRtl = style.dirRtl;
}
}
static bool IsVisibleDrawInstr(DrawInstr& i) {
switch (i.type) {
case DrawInstrType::String:
case DrawInstrType::RtlString:
case DrawInstrType::Line:
case DrawInstrType::Image:
return true;
}
return false;
}
// sum of widths of all elements with a fixed size and flexible
// spaces (using minimum value for its width)
float HtmlFormatter::CurrLineDx() {
float dx = NewLineX();
for (DrawInstr& i : currLineInstr) {
if (DrawInstrType::String == i.type || DrawInstrType::RtlString == i.type) {
dx += i.bbox.dx;
} else if (DrawInstrType::Image == i.type) {
dx += i.bbox.dx;
} else if (DrawInstrType::ElasticSpace == i.type) {
dx += spaceDx;
} else if (DrawInstrType::FixedSpace == i.type) {
dx += i.bbox.dx;
}
}
return dx;
}
// return the height of the tallest element on the line
float HtmlFormatter::CurrLineDy() {
float dy = lineSpacing;
for (DrawInstr& i : currLineInstr) {
if (IsVisibleDrawInstr(i)) {
if (i.bbox.dy > dy) {
dy = i.bbox.dy;
}
}
}
return dy;
}
// return the width of the left margin (used for paragraph
// indentation inside lists)
float HtmlFormatter::NewLineX() const {
// TODO: indent based on font size instead?
float x = 15.f * listDepth;
if (x < pageDx - 20.f) {
return x;
}
if (pageDx < 20.f) {
return 0.f;
}
return pageDx - 20.f;
}
// When this is called, Width and Height of each element is already set
// We set position x of each visible element
void HtmlFormatter::LayoutLeftStartingAt(float offX) {
DrawInstr* lastInstr = nullptr;
int instrCount = 0;
float x = offX + NewLineX();
for (DrawInstr& i : currLineInstr) {
if (DrawInstrType::String == i.type || DrawInstrType::RtlString == i.type || DrawInstrType::Image == i.type) {
i.bbox.x = x;
x += i.bbox.dx;
lastInstr = &i;
instrCount++;
} else if (DrawInstrType::ElasticSpace == i.type) {
x += spaceDx;
} else if (DrawInstrType::FixedSpace == i.type) {
x += i.bbox.dx;
}
}
// center a single image
if (instrCount == 1 && DrawInstrType::Image == lastInstr->type) {
lastInstr->bbox.x = (pageDx - lastInstr->bbox.dx) / 2.f;
}
}
// TODO: if elements are of different sizes (e.g. texts using different fonts)
// we should align them according to the baseline (which we would first need to
// record for each element)
static void SetYPos(Vec<DrawInstr>& instr, float y) {
for (DrawInstr& i : instr) {
if (IsVisibleDrawInstr(i)) {
i.bbox.y = y;
}
}
}
void HtmlFormatter::DumpLineDebugInfo() {
// TODO: write me
// like CurrLineDx() but dumps info about draw instructions to dbg out
}
// Redistribute extra space in the line equally among the spaces
void HtmlFormatter::JustifyLineBoth() {
float extraSpaceDxTotal = pageDx - currX;
#ifdef DEBUG
if (extraSpaceDxTotal < 0.f)
DumpLineDebugInfo();
#endif
CrashIf(extraSpaceDxTotal < 0.f);
LayoutLeftStartingAt(0.f);
size_t spaces = 0;
bool endsWithSpace = false;
for (DrawInstr& i : currLineInstr) {
if (DrawInstrType::ElasticSpace == i.type) {
++spaces;
endsWithSpace = true;
} else if (DrawInstrType::String == i.type || DrawInstrType::RtlString == i.type) {
endsWithSpace = false;
} else if (DrawInstrType::Image == i.type) {
endsWithSpace = false;
}
}
// don't take a space at the end of the line into account
// (the last word is explicitly right-aligned below)
if (endsWithSpace) {
spaces--;
}
if (0 == spaces) {
return;
}
// redistribute extra dx space among elastic spaces
float extraSpaceDx = extraSpaceDxTotal / (float)spaces;
float offX = 0.f;
DrawInstr* lastStr = nullptr;
for (DrawInstr& i : currLineInstr) {
if (DrawInstrType::ElasticSpace == i.type) {
offX += extraSpaceDx;
} else if (DrawInstrType::String == i.type || DrawInstrType::RtlString == i.type ||
DrawInstrType::Image == i.type) {
i.bbox.x += offX;
lastStr = &i;
}
}
// align the last element perfectly against the right edge in case
// we've accumulated rounding errors
if (lastStr) {
lastStr->bbox.x = pageDx - lastStr->bbox.dx;
}
}
bool HtmlFormatter::IsCurrLineEmpty() {
for (DrawInstr& i : currLineInstr) {
if (IsVisibleDrawInstr(i)) {
return false;
}
}
return true;
}
void HtmlFormatter::JustifyCurrLine(AlignAttr align) {
// TODO: is CurrLineDx needed at all?
CrashIf(currX != CurrLineDx());
switch (align) {
case AlignAttr::Left:
LayoutLeftStartingAt(0.f);
break;
case AlignAttr::Right:
LayoutLeftStartingAt(pageDx - currX);
break;
case AlignAttr::Center:
LayoutLeftStartingAt((pageDx - currX) / 2.f);
break;
case AlignAttr::Justify:
JustifyLineBoth();
break;
default:
CrashIf(true);
break;
}
// when the reading direction is right-to-left, mirror the entire page
// so that the first element on a line is the right-most, etc.
if (dirRtl) {
for (DrawInstr& i : currLineInstr) {
if (IsVisibleDrawInstr(i)) {
i.bbox.x = pageDx - i.bbox.x - i.bbox.dx;
}
}
}
}
static RectF RectFUnion(RectF& r1, RectF& r2) {
if (r2.IsEmpty()) {
return r1;
}
if (r1.IsEmpty()) {
return r2;
}
return r1.Union(r2);
}
void HtmlFormatter::UpdateLinkBboxes(HtmlPage* page) {
for (DrawInstr& i : page->instructions) {
if (DrawInstrType::LinkStart != i.type) {
continue;
}
for (DrawInstr* i2 = &i + 1; i2->type != DrawInstrType::LinkEnd; i2++) {
if (IsVisibleDrawInstr(*i2)) {
i.bbox = RectFUnion(i.bbox, i2->bbox);
}
}
}
}
void HtmlFormatter::ForceNewPage() {
bool createdNewPage = FlushCurrLine(true);
if (createdNewPage) {
return;
}
UpdateLinkBboxes(currPage);
pagesToSend.Append(currPage);
EmitNewPage();
currX = NewLineX();
currLineTopPadding = 0.f;
}
// returns true if created a new page
bool HtmlFormatter::FlushCurrLine(bool isParagraphBreak) {
if (IsCurrLineEmpty()) {
currX = NewLineX();
currLineTopPadding = 0;
// remove all spaces (only keep SetFont, LinkStart and Anchor instructions)
for (size_t k = currLineInstr.size(); k > 0; k--) {
DrawInstr& i = currLineInstr.at(k - 1);
if (DrawInstrType::FixedSpace == i.type || DrawInstrType::ElasticSpace == i.type) {
currLineInstr.RemoveAt(k - 1);
}
}
return false;
}
AlignAttr align = CurrStyle()->align;
if (isParagraphBreak && (AlignAttr::Justify == align)) {
align = AlignAttr::Left;
}
JustifyCurrLine(align);
// create a new page if necessary
float totalLineDy = CurrLineDy() + currLineTopPadding;
bool createdPage = false;
if (currY + totalLineDy > pageDy) {
// current line too big to fit in current page,
// so need to start another page
UpdateLinkBboxes(currPage);
pagesToSend.Append(currPage);
// instructions for each page need to be self-contained
// so we have to carry over some state (like current font)
CrashIf(!CurrFont());
EmitNewPage();
CrashIf(currLineReparseIdx > INT_MAX);
currPage->reparseIdx = (int)currLineReparseIdx;
createdPage = true;
}
SetYPos(currLineInstr, currY + currLineTopPadding);
currY += totalLineDy;
DrawInstr link;
if (currLinkIdx) {
link = currLineInstr.at(currLinkIdx - 1);
// TODO: this occasionally leads to empty links
AppendInstr(DrawInstr(DrawInstrType::LinkEnd));
}
currPage->instructions.Append(currLineInstr.LendData(), currLineInstr.size());
currLineInstr.Reset();
currLineReparseIdx = -1; // mark as not set
currLineTopPadding = 0;
currX = NewLineX();
if (currLinkIdx) {
AppendInstr(DrawInstr::LinkStart(link.str.s, link.str.len));
currLinkIdx = currLineInstr.size();
}
nextPageStyle = styleStack.Last();
return createdPage;
}
void HtmlFormatter::EmitNewPage() {
CrashIf(currReparseIdx > INT_MAX);
currPage = new HtmlPage((int)currReparseIdx);
currPage->instructions.Append(DrawInstr::SetFont(nextPageStyle.font));
currY = 0.f;
}
void HtmlFormatter::EmitEmptyLine(float lineDy) {
CrashIf(!IsCurrLineEmpty());
currY += lineDy;
if (currY <= pageDy) {
currX = NewLineX();
// remove all spaces (only keep SetFont, LinkStart and Anchor instructions)
for (size_t k = currLineInstr.size(); k > 0; k--) {
DrawInstr& i = currLineInstr.at(k - 1);
if (DrawInstrType::FixedSpace == i.type || DrawInstrType::ElasticSpace == i.type) {
currLineInstr.RemoveAt(k - 1);
}
}
return;
}
ForceNewPage();
}
static bool HasPreviousLineSingleImage(Vec<DrawInstr>& instrs) {
float imageY = -1;
for (size_t idx = instrs.size(); idx > 0; idx--) {
DrawInstr& i = instrs.at(idx - 1);
if (!IsVisibleDrawInstr(i)) {
continue;
}
if (-1 != imageY) {
// if another visible item precedes the image,
// it must be completely above it (previous line)
return i.bbox.y + i.bbox.dy <= imageY;
}
if (DrawInstrType::Image != i.type) {
return false;
}
imageY = i.bbox.y;
}
return imageY != -1;
}
bool HtmlFormatter::EmitImage(ByteSlice* img) {
CrashIf(img->empty());
Size imgSize = BitmapSizeFromData(*img);
if (imgSize.IsEmpty()) {
return false;
}
SizeF newSize((float)imgSize.dx, (float)imgSize.dy);
// move overly large images to a new line (if they don't fit entirely)
if (!IsCurrLineEmpty() && (currX + newSize.dx > pageDx || currY + newSize.dy > pageDy)) {
FlushCurrLine(false);
}
// move overly large images to a new page
// (if they don't fit even when scaled down to 75%)
float scalePage = std::min((pageDx - currX) / newSize.dx, pageDy / newSize.dy);
if (currY > 0 && currY + newSize.dy * std::min(scalePage, 0.75f) > pageDy) {
ForceNewPage();
}
// if image is bigger than the available space, scale it down
if (newSize.dx > pageDx - currX || newSize.dy > pageDy - currY) {
float scale = std::min(scalePage, (pageDy - currY) / newSize.dy);
// scale down images that follow right after a line
// containing a single image as little as possible,
// as they might be intended to be of the same size
if (scale < scalePage && HasPreviousLineSingleImage(currPage->instructions)) {
ForceNewPage();
scale = scalePage;
}
if (scale < 1) {
newSize.dx = std::min(newSize.dx * scale, pageDx - currX);
newSize.dy = std::min(newSize.dy * scale, pageDy - currY);
}
}
RectF bbox(PointF(currX, 0), newSize);
AppendInstr(DrawInstr::Image(*img, bbox));
currX += bbox.dx;
return true;
}
// add horizontal line (<hr> in html terms)
void HtmlFormatter::EmitHr() {
// hr creates an implicit paragraph break
FlushCurrLine(true);
CrashIf(NewLineX() != currX);
RectF bbox(0.f, 0.f, pageDx, lineSpacing);
AppendInstr(DrawInstr(DrawInstrType::Line, bbox));
FlushCurrLine(true);
}
void HtmlFormatter::EmitParagraph(float indent) {
FlushCurrLine(true);
CrashIf(NewLineX() != currX);
bool needsIndent = AlignAttr::Left == CurrStyle()->align || AlignAttr::Justify == CurrStyle()->align;
if (indent > 0 && needsIndent && EnsureDx(indent)) {
AppendInstr(DrawInstr::FixedSpace(indent));
currX += indent;
}
}
// ensure there is enough dx space left in the current line
// if there isn't, we start a new line
// returns false if dx is bigger than pageDx
bool HtmlFormatter::EnsureDx(float dx) {
if (currX + dx <= pageDx) {
return true;
}
FlushCurrLine(false);
return dx <= pageDx;
}
// don't emit multiple spaces and don't emit spaces
// at the beginning of the line
static bool CanEmitElasticSpace(float currX, float NewLineX, float maxCurrX, Vec<DrawInstr>& currLineInstr) {
if (NewLineX == currX || 0 == currLineInstr.size()) {
return false;
}
// prevent elastic spaces from being flushed to the
// beginning of the next line
if (currX > maxCurrX) {
return false;
}
DrawInstr& di = currLineInstr.Last();
// don't add a space if only an anchor would be in between them
if (DrawInstrType::Anchor == di.type && currLineInstr.size() > 1) {
di = currLineInstr.at(currLineInstr.size() - 2);
}
return (DrawInstrType::ElasticSpace != di.type) && (DrawInstrType::FixedSpace != di.type);
}
void HtmlFormatter::EmitElasticSpace() {
if (!CanEmitElasticSpace(currX, NewLineX(), pageDx - spaceDx, currLineInstr)) {
return;
}
EnsureDx(spaceDx);
currX += spaceDx;
AppendInstr(DrawInstr(DrawInstrType::ElasticSpace));
}
// return true if we can break a word on a given character during layout
static bool CanBreakWordOnChar(WCHAR c) {
// don't break on Chinese and Japan characters
// https://github.com/sumatrapdfreader/sumatrapdf/issues/250
// https://github.com/sumatrapdfreader/sumatrapdf/pull/1057
// There are other ranges, but far less common
// https://stackoverflow.com/questions/1366068/whats-the-complete-range-for-chinese-characters-in-unicode
return c >= 0x2E80 && c <= 0xA4CF;
}
// a text run is a string of consecutive text with uniform style
void HtmlFormatter::EmitTextRun(const char* s, const char* end) {
currReparseIdx = s - htmlParser->Start();
CrashIf(!ValidReparseIdx(currReparseIdx, htmlParser));
CrashIf(IsSpaceOnly(s, end) && !preFormatted);
const char* tmp = ResolveHtmlEntities(s, end, textAllocator);
bool resolved = tmp != s;
if (resolved) {
s = tmp;
end = s + str::Len(s);
}
while (s < end) {
// don't update the reparseIdx if s doesn't point into the original source
if (!resolved) {
currReparseIdx = s - htmlParser->Start();
}
auto bufTmp = ToWstrTemp(s, end - s);
size_t strLen = bufTmp.size();
WCHAR* buf = bufTmp.Get();
// soft hyphens should not be displayed
strLen -= str::RemoveCharsInPlace(buf, L"\xad");
if (0 == strLen) {
break;
}
textMeasure->SetFont(CurrFont());
RectF bbox = textMeasure->Measure(buf, strLen);
if (bbox.dx <= pageDx - currX) {
AppendInstr(DrawInstr::Str(s, end - s, bbox, dirRtl));
currX += bbox.dx;
break;
}
// get len That Fits the remaining space in the line
size_t lenThatFits = StringLenForWidth(textMeasure, buf, strLen, pageDx - currX);
// try to prevent a break in the middle of a word
if (lenThatFits > 0) {
if (!CanBreakWordOnChar(buf[lenThatFits])) {
size_t lenTmp;
for (lenTmp = lenThatFits; lenTmp > 0; lenTmp--) {
if (CanBreakWordOnChar(buf[lenTmp - 1])) {
break;
}
}
if (lenTmp == 0) {
// make a new line if the word need to show in another line
if (currX != NewLineX()) {
FlushCurrLine(false);
continue;
}
// split the word (or CJK sentence) if it is too long to show in one line
} else {
// renew lenThatFits
lenThatFits = lenTmp;
}
}
} else {
// make a new line when current line is fullfilled
FlushCurrLine(false);
continue;
}
textMeasure->SetFont(CurrFont());
bbox = ToGdipRectF(textMeasure->Measure(buf, lenThatFits));
CrashIf(bbox.dx > pageDx);
// s is UTF-8 and buf is UTF-16, so one
// WCHAR doesn't always equal one char
// TODO: this usually fails for non-BMP characters (i.e. hardly ever)
for (size_t i = lenThatFits; i > 0; i--) {
lenThatFits += buf[i - 1] < 0x80 ? 0 : buf[i - 1] < 0x800 ? 1 : 2;
}
AppendInstr(DrawInstr::Str(s, lenThatFits, bbox, dirRtl));
currX += bbox.dx;
s += lenThatFits;
}
}
void HtmlFormatter::HandleAnchorAttr(HtmlToken* t, bool idsOnly) {
if (t->IsEndTag()) {
return;
}
AttrInfo* attr = t->GetAttrByName("id");
if (!attr && !idsOnly && Tag_A == t->tag) {
attr = t->GetAttrByName("name");
}
if (!attr) {
return;
}
// TODO: make anchors more specific than the top of the current line?
RectF bbox(0, currY, pageDx, 0);
// append at the start of the line to prevent the anchor
// from being flushed to the next page (with wrong currY value)
currPage->instructions.Append(DrawInstr::Anchor(attr->val, attr->valLen, bbox));
}
void HtmlFormatter::HandleDirAttr(HtmlToken* t) {
// only apply reading direction changes to block elements (for now)
if (t->IsStartTag() && !IsInlineTag(t->tag)) {
AttrInfo* attr = t->GetAttrByName("dir");
if (attr) {
dirRtl = CurrStyle()->dirRtl = attr->ValIs("RTL");
}
}
}
void HtmlFormatter::HandleTagBr() {
// make sure to always emit a line
if (IsCurrLineEmpty()) {
EmitEmptyLine(lineSpacing);
} else {
FlushCurrLine(true);
}
}
static AlignAttr GetAlignAttr(HtmlToken* t, AlignAttr defVal) {
AttrInfo* attr = t->GetAttrByName("align");
if (!attr) {
return defVal;
}
AlignAttr align = FindAlignAttr(attr->val, attr->valLen);
if (AlignAttr::NotFound == align) {
return defVal;
}
return align;
}
void HtmlFormatter::HandleTagP(HtmlToken* t, bool isDiv) {
if (!t->IsEndTag()) {
AlignAttr align = CurrStyle()->align;
float indent = 0;
StyleRule rule = ComputeStyleRule(t);
if (rule.textAlign != AlignAttr::NotFound) {
align = rule.textAlign;
} else if (!isDiv) {
// prefer CSS styling to align attribute
align = GetAlignAttr(t, align);
}
if (rule.textIndentUnit != StyleRule::inherit && rule.textIndent > 0) {
float factor = CurrFont()->GetSize();
if (rule.textIndentUnit != StyleRule::em) {
factor = 1;
#if 0
if (rule.textIndentUnit == StyleRule::pt) {
/* TODO: take DPI into account */
factor = 1;
}
#endif
}
indent = rule.textIndent * factor;
}
SetAlignment(align);
EmitParagraph(indent);
} else {
FlushCurrLine(true);
RevertStyleChange();
}
EmitEmptyLine(0.4f * CurrFont()->GetSize());
}
void HtmlFormatter::HandleTagFont(HtmlToken* t) {
if (t->IsEndTag()) {
RevertStyleChange();
return;
}
AttrInfo* attr = t->GetAttrByName("face");
const WCHAR* faceName = CurrFont()->GetName();
if (attr) {
auto bufTmp = ToWstrTemp(attr->val, attr->valLen);
WCHAR* buf = bufTmp.Get();
size_t strLen = bufTmp.size();
// multiple font names can be comma separated
if (strLen > 0 && *buf != ',') {
str::TransCharsInPlace(buf, L",", L"\0");
faceName = buf;
}
}
float fontSize = CurrFont()->GetSize();
attr = t->GetAttrByName("size");
if (attr) {
// the sizes are in the range from 1 (tiny) to 7 (huge)
int size = 3; // normal size
str::Parse(attr->val, attr->valLen, "%d", &size);
// sizes can also be relative to the current size
if (attr->valLen > 0 && ('-' == *attr->val || '+' == *attr->val)) {
size += 3;
}
size = limitValue(size, 1, 7);
float scale = (float)pow(1.2f, size - 3);
fontSize = defaultFontSize * scale;
}
SetFont(faceName, (FontStyle)CurrFont()->GetStyle(), fontSize);
}
bool HtmlFormatter::HandleTagA(HtmlToken* t, const char* linkAttr, const char* attrNS) {
if (t->IsStartTag() && !currLinkIdx) {
AttrInfo* attr = attrNS ? t->GetAttrByNameNS(linkAttr, attrNS) : t->GetAttrByName(linkAttr);
if (attr) {
AppendInstr(DrawInstr::LinkStart(attr->val, attr->valLen));
currLinkIdx = currLineInstr.size();
return true;
}
} else if (t->IsEndTag() && currLinkIdx) {
AppendInstr(DrawInstr(DrawInstrType::LinkEnd));
currLinkIdx = 0;
return true;
}
return false;
}
inline bool IsTagH(HtmlTag tag) {
switch (tag) {
case Tag_H1:
case Tag_H2:
case Tag_H3:
case Tag_H4:
case Tag_H5:
case Tag_H6:
return true;
}
return false;
}
void HtmlFormatter::HandleTagHx(HtmlToken* t) {
if (t->IsEndTag()) {
FlushCurrLine(true);
currY += CurrFont()->GetSize() / 2;
RevertStyleChange();
} else {
EmitParagraph(0);
float fontSize = defaultFontSize * (float)pow(1.1f, '5' - t->s[1]);
if (currY > 0) {
currY += fontSize / 2;
}
SetFontBasedOn(CurrFont(), FontStyleBold, fontSize);
StyleRule rule = ComputeStyleRule(t);
if (AlignAttr::NotFound == rule.textAlign) {
rule.textAlign = GetAlignAttr(t, AlignAttr::Left);
}
CurrStyle()->align = rule.textAlign;
}
}
void HtmlFormatter::HandleTagList(HtmlToken* t) {
FlushCurrLine(true);
if (t->IsStartTag()) {
listDepth++;
} else if (t->IsEndTag() && listDepth > 0) {
listDepth--;
}
currX = NewLineX();
}
void HtmlFormatter::HandleTagPre(HtmlToken* t) {
FlushCurrLine(true);
if (t->IsStartTag()) {
SetFont(L"Courier New", (FontStyle)CurrFont()->GetStyle());
CurrStyle()->align = AlignAttr::Left;
preFormatted = true;
} else if (t->IsEndTag()) {
RevertStyleChange();
preFormatted = false;
}
}
StyleRule* HtmlFormatter::FindStyleRule(HtmlTag tag, const char* clazz, size_t clazzLen) {
u32 classHash = clazz ? MurmurHash2(clazz, clazzLen) : 0;
for (size_t i = 0; i < styleRules.size(); i++) {
StyleRule& rule = styleRules.at(i);
if (tag == rule.tag && classHash == rule.classHash) {
return &rule;
}
}
return nullptr;
}
StyleRule HtmlFormatter::ComputeStyleRule(HtmlToken* t) {
StyleRule rule;
// get style rules ordered by specificity
StyleRule* prevRule = FindStyleRule(Tag_Body, nullptr, 0);
if (prevRule) {
rule.Merge(*prevRule);
}
prevRule = FindStyleRule(Tag_Any, nullptr, 0);
if (prevRule) {
rule.Merge(*prevRule);
}
prevRule = FindStyleRule(t->tag, nullptr, 0);
if (prevRule) {
rule.Merge(*prevRule);
}
// TODO: support multiple class names