-
Notifications
You must be signed in to change notification settings - Fork 28
/
GumboInterface.cpp
1610 lines (1378 loc) · 53.8 KB
/
GumboInterface.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 (C) 2015-2020 Kevin B. Hendricks, Stratford Ontario
**
** This file is part of PageEdit.
**
** PageEdit is free software: you can redistribute it and/or modify
** it under the terms of the GNU General Public License as published by
** the Free Software Foundation, either version 3 of the License, or
** (at your option) any later version.
**
** PageEdit is distributed in the hope that it will be useful,
** but WITHOUT ANY WARRANTY; without even the implied warranty of
** MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
** GNU General Public License for more details.
**
** You should have received a copy of the GNU General Public License
** along with PageEdit. If not, see <http://www.gnu.org/licenses/>.
**
*************************************************************************/
#include <QString>
#include <QStringList>
#include <QRegularExpression>
#include <QRegularExpressionMatch>
#include <QDir>
#include <QUrl>
#include <QFileInfo>
// #include <QDebug>
#include "Utility.h"
#include "GumboInterface.h"
#include "string_buffer.h"
#include "error.h"
static std::unordered_set<std::string> nonbreaking_inline = {
"a","abbr","acronym","b","bdo","big","br","button","cite","code","del",
"dfn","em","font","i","image","img","input","ins","kbd","label","map",
"mark", "nobr","object","q","ruby","rt","s","samp","select","small",
"span","strike","strong","sub","sup","textarea","tt","u","var",
"wbr", "mbp:nu"
};
static std::unordered_set<std::string> preserve_whitespace = {
"code", "pre","textarea","script","style"
};
static std::unordered_set<std::string> special_handling = {
"html","body"
};
static std::unordered_set<std::string> no_entity_sub = {
"script","style"
};
static std::unordered_set<std::string> void_tags = {
"area","base","basefont","bgsound","br","col","command","embed",
"event-source","frame","hr","img","input","keygen","link",
"meta","param","source","spacer","track","wbr",
"mbp:pagebreak", "mglyph", "mspace", "mprescripts", "none",
"maligngroup", "malignmark", "msline"
};
static std::unordered_set<std::string> structural_tags = {
"article","aside","blockquote","body","canvas","colgroup","div","dl",
"figure","footer","head","header","hr","html","ol","section",
"table","tbody","tfoot","thead","td","th","tr","ul"
};
static std::unordered_set<std::string> other_text_holders = {
"address","caption","dd","div","dt","h1","h2","h3","h4","h5","h6",
"legend","li","option","p","td","th","title"
};
static std::unordered_set<std::string> manifest_properties = {
"math","nav","script","svg","epub:switch"
};
static std::unordered_set<std::string> href_src_tags = {
"a","area","audio","base","embed","font-face-uri","frame","iframe",
"image","img","input","link","object","script","source","track","video"
};
static const QChar POUND_SIGN = QChar::fromLatin1('#');
static const QChar FORWARD_SLASH = QChar::fromLatin1('/');
static const std::string aSRC = std::string("src");
static const std::string aHREF = std::string("href");
static const std::string aPOSTER = std::string("poster");
static const std::string aDATA = std::string("data");
QHash<QString,QString> EmptyHash = QHash<QString,QString>();
// These need to match the GumboAttributeNamespaceEnum sequence
static const char * attribute_nsprefixes[4] = { "", "xlink:", "xml:", "xmlns:" };
// Note: m_output contains the gumbo output tree which
// has data structures with pointers into the original source
// buffer passed in!!!!!!
// This source buffer is provided by the m_utf8src std::string
// which should always exist unchanged alongside the output tree
// Do NOT change or delete m_utf8src once set until after you
// have properly destroyed the gumbo output tree
GumboInterface::GumboInterface(const QString &source, const QString &version)
: m_source(source),
m_output(NULL),
m_utf8src(""),
m_sourceupdates(EmptyHash),
m_newcsslinks(""),
m_currentbkpath(""),
m_currentdir(""),
m_newbody(""),
m_version(version),
m_newbookpath("")
{
}
GumboInterface::GumboInterface(const QString &source, const QString &version, const QHash<QString,QString> & source_updates)
: m_source(source),
m_output(NULL),
m_utf8src(""),
m_sourceupdates(source_updates),
m_newcsslinks(""),
m_currentbkpath(""),
m_currentdir(""),
m_newbody(""),
m_version(version),
m_newbookpath("")
{
}
GumboInterface::~GumboInterface()
{
if (m_output != NULL) {
gumbo_destroy_output(m_output);
m_output = NULL;
m_utf8src = "";
}
}
void GumboInterface::parse()
{
if (!m_source.isEmpty() && (m_output == NULL)) {
m_utf8src = m_source.toStdString();
// remove any xml header line and any trailing whitespace
if (m_utf8src.compare(0,5,"<?xml") == 0) {
size_t end = m_utf8src.find_first_of('>', 5);
end = m_utf8src.find_first_not_of("\n\r\t\v\f ",end+1);
m_utf8src.erase(0,end);
}
// In case we ever have to revert to earlier versions, please note the following
// additional initialization is needed because Microsoft Visual Studio 2013 (and earlier?)
// do not properly initialize myoptions from the static const kGumboDefaultOptions defined
// in the gumbo library. Instead whatever was in memory at the time is used causing random
// issues later on so if reverting remember to keep these specific changes as the bug
// they work around took a long long time to track down
GumboOptions myoptions = kGumboDefaultOptions;
myoptions.tab_stop = 4;
myoptions.use_xhtml_rules = true;
myoptions.stop_on_first_error = false;
myoptions.max_tree_depth = 400;
myoptions.max_errors = 50;
// GumboInterface::m_mutex.lock();
m_output = gumbo_parse_with_options(&myoptions, m_utf8src.data(), m_utf8src.length());
// GumboInterface::m_mutex.unlock();
}
}
void GumboInterface::parse_fragment()
{
if (!m_source.isEmpty() && (m_output == NULL)) {
// In case we ever have to revert to earlier versions, please note the following
// additional initialization is needed because Microsoft Visual Studio 2013 (and earlier?)
// do not properly initialize myoptions from the static const kGumboDefaultOptions defined
// in the gumbo library. Instead whatever was in memory at the time is used causing random
// issues later on so if reverting remember to keep these specific changes as the bug
// they work around took a long long time to track down
GumboOptions myoptions = kGumboDefaultOptions;
myoptions.tab_stop = 4;
myoptions.use_xhtml_rules = true;
myoptions.stop_on_first_error = false;
myoptions.max_tree_depth = 400;
myoptions.max_errors = 50;
m_utf8src = m_source.toStdString();
m_output = gumbo_parse_fragment(&myoptions, m_utf8src.data(), m_utf8src.length(),
GUMBO_TAG_BODY, GUMBO_NAMESPACE_HTML);
m_output = gumbo_parse_with_options(&myoptions, m_utf8src.data(), m_utf8src.length());
}
}
QString GumboInterface::repair()
{
QString result = "";
if (!m_source.isEmpty()) {
if (m_output == NULL) {
parse();
}
std::string utf8out = serialize(m_output->document);
rtrim(utf8out);
result = "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n" + QString::fromStdString(utf8out);
}
return result;
}
QString GumboInterface::get_fragment_xhtml()
{
QString result = "";
if (!m_source.isEmpty()) {
if (m_output == NULL) {
parse_fragment();
}
std::string utf8out = serialize(m_output->document);
rtrim(utf8out);
result = QString::fromStdString(utf8out);
}
return result;
}
QString GumboInterface::getxhtml()
{
QString result = "";
if (!m_source.isEmpty()) {
if (m_output == NULL) {
parse();
}
std::string utf8out = serialize(m_output->document);
rtrim(utf8out);
result = "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n" + QString::fromStdString(utf8out);
}
return result;
}
QString GumboInterface::prettyprint(QString indent_chars)
{
QString result = "";
if (!m_source.isEmpty()) {
if (m_output == NULL) {
parse();
}
std::string ind = indent_chars.toStdString();
std::string utf8out = prettyprint(m_output->document, 0, ind);
rtrim(utf8out);
result = "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n" + QString::fromStdString(utf8out);
}
return result;
}
QStringList GumboInterface::get_all_properties()
{
QStringList properties;
if (!m_source.isEmpty()) {
if (m_output == NULL) {
parse();
}
properties = get_properties(m_output->root);
}
return properties;
}
QString GumboInterface::perform_source_updates(const QString& my_current_book_relpath,
const QString& newbookpath)
{
m_currentbkpath = my_current_book_relpath;
m_currentdir = QFileInfo(m_currentbkpath).dir().path();
m_newbookpath = newbookpath;
QString result = "";
if (!m_source.isEmpty()) {
if (m_output == NULL) {
parse();
}
enum UpdateTypes doupdates = SourceUpdates;
std::string utf8out = serialize(m_output->document, doupdates);
rtrim(utf8out);
result = "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n" + QString::fromStdString(utf8out);
}
return result;
}
QString GumboInterface::perform_style_updates(const QString& my_current_book_relpath,
const QString& newbookpath)
{
m_currentbkpath = my_current_book_relpath;
m_currentdir = QFileInfo(m_currentbkpath).dir().path();
m_newbookpath = newbookpath;
QString result = "";
if (!m_source.isEmpty()) {
if (m_output == NULL) {
parse();
}
enum UpdateTypes doupdates = StyleUpdates;
std::string utf8out = serialize(m_output->document, doupdates);
rtrim(utf8out);
result = "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n" + QString::fromStdString(utf8out);
}
return result;
}
QString GumboInterface::perform_link_updates(const QString& newcsslinks)
{
m_newcsslinks = newcsslinks.toStdString();
QString result = "";
if (!m_source.isEmpty()) {
if (m_output == NULL) {
parse();
}
enum UpdateTypes doupdates = LinkUpdates;
std::string utf8out = serialize(m_output->document, doupdates);
rtrim(utf8out);
result = "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n" + QString::fromStdString(utf8out);
}
return result;
}
GumboNode * GumboInterface::get_document_node()
{
if (!m_source.isEmpty()) {
if (m_output == NULL) {
parse();
}
}
return m_output->document;
}
GumboNode * GumboInterface::get_root_node() {
if (!m_source.isEmpty()) {
if (m_output == NULL) {
parse();
}
}
return m_output->root;
}
GumboNode * GumboInterface::get_body_node()
{
if (!m_source.isEmpty()) {
if (m_output == NULL) {
parse();
}
}
QList<GumboTag> tags = QList<GumboTag>() << GUMBO_TAG_BODY;
QList<GumboNode*> nodes = get_all_nodes_with_tags(tags);
if (nodes.count() == 0) {
return NULL;
}
return nodes.at(0);
}
QString GumboInterface::get_body_contents()
{
if (!m_source.isEmpty()) {
if (m_output == NULL) {
parse();
}
}
QList<GumboTag> tags = QList<GumboTag>() << GUMBO_TAG_BODY;
QList<GumboNode*> nodes = get_all_nodes_with_tags(tags);
if (nodes.count() != 1) {
return QString();
}
enum UpdateTypes doupdates = NoUpdates;
std::string results = serialize_contents(nodes.at(0), doupdates);
return QString::fromStdString(results);
}
QString GumboInterface::get_body_text()
{
if (!m_source.isEmpty()) {
if (m_output == NULL) {
parse();
}
}
QList<GumboTag> tags = QList<GumboTag>() << GUMBO_TAG_BODY;
QList<GumboNode*> nodes = get_all_nodes_with_tags(tags);
if (nodes.count() != 1) {
return QString();
}
QString results = get_local_text_of_node(nodes.at(0));
return results;
}
QStringList GumboInterface::get_properties(GumboNode* node)
{
if (node->type != GUMBO_NODE_ELEMENT) {
return QStringList();
}
QStringList properties;
std::string tagname = get_tag_name(node);
if (in_set(manifest_properties, tagname)) {
properties.append(QString::fromStdString(tagname));
}
GumboAttribute* attr = gumbo_get_attribute(&node->v.element.attributes, "src");
if (attr && !QUrl(QString::fromUtf8(attr->value)).isRelative()) {
properties.append(QString("remote-resources"));
}
GumboVector* children = &node->v.element.children;
for (unsigned int i = 0; i < children->length; ++i) {
properties.append(get_properties(static_cast<GumboNode*>(children->data[i])));
}
return properties;
}
QString GumboInterface::get_qwebpath_to_node(GumboNode* node)
{
QStringList path_pieces;
GumboNode* anode = node;
while (anode && !((anode->type == GUMBO_NODE_ELEMENT) && (anode->v.element.tag == GUMBO_TAG_HTML))) {
GumboNode* myparent = anode->parent;
QString parent_name = QString::fromStdString(get_tag_name(myparent));
int index;
QString aname = QString::fromStdString(get_tag_name(anode));
if (aname == "#text") {
index = anode->index_within_parent;
} else {
// need to find child num in parent as if only elements exist
GumboVector* children = &myparent->v.element.children;
int elnum = 0;
for (unsigned int i=0; i < children->length; i++) {
GumboNode* child = static_cast<GumboNode*>(children->data[i]);
if (i == anode->index_within_parent) {
break;
}
if ((child->type == GUMBO_NODE_ELEMENT) || (child->type == GUMBO_NODE_TEMPLATE)) {
elnum++;
}
}
index = elnum;
}
path_pieces.prepend(parent_name + " " + QString::number(index));
anode = myparent;
}
return path_pieces.join(",");
}
GumboNode* GumboInterface::get_node_from_qwebpath(QString webpath)
{
QStringList path_pieces = webpath.split(",", Qt::SkipEmptyParts);
GumboNode* node = get_root_node();
GumboNode* end_node = node;
for (int i=0; i < path_pieces.count() - 1 ; ++i) {
QString piece = path_pieces.at(i);
QString name = piece.split(" ")[0];
int index = piece.split(" ")[1].toInt();
GumboVector* children = &node->v.element.children;
GumboNode * next_node = NULL;
if (children->length > 0) {
if (path_pieces.at(i+1).startsWith("#text")) {
// trying to find the right text child of the parent is very difficult
// It changes depending on what live editing is done in BookView
// It also requires document.normalize() to be done to merge adjacent text pieces
// but doing so will remove the cursor/highlight if it is on a text node merged away
// so restrict this to something same in that same parent element
if (index >= (int)(children->length)) index = children->length - 1;
if (index < 0) index = 0;
next_node = static_cast<GumboNode*>(children->data[index]);
} else {
// need to index correct child index when only counting elements
int elnum = -1;
for (unsigned int j=0; j < children->length; j++) {
GumboNode* child = static_cast<GumboNode*>(children->data[j]);
if ((child->type == GUMBO_NODE_ELEMENT) || (child->type == GUMBO_NODE_TEMPLATE)) {
elnum++;
}
if (elnum == index) {
next_node = child;
break;
}
}
}
if (next_node) {
end_node = next_node;
node = next_node;
} else {
break;
}
}
}
return end_node;
}
QList<unsigned int> GumboInterface::get_path_to_node(GumboNode* node)
{
QList<unsigned int> apath = QList<unsigned int>();
GumboNode* anode = node;
while (anode && !((anode->type == GUMBO_NODE_ELEMENT) && (anode->v.element.tag == GUMBO_TAG_HTML))) {
apath.prepend(anode->index_within_parent);
anode = anode->parent;
}
return apath;
}
GumboNode* GumboInterface::get_node_from_path(QList<unsigned int> & apath)
{
GumboNode* dest = get_root_node();
foreach(unsigned int childnum, apath) {
if ((dest->type == GUMBO_NODE_ELEMENT) || (dest->type == GUMBO_NODE_TEMPLATE)) {
GumboVector* children = &dest->v.element.children;
if (childnum < children->length) {
dest = static_cast<GumboNode*>(children->data[childnum]);
} else {
break;
}
} else {
break;
}
}
return dest;
}
QString GumboInterface::perform_body_updates(const QString & new_body)
{
QString result = "";
if (!m_source.isEmpty()) {
if (m_output == NULL) {
parse();
}
}
QList<GumboTag> tags = QList<GumboTag>() << GUMBO_TAG_BODY;
QList<GumboNode*> nodes = get_all_nodes_with_tags(tags);
if (nodes.count() != 1) {
return QString();
}
m_newbody = new_body.toStdString();
enum UpdateTypes doupdates = BodyUpdates;
std::string utf8out = serialize(m_output->document, doupdates);
result = "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n" + QString::fromStdString(utf8out);
m_newbody= "";
return result;
}
QList<GumboWellFormedError> GumboInterface::error_check()
{
QList<GumboWellFormedError> errlist;
int line_offset = 0;
// In case we ever have to revert to earlier versions, please note the following
// additional initialization is needed because Microsoft Visual Studio 2013 (and earlier?)
// do not properly initialize myoptions from the static const kGumboDefaultOptions defined
// in the gumbo library. Instead whatever was in memory at the time is used causing random
// issues later on so if reverting remember to keep these specific changes as the bug
// they work around took a long long time to track down
GumboOptions myoptions = kGumboDefaultOptions;
myoptions.tab_stop = 4;
myoptions.use_xhtml_rules = true;
myoptions.stop_on_first_error = false;
myoptions.max_tree_depth = 400;
myoptions.max_errors = -1;
if (!m_source.isEmpty() && (m_output == NULL)) {
m_utf8src = m_source.toStdString();
// remove any xml header line and trailing whitespace
if (m_utf8src.compare(0,5,"<?xml") == 0) {
size_t end = m_utf8src.find_first_of('>', 0);
end = m_utf8src.find_first_not_of("\n\r\t\v\f ",end+1);
m_utf8src.erase(0,end);
line_offset++;
}
// add in epub version specific doctype if missing
if ((m_utf8src.compare(0,9,"<!DOCTYPE") != 0) && (m_utf8src.compare(0,9,"<!doctype") != 0)) {
if (m_version.startsWith('3')) {
m_utf8src.insert(0,"<!DOCTYPE html>\n");
} else {
m_utf8src.insert(0, "<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.1//EN\"\n \"http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd\">\n\n");
}
line_offset--;
}
m_output = gumbo_parse_with_options(&myoptions, m_utf8src.data(), m_utf8src.length());
}
// qDebug() << QString::fromStdString(m_utf8src);
const GumboVector* errors = &m_output->errors;
for (unsigned int i=0; i< errors->length; ++i) {
GumboError* er = static_cast<GumboError*>(errors->data[i]);
GumboWellFormedError gperror;
gperror.line = er->position.line + line_offset;;
gperror.column = er->position.column;
// unsigned int typenum = er->type;
GumboStringBuffer text;
gumbo_string_buffer_init(&text);
gumbo_error_to_string(er, &text);
std::string errmsg(text.data, text.length);
gperror.message = QString::fromStdString(errmsg);
// qDebug() << gperror.message;
gumbo_string_buffer_destroy(&text);
errlist.append(gperror);
}
return errlist;
}
QList<GumboWellFormedError> GumboInterface::fragment_error_check()
{
QList<GumboWellFormedError> errlist;
// In case we ever have to revert to earlier versions, please note the following
// additional initialization is needed because Microsoft Visual Studio 2013 (and earlier?)
// do not properly initialize myoptions from the static const kGumboDefaultOptions defined
// in the gumbo library. Instead whatever was in memory at the time is used causing random
// issues later on so if reverting remember to keep these specific changes as the bug
// they work around took a long long time to track down
GumboOptions myoptions = kGumboDefaultOptions;
myoptions.tab_stop = 4;
myoptions.use_xhtml_rules = true;
myoptions.stop_on_first_error = false;
myoptions.max_tree_depth = 400;
myoptions.max_errors = -1;
if (!m_source.isEmpty() && (m_output == NULL)) {
m_utf8src = m_source.toStdString();
m_output = gumbo_parse_fragment(&myoptions, m_utf8src.data(), m_utf8src.length(),
GUMBO_TAG_BODY, GUMBO_NAMESPACE_HTML);
}
const GumboVector* errors = &m_output->errors;
for (unsigned int i=0; i< errors->length; ++i) {
GumboError* er = static_cast<GumboError*>(errors->data[i]);
GumboWellFormedError gperror;
gperror.line = er->position.line;
gperror.column = er->position.column;
// unsigned int typenum = er->type;
GumboStringBuffer text;
gumbo_string_buffer_init(&text);
gumbo_error_to_string(er, &text);
std::string errmsg(text.data, text.length);
gperror.message = QString::fromStdString(errmsg);
gumbo_string_buffer_destroy(&text);
errlist.append(gperror);
}
return errlist;
}
QList<GumboNode*> GumboInterface::get_nodes_with_comments(GumboNode * node)
{
QList<GumboNode*> nodes;
if (node->type == GUMBO_NODE_COMMENT) {
nodes.append(node);
return nodes;
}
if (node->type != GUMBO_NODE_ELEMENT) {
return nodes;
}
GumboVector* children = &node->v.element.children;
for (unsigned int i = 0; i < children->length; ++i) {
nodes.append(get_nodes_with_comments(static_cast<GumboNode*>(children->data[i])));
}
return nodes;
}
QList<GumboNode*> GumboInterface::get_element_nodes_with_prefix(GumboNode * node, const std::string& prefix)
{
QList<GumboNode*> nodes;
if (node->type != GUMBO_NODE_ELEMENT) {
return nodes;
}
std::string tag_name = get_tag_name(node);
if (tag_name.rfind(prefix, 0) == 0) {
nodes.append(node);
}
GumboVector* children = &node->v.element.children;
for (unsigned int i = 0; i < children->length; ++i) {
nodes.append(get_element_nodes_with_prefix(static_cast<GumboNode*>(children->data[i]), prefix));
}
return nodes;
}
QList<GumboNode*> GumboInterface::get_all_nodes_with_attribute(const QString& attname)
{
QList<GumboNode*> nodes;
if (!m_source.isEmpty()) {
if (m_output == NULL) {
parse();
}
nodes = get_nodes_with_attribute(m_output->root, attname.toUtf8().constData());
}
return nodes;
}
QList<GumboNode*> GumboInterface::get_nodes_with_attribute(GumboNode* node, const char * attname)
{
if (node->type != GUMBO_NODE_ELEMENT) {
return QList<GumboNode*>();
}
QList<GumboNode*> nodes;
GumboAttribute* attr = gumbo_get_attribute(&node->v.element.attributes, attname);
if (attr) {
nodes.append(node);
}
GumboVector* children = &node->v.element.children;
for (unsigned int i = 0; i < children->length; ++i) {
nodes.append(get_nodes_with_attribute(static_cast<GumboNode*>(children->data[i]), attname));
}
return nodes;
}
QStringList GumboInterface::get_all_values_for_attribute(const QString& attname)
{
QStringList attrvals;
if (!m_source.isEmpty()) {
if (m_output == NULL) {
parse();
}
attrvals = get_values_for_attr(m_output->root, attname.toUtf8().constData());
}
return attrvals;
}
QStringList GumboInterface::get_values_for_attr(GumboNode* node, const char* attr_name)
{
if (node->type != GUMBO_NODE_ELEMENT) {
return QStringList();
}
QStringList attr_vals;
GumboAttribute* attr = gumbo_get_attribute(&node->v.element.attributes, attr_name);
if (attr != NULL) {
attr_vals.append(QString::fromUtf8(attr->value));
}
GumboVector* children = &node->v.element.children;
for (unsigned int i = 0; i < children->length; ++i) {
attr_vals.append(get_values_for_attr(static_cast<GumboNode*>(children->data[i]), attr_name));
}
return attr_vals;
}
QHash<QString,QString> GumboInterface::get_attributes_of_node(GumboNode* node)
{
QHash<QString,QString> node_atts;
if (node->type != GUMBO_NODE_ELEMENT) {
return node_atts;
}
const GumboVector * attribs = &node->v.element.attributes;
for (unsigned int i=0; i< attribs->length; ++i) {
GumboAttribute* attr = static_cast<GumboAttribute*>(attribs->data[i]);
QString key = QString::fromStdString(get_attribute_name(attr));
QString val = QString::fromUtf8(attr->value);
node_atts[key] = val;
}
return node_atts;
}
QString GumboInterface::get_local_text_of_node(GumboNode* node)
{
QString node_text;
if (node->type != GUMBO_NODE_ELEMENT) {
return node_text;
}
// handle br tag as special case element tag with a text value
GumboTag tag = node->v.element.tag;
if (tag == GUMBO_TAG_BR) {
node_text = "\n";
return node_text;
}
GumboVector* children = &node->v.element.children;
for (unsigned int i = 0; i < children->length; ++i) {
GumboNode* child = static_cast<GumboNode*> (children->data[i]);
if (child->type == GUMBO_NODE_TEXT) {
node_text += QString::fromUtf8(child->v.text.text);
} else if (child->type == GUMBO_NODE_WHITESPACE) {
// keep all whitespace to keep as close to original as possible
node_text += QString::fromUtf8(child->v.text.text);
} else if (child->type == GUMBO_NODE_CDATA) {
node_text += QString::fromUtf8(child->v.text.text);
} else if (child->type == GUMBO_NODE_ELEMENT) {
node_text += get_local_text_of_node(child);
}
}
return node_text;
}
QList<GumboNode*> GumboInterface::get_all_nodes_with_tag(GumboTag tag)
{
QList<GumboTag> tags;
tags << tag;
return get_all_nodes_with_tags(tags);
}
QList<GumboNode*> GumboInterface::get_all_nodes_with_tags(const QList<GumboTag> & tags )
{
QList<GumboNode*> nodes;
if (!m_source.isEmpty()) {
if (m_output == NULL) {
parse();
}
nodes = get_nodes_with_tags(m_output->root, tags);
}
return nodes;
}
QList<GumboNode*> GumboInterface::get_nodes_with_tags(GumboNode* node, const QList<GumboTag> & tags)
{
if (node->type != GUMBO_NODE_ELEMENT) {
return QList<GumboNode*>();
}
QList<GumboNode*> nodes;
GumboTag tag = node ->v.element.tag;
if (tags.contains(tag)) {
nodes.append(node);
}
GumboVector* children = &node->v.element.children;
for (unsigned int i = 0; i < children->length; ++i) {
nodes.append(get_nodes_with_tags(static_cast<GumboNode*>(children->data[i]), tags));
}
return nodes;
}
bool GumboInterface::in_set(std::unordered_set<std::string> &s, std::string &key)
{
return s.find(key) != s.end();
}
void GumboInterface::rtrim(std::string &s)
{
s.erase(s.find_last_not_of(" \n\r\t\v\f")+1);
}
void GumboInterface::ltrim(std::string &s)
{
s.erase(0,s.find_first_not_of(" \n\r\t\v\f"));
}
void GumboInterface::ltrimnewlines(std::string &s)
{
s.erase(0,s.find_first_not_of("\n\r"));
}
// delete everything up to and including the newline
void GumboInterface::newlinetrim(std::string &s)
{
size_t pos = s.find("\n");
if (pos != std::string::npos) {
s.erase(0, pos+1);
}
}
void GumboInterface::condense_whitespace(std::string &s)
{
size_t n = s.length();
std::string val;
val.reserve(n);
std::string wspace = " \n\r\t\v\f";
char last_c = 'x';
for (size_t i=0; i < n; i++) {
char c = s.at(i);
if (wspace.find(c) != std::string::npos) {
c = ' ';
}
if ((c != ' ') || (last_c != ' ')) {
val.push_back(c);
}
last_c = c;
}
s = val;
}
void GumboInterface::replace_all(std::string &s, const char * s1, const char * s2)
{
std::string t1(s1);
size_t len = t1.length();
size_t pos = s.find(t1);
while (pos != std::string::npos) {
s.replace(pos, len, s2);
pos = s.find(t1, pos + len);
}
}
std::string GumboInterface::update_attribute_value(const std::string &attvalue)
{
std::string result = attvalue;
if (attvalue.find(":") != std::string::npos) return result;
bool has_fragment = attvalue.find("#") != std::string::npos;
QUrl href(QString::fromStdString(attvalue));
QString attpath = href.path();
// handle purely local hrefs here as they do not need to be updated at all
if (attpath.isEmpty() && has_fragment) return result;
QString fragment;
if (has_fragment) {
fragment = href.fragment();
}
QString dest_oldbkpath;
if (attpath.isEmpty()) {
dest_oldbkpath = m_currentbkpath;
} else {
dest_oldbkpath = Utility::buildBookPath(attpath, m_currentdir);
}
// note destination may not have moved but we still need to update
// the link since we may have moved
QString dest_newbkpath = m_sourceupdates.value(dest_oldbkpath, dest_oldbkpath);
if (!dest_newbkpath.isEmpty() && !m_newbookpath.isEmpty()) {
QString new_path = Utility::buildRelativePath(m_newbookpath, dest_newbkpath);
QString new_href(Utility::URLEncodePath(new_path));
if (has_fragment) {
new_href.append("#");
new_href.append(QUrl::toPercentEncoding(fragment));
}
// if empty then internal link to the top (which is best here?)
if (new_href.isEmpty()) new_href = QFileInfo(dest_newbkpath).fileName();
// if (new_href.isEmpty()) new_href="#";
result = new_href.toStdString();
}
return result;
}
std::string GumboInterface::update_style_urls(const std::string &source)
{
QString result = QString::fromStdString(source);
// Now parse the text once looking urls and replacing them where needed
QRegularExpression reference(
"(?:(?:src|background|background-image|list-style|list-style-image|border-image|border-image-source|content)\\s*:|@import)\\s*"
"[^;\\}\\(\"']*"
"(?:"
"url\\([\"']?([^\\(\\)\"']*)[\"']?\\)"
"|"
"[\"']([^\\(\\)\"']*)[\"']"
")");
int start_index = 0;
QRegularExpressionMatch mo = reference.match(result, start_index);
do {
for (int i = 1; i < reference.captureCount(); ++i) {
if (mo.captured(i).trimmed().isEmpty()) {
continue;
}
if (mo.captured(i).indexOf(":") != -1) continue;
QString apath = Utility::URLDecodePath(mo.captured(i));
QString dest_oldbkpath;
if (apath.isEmpty()) {
dest_oldbkpath = m_currentbkpath;
} else {
dest_oldbkpath = Utility::buildBookPath(apath, m_currentdir);
}
// note destination may not have moved but we still need to update
// the link
QString dest_newbkpath = m_sourceupdates.value(dest_oldbkpath, dest_oldbkpath);
if (!dest_newbkpath.isEmpty() && !m_newbookpath.isEmpty()) {
QString new_href = Utility::buildRelativePath(m_newbookpath, dest_newbkpath);
if (new_href.isEmpty()) new_href = QFileInfo(dest_newbkpath).fileName();