/
Book.cpp
1571 lines (1361 loc) · 60.3 KB
/
Book.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-2022 Kevin B. Hendricks Stratford, ON, Canada
** Copyright (C) 2009-2011 Strahinja Markovic <strahinja.markovic@gmail.com>
**
** This file is part of Sigil.
**
** Sigil 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.
**
** Sigil 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 Sigil. If not, see <http://www.gnu.org/licenses/>.
**
*************************************************************************/
#include <QtCore>
#include <QFileInfo>
#include <QFutureSynchronizer>
#include <QtConcurrent/QtConcurrent>
#include <QApplication>
#include <QProgressDialog>
#include "BookManipulation/Book.h"
#include "BookManipulation/CleanSource.h"
#include "BookManipulation/FolderKeeper.h"
#include "Parsers/GumboInterface.h"
#include "Parsers/CSSToolbox.h"
#include "Misc/TempFolder.h"
#include "Misc/Utility.h"
#include "Misc/HTMLSpellCheck.h"
#include "Misc/HTMLSpellCheckML.h"
#include "Misc/Landmarks.h"
#include "ResourceObjects/HTMLResource.h"
#include "ResourceObjects/NCXResource.h"
#include "ResourceObjects/OPFResource.h"
#include "ResourceObjects/MiscTextResource.h"
#include "sigil_constants.h"
#include "SourceUpdates/AnchorUpdates.h"
#include "SourceUpdates/PerformHTMLUpdates.h"
#include "SourceUpdates/UniversalUpdates.h"
#include "Misc/SettingsStore.h"
static const QString FIRST_CSS_NAME = "Style0001.css";
static const QString FIRST_JS_NAME = "Script0001.js";
static const QString FIRST_SVG_NAME = "Image0001.svg";
static const QString PLACEHOLDER_TEXT = "PLACEHOLDER";
static const QString EMPTY_HTML_FILE = "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n"
"<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.1//EN\"\n"
" \"http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd\">\n\n"
"<html xmlns=\"http://www.w3.org/1999/xhtml\">\n"
"<head>\n"
" <title></title>\n"
"</head>\n\n"
"<body>\n"
// The "nbsp" is here so that the user starts writing
// inside the <p> element; if it's not here, webkit
// inserts text _outside_ the <p> element
" <p> </p>\n"
"</body>\n"
"</html>";
static const QString EMPTY_HTML5_FILE = "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n"
"<!DOCTYPE html>\n\n"
"<html xmlns=\"http://www.w3.org/1999/xhtml\" xmlns:epub=\"http://www.idpf.org/2007/ops\">\n"
"<head>\n"
" <title></title>\n"
"</head>\n\n"
"<body>\n"
// The numeric entity for nbsp is here so that the user starts writing
// inside the <p> element; if it's not here, webkit
// inserts text _outside_ the <p> element, Epub3 requires numeric entities
" <p> </p>\n"
"</body>\n"
"</html>";
const QString SGC_NAV_CSS_FILENAME = "sgc-nav.css";
const QString EMPTY_NAV_FILE_START =
"<?xml version=\"1.0\" encoding=\"utf-8\"?>\n"
"<!DOCTYPE html>\n"
"<html xmlns=\"http://www.w3.org/1999/xhtml\" xmlns:epub=\"http://www.idpf.org/2007/ops\" "
"lang=\"%1\" xml:lang=\"%2\">\n"
"<head>\n"
" <title>ePub NAV</title>\n"
" <meta charset=\"utf-8\" />\n"
" <link href=\"%3\" rel=\"stylesheet\" type=\"text/css\"/>"
"</head>\n"
"<body epub:type=\"frontmatter\">\n";
const QString EMPTY_NAV_FILE_TOC =
" <nav epub:type=\"toc\" id=\"toc\" role=\"doc-toc\">\n"
" <h1>%1</h1>\n"
" <ol>\n"
" <li>\n"
" <a href=\"%2\">%3</a>\n"
" </li>\n"
" </ol>\n"
" </nav>\n";
const QString EMPTY_NAV_FILE_LANDMARKS =
" <nav epub:type=\"landmarks\" id=\"landmarks\" hidden=\"\">\n"
" <h2>%1</h2>\n"
" <ol>\n"
" <li>\n"
" <a epub:type=\"toc\" href=\"#toc\">%2</a>\n"
" </li>\n"
" </ol>\n"
" </nav>\n";
const QString EMPTY_NAV_FILE_END =
"</body>\n"
"</html>";
static const QString SGC_NAV_CSS_FILE =
"nav#landmarks {\n"
" display:none;\n"
"}\n\n"
"nav#page-list {\n"
" display:none;\n"
"}\n\n"
"ol {\n"
" list-style-type: none;\n"
"}\n\n";
const QString HTML_NAV_FILENAME = "nav.xhtml";
static const QString SGC_TOC_CSS_FILE =
"div.sgc-toc-title {\n"
" font-size: 2em;\n"
" font-weight: bold;\n"
" margin-bottom: 1em;\n"
" text-align: center;\n"
"}\n\n"
"div.sgc-toc-level-1 {\n"
" margin-left: 0em;\n"
"}\n\n"
"div.sgc-toc-level-2 {\n"
" margin-left: 2em;\n"
"}\n\n"
"div.sgc-toc-level-3 {\n"
" margin-left: 2em;\n"
"}\n\n"
"div.sgc-toc-level-4 {\n"
" margin-left: 2em;\n"
"}\n\n"
"div.sgc-toc-level-5 {\n"
" margin-left: 2em;\n"
"}\n\n"
"div.sgc-toc-level-6 {\n"
" margin-left: 2em;\n"
"}\n";
static const QString SGC_INDEX_CSS_FILE =
"div.sgc-index-title {\n"
" font-size: 2em;\n"
" font-weight: bold;\n"
" margin-bottom: 1em;\n"
" text-align: center;\n"
"}\n\n"
"div.sgc-index-body {\n"
" margin-left: -2em;\n"
"}\n\n"
"div.sgc-index-entry {\n"
" margin-top: 0em;\n"
" margin-bottom: 0.5em;\n"
" margin-left: 3.5em;\n"
" text-indent: -1.5em;\n"
"}\n\n"
"div.sgc-index-new-letter {\n"
" margin-top: 1.5em;\n"
" margin-left: 1.3em;\n"
" margin-bottom: 0.5em;\n"
" font-size: 1.5em;\n"
" font-weight: bold;\n"
" border-bottom: solid black 4px;\n"
" width: 50%;\n"
"}\n";
const QString HTML_COVER_SOURCE =
"<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"no\" ?>\n"
"<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.1//EN\"\n"
"\"http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd\">\n"
"<html xmlns=\"http://www.w3.org/1999/xhtml\">\n"
"<head>\n"
" <title>Cover</title>\n"
"</head>\n"
""
"<body>\n"
" <div style=\"text-align: center; padding: 0pt; margin: 0pt;\">\n"
" <svg xmlns=\"http://www.w3.org/2000/svg\" height=\"100%\" preserveAspectRatio=\"xMidYMid meet\" version=\"1.1\" viewBox=\"0 0 SGC_IMAGE_WIDTH SGC_IMAGE_HEIGHT\" width=\"100%\" xmlns:xlink=\"http://www.w3.org/1999/xlink\">\n"
" <image width=\"SGC_IMAGE_WIDTH\" height=\"SGC_IMAGE_HEIGHT\" xlink:href=\"SGC_IMAGE_FILENAME\"/>\n"
" </svg>\n"
" </div>\n"
"</body>\n"
"</html>\n";
const QString HTML5_COVER_SOURCE =
"<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"no\" ?>\n"
"<!DOCTYPE html>\n\n"
"<html xmlns=\"http://www.w3.org/1999/xhtml\" xmlns:epub=\"http://www.idpf.org/2007/ops\">\n"
"<head>\n"
" <title>Cover</title>\n"
"</head>\n"
""
"<body>\n"
" <div style=\"height: 100vh; text-align: center; padding: 0pt; margin: 0pt;\">\n"
" <svg xmlns=\"http://www.w3.org/2000/svg\" height=\"100%\" preserveAspectRatio=\"xMidYMid meet\" version=\"1.1\" viewBox=\"0 0 SGC_IMAGE_WIDTH SGC_IMAGE_HEIGHT\" width=\"100%\" xmlns:xlink=\"http://www.w3.org/1999/xlink\">\n"
" <image width=\"SGC_IMAGE_WIDTH\" height=\"SGC_IMAGE_HEIGHT\" xlink:href=\"SGC_IMAGE_FILENAME\"/>\n"
" </svg>\n"
" </div>\n"
"</body>\n"
"</html>\n";
Book::Book()
:
m_Mainfolder(new FolderKeeper(this)),
m_IsModified(false)
{
}
Book::~Book()
{
delete m_Mainfolder;
}
FolderKeeper *Book::GetFolderKeeper()
{
return m_Mainfolder;
}
const FolderKeeper *Book::GetFolderKeeper() const
{
return m_Mainfolder;
}
OPFResource *Book::GetOPF()
{
return m_Mainfolder->GetOPF();
}
const OPFResource *Book::GetConstOPF() const
{
return m_Mainfolder->GetOPF();
}
NCXResource *Book::GetNCX()
{
return m_Mainfolder->GetNCX();
}
const NCXResource *Book::GetConstNCX() const
{
return m_Mainfolder->GetNCX();
}
QString Book::GetPublicationIdentifier() const
{
return GetConstOPF()->GetMainIdentifierValue();
}
QList<MetaEntry> Book::GetMetadata() const
{
return GetConstOPF()->GetDCMetadata();
}
QStringList Book::GetMetadataValues(QString text) const
{
return GetConstOPF()->GetDCMetadataValues(text);
}
void Book::SetMetadata(const QList<MetaEntry> &metadata)
{
GetOPF()->SetDCMetadata(metadata);
SetModified(true);
}
QString Book::GetFirstUniqueSectionName(QString extension)
{
// If not files just return the default first name
QList<HTMLResource *> html_resources = m_Mainfolder->GetResourceTypeList<HTMLResource>(true);
if (html_resources.count() < 1) {
return FIRST_SECTION_NAME;
}
// Get the extension of the current file
QString first_html_file = html_resources.first()->Filename();
QString first_html_filename = first_html_file.left(first_html_file.lastIndexOf("."));
if (extension.isEmpty()) {
extension = first_html_file.right(first_html_file.length() - first_html_file.lastIndexOf("."));
// do not create new extensions with .xml or any other strange extension that are vague
// ie. xhtml is xml but xml need not be xhtml
if ((extension != ".xhtml") && (extension != ".htm") && (extension != ".html")) {
extension = ".xhtml";
}
// If no extension use the default first name extension
if (extension.isEmpty()) {
extension = FIRST_SECTION_NAME;
extension = extension.right(extension.length() - extension.lastIndexOf("."));
}
}
QString filename = FIRST_SECTION_PREFIX + extension;
return m_Mainfolder->GetUniqueFilenameVersion(filename);
}
QList<HTMLResource *> Book::GetHTMLResources()
{
return m_Mainfolder->GetResourceTypeList<HTMLResource>(false);
}
HTMLResource *Book::CreateNewHTMLFile(const QString &folder_path)
{
TempFolder tempfolder;
QString fullfilepath = tempfolder.GetPath() + "/" + GetFirstUniqueSectionName();
Utility::WriteUnicodeTextFile(PLACEHOLDER_TEXT, fullfilepath);
Resource * resource = m_Mainfolder->AddContentFileToFolder(fullfilepath,
true,
QString("application/xhtml+xml"),
QString(),
folder_path);
HTMLResource *html_resource = qobject_cast<HTMLResource *>(resource);
SetModified(true);
return html_resource;
}
HTMLResource *Book::CreateEmptyHTMLFile(const QString &folderpath)
{
HTMLResource *html_resource = CreateNewHTMLFile(folderpath);
QString version = html_resource->GetEpubVersion();
QString data;
QString template_path;
if (version.startsWith('2')) {
template_path = Utility::DefinePrefsDir() + "/" + "user-template2.xhtml";
data = EMPTY_HTML_FILE;
} else {
template_path = Utility::DefinePrefsDir() + "/" + "user-template3.xhtml";
data = EMPTY_HTML5_FILE;
}
if (QFile::exists(template_path)) {
data = CleanSource::Mend(Utility::ReadUnicodeTextFile(template_path), version);
}
html_resource->SetText(data);
SetModified(true);
return html_resource;
}
HTMLResource *Book::CreateEmptyNavFile(bool update_opf,
const QString &folderpath,
const QString &navname,
const QString &first_textdir)
{
bool found_css = false;
Resource * styleresource = NULL;
QList<Resource*> resources = GetFolderKeeper()->GetResourceTypeAsGenericList<CSSResource>(false);
foreach(Resource *resource, resources) {
if (resource->Filename() == SGC_NAV_CSS_FILENAME) {
styleresource = resource;
found_css = true;
break;
}
}
// If NAV CSS file does not exist look for a default file
// in preferences directory and if none create one.
if (!found_css) {
TempFolder tempfolder;
QString css_path = Utility::DefinePrefsDir() + "/" + SGC_NAV_CSS_FILENAME;
if (!QFile::exists(css_path)) {
css_path = tempfolder.GetPath() + "/" + SGC_NAV_CSS_FILENAME;
Utility::WriteUnicodeTextFile(SGC_NAV_CSS_FILE, css_path);
}
styleresource = m_Mainfolder->AddContentFileToFolder(css_path,
update_opf,
"text/css");
CSSResource *css_resource = qobject_cast<CSSResource *> (styleresource);
// Need to make sure InitialLoad is done in newly added css resource object to prevent
// blank css issues after a save to disk
if (css_resource) css_resource->InitialLoad();
}
TempFolder tempfolder;
QString fullfilepath = tempfolder.GetPath() + "/" + navname;
Utility::WriteUnicodeTextFile(PLACEHOLDER_TEXT, fullfilepath);
Resource * resource = m_Mainfolder->AddContentFileToFolder(fullfilepath,
update_opf,
"application/xhtml+xml",
QString(),
folderpath);
// get the informtion we need to correctly fill the template
QString navbookpath = resource->GetRelativePath();
QString navstylebookpath = styleresource->GetRelativePath();
QString textdir = GetFolderKeeper()->GetDefaultFolderForGroup("Text");
if (first_textdir != "\\") textdir = first_textdir;
QString first_section_bookpath = FIRST_SECTION_NAME;
if (!textdir.isEmpty()) first_section_bookpath = textdir + "/" + FIRST_SECTION_NAME;
QString stylehref = Utility::URLEncodePath(Utility::buildRelativePath(navbookpath, navstylebookpath));
QString texthref = Utility::URLEncodePath(Utility::buildRelativePath(navbookpath, first_section_bookpath));
HTMLResource * html_resource = qobject_cast<HTMLResource *>(resource);
SettingsStore ss;
QString defaultLanguage = ss.defaultMetadataLang();
QString navtitle = Landmarks::instance()->GetName("toc");
QString guidetitle = Landmarks::instance()->GetName("landmarks");
QString start = tr("Start");
QString navtext =
EMPTY_NAV_FILE_START.arg(defaultLanguage).arg(defaultLanguage).arg(stylehref) +
EMPTY_NAV_FILE_TOC.arg(navtitle).arg(texthref).arg(start) +
EMPTY_NAV_FILE_LANDMARKS.arg(guidetitle).arg(navtitle) +
EMPTY_NAV_FILE_END;
html_resource->SetText(navtext);
html_resource->SaveToDisk();
SetModified(true);
return html_resource;
}
void Book::MoveResourceAfter(HTMLResource *from_resource, HTMLResource *to_resource)
{
if (from_resource == NULL || to_resource == NULL) {
return;
}
GetOPF()->MoveReadingOrder(from_resource, to_resource);
SetModified(true);
}
HTMLResource *Book::CreateHTMLCoverFile(QString text)
{
HTMLResource *html_resource = CreateNewHTMLFile();
QString version = html_resource->GetEpubVersion();
html_resource->RenameTo(HTML_COVER_FILENAME);
if (text.isEmpty()) {
if (version.startsWith('2')) {
text = HTML_COVER_SOURCE;
} else {
text = HTML5_COVER_SOURCE;
}
}
html_resource->SetText(text);
html_resource->SaveToDisk();
// Move file to start of book.
QList<HTMLResource *> html_resources = m_Mainfolder->GetResourceTypeList<HTMLResource>(true);
html_resources.removeOne(html_resource);
html_resources.prepend(html_resource);
GetOPF()->UpdateSpineOrder(html_resources);
SetModified(true);
return html_resource;
}
CSSResource *Book::CreateHTMLTOCCSSFile()
{
CSSResource *css_resource = CreateEmptyCSSFile();
css_resource->SetText(SGC_TOC_CSS_FILE);
css_resource->SaveToDisk();
return css_resource;
}
CSSResource *Book::CreateIndexCSSFile()
{
CSSResource *css_resource = CreateEmptyCSSFile();
css_resource->SetText(SGC_INDEX_CSS_FILE);
css_resource->SaveToDisk();
return css_resource;
}
CSSResource *Book::CreateEmptyCSSFile(const QString &folderpath)
{
TempFolder tempfolder;
QString fullfilepath = tempfolder.GetPath() + "/" + m_Mainfolder->GetUniqueFilenameVersion(FIRST_CSS_NAME);
Utility::WriteUnicodeTextFile("", fullfilepath);
Resource * resource = m_Mainfolder->AddContentFileToFolder(fullfilepath,
true,
"text/css",
QString(),
folderpath);
CSSResource *css_resource = qobject_cast<CSSResource *>(resource);
QString version = css_resource->GetEpubVersion();
QString data = "";
QString template_path;
if (version.startsWith('2')) {
template_path = Utility::DefinePrefsDir() + "/" + "user-template2.css";
} else {
template_path = Utility::DefinePrefsDir() + "/" + "user-template3.css";
}
if (QFile::exists(template_path)) {
data = Utility::ReadUnicodeTextFile(template_path);
}
css_resource->SetText(data);
SetModified(true);
return css_resource;
}
MiscTextResource *Book::CreateEmptyJSFile(const QString &folderpath)
{
TempFolder tempfolder;
QString fullfilepath = tempfolder.GetPath() + "/" + m_Mainfolder->GetUniqueFilenameVersion(FIRST_JS_NAME);
Utility::WriteUnicodeTextFile("", fullfilepath);
Resource * resource = m_Mainfolder->AddContentFileToFolder(fullfilepath,
true,
"application/javascript",
QString(),
folderpath);
MiscTextResource *js_resource = qobject_cast<MiscTextResource *>(resource);
SetModified(true);
return js_resource;
}
SVGResource *Book::CreateEmptySVGFile(const QString& folderpath)
{
TempFolder tempfolder;
QString fullfilepath = tempfolder.GetPath() + "/" + m_Mainfolder->GetUniqueFilenameVersion(FIRST_SVG_NAME);
Utility::WriteUnicodeTextFile("", fullfilepath);
Resource * resource = m_Mainfolder->AddContentFileToFolder(fullfilepath,
true,
"image/svg+xml",
QString(),
folderpath);
SVGResource *svg_resource = qobject_cast<SVGResource *>(resource);
SetModified(true);
return svg_resource;
}
HTMLResource *Book::CreateSectionBreakOriginalResource(const QString &content, HTMLResource *originating_resource)
{
if (originating_resource == NULL)
return NULL;
const QString originating_bookpath = originating_resource->GetRelativePath();
// use this to get file extension for renaming purposes
const QString originating_filename = originating_resource->Filename();
// use this to get folder path for new resource
const QString folder_path = Utility::startingDir(originating_bookpath);
int reading_order = GetOPF()->GetReadingOrder(originating_resource);
Q_ASSERT(reading_order >= 0);
QList<HTMLResource *> html_resources = m_Mainfolder->GetResourceTypeList<HTMLResource>(true);
QString old_extension = originating_filename.right(originating_filename.length() - originating_filename.lastIndexOf("."));
originating_resource->RenameTo(GetFirstUniqueSectionName(old_extension));
HTMLResource *new_resource = CreateNewHTMLFile(folder_path);
QString version = GetOPF()->GetEpubVersion();
new_resource->RenameTo(originating_filename);
new_resource->SetText(CleanSource::Mend(content, version));
m_Mainfolder->SuspendWatchingResources();
new_resource->SaveToDisk();
m_Mainfolder->ResumeWatchingResources();
html_resources.insert(reading_order, new_resource);
GetOPF()->UpdateSpineOrder(html_resources);
// Update references between the two new files. Since they used to be one single file we can
// assume that each id is unique (if they aren't then the references were broken anyway).
QList<HTMLResource *> new_files;
new_files.append(originating_resource);
// The originating resource must always be first in the list
new_files.append(new_resource);
AnchorUpdates::UpdateAllAnchorsWithIDs(new_files);
// Remove the original and new files from the list of html resources as we want to scan all
// the other files for external references to the original file.
html_resources.removeOne(originating_resource);
html_resources.removeOne(new_resource);
// Now, update references to the original file that are made in other files.
// We can't assume that ids are unique in this case, and so need to use a different mechanism.
AnchorUpdates::UpdateExternalAnchors(html_resources, originating_bookpath, new_files);
// Update TOC entries as well if an NCX exists:
NCXResource * ncx_resource = GetNCX();
if (ncx_resource) {
AnchorUpdates::UpdateTOCEntries(ncx_resource, originating_bookpath, new_files);
}
SetModified(true);
return new_resource;
}
void Book::CreateNewSections(const QStringList &new_sections, HTMLResource *original_resource)
{
const QString originating_bookpath = original_resource->GetRelativePath();
int original_position = GetOPF()->GetReadingOrder(original_resource);
Q_ASSERT(original_position >= 0);
QString new_file_prefix = QFileInfo(original_resource->Filename()).baseName();
QString file_extension = "." + QFileInfo(original_resource->Filename()).suffix();
QString folder_path = Utility::startingDir(original_resource->GetRelativePath());
if (new_sections.isEmpty()) {
return;
}
TempFolder tempfolder;
QFutureSynchronizer<NewSectionResult> sync;
QList<HTMLResource *> html_resources = m_Mainfolder->GetResourceTypeList<HTMLResource>(true);
// A list of all the files that have not been involved in the split.
// This will be used later when anchors are updated.
QList<HTMLResource *> other_files = html_resources;
other_files.removeOne(original_resource);
int next_reading_order;
if (original_position == -1) {
next_reading_order = m_Mainfolder->GetHighestReadingOrder() + 1;
} else {
next_reading_order = original_position + 1;
}
for (int i = 0; i < new_sections.count(); ++i) {
int reading_order = next_reading_order + i;
NewSection sectionInfo;
sectionInfo.source = new_sections.at(i);
sectionInfo.reading_order = reading_order;
sectionInfo.temp_folder_path = tempfolder.GetPath();
sectionInfo.new_file_prefix = new_file_prefix;
sectionInfo.file_suffix = i;
sectionInfo.file_extension = file_extension;
sectionInfo.folder_path = folder_path;
sync.addFuture(
#if QT_VERSION < QT_VERSION_CHECK(6, 0, 0)
QtConcurrent::run(this, &Book::CreateANewSection, sectionInfo)
#else
QtConcurrent::run(&Book::CreateANewSection, this, sectionInfo)
//QtConcurrent::run(this, [this, sectionInfo] { &Book::CreateOneNewSection(sectionInfo);
#endif
);
}
sync.waitForFinished();
QList<HTMLResource *> new_files;
// the original_resource must always be first in the new_files list
new_files.append(original_resource);
QList<QFuture<NewSectionResult>> futures = sync.futures();
if (original_position == -1) {
// Add new sections to the end of the book
for (int i = 0; i < futures.count(); ++i) {
html_resources.append(futures.at(i).result().created_section);
new_files.append(futures.at(i).result().created_section);
}
} else {
// Insert the new files at the correct positions in the list
// The new files need to be inserted in order from first to last
for (int i = 0; i < new_sections.count(); ++i) {
int reading_order = next_reading_order + i;
if (futures.at(i).result().reading_order == reading_order) {
html_resources.insert(reading_order , futures.at(i).result().created_section);
new_files.append(futures.at(i).result().created_section);
} else {
// This is security code to protect against any mangling of the futures list by Qt
for (int j = 0 ; j < futures.count() ; ++j) {
if (futures.at(j).result().reading_order == reading_order) {
html_resources.insert(reading_order , futures.at(j).result().created_section);
new_files.append(futures.at(j).result().created_section);
break;
}
}
}
}
}
// Update anchor references between fragment ids in the new files. Since these all came from one single
// file it's safe to assume that the fragment ids are all unique (since otherwise the references would be broken).
AnchorUpdates::UpdateAllAnchorsWithIDs(new_files);
// Now, update references to the original file that are made in other files.
// We can't assume that ids are unique in this case, and so need to use a different mechanism.
AnchorUpdates::UpdateExternalAnchors(other_files, original_resource->GetRelativePath(), new_files);
// Update TOC entries as well if an NCX exists, they are optional on epub3
NCXResource * ncx_resource = GetNCX();
if (ncx_resource) {
AnchorUpdates::UpdateTOCEntries(ncx_resource, originating_bookpath, new_files);
}
GetOPF()->UpdateSpineOrder(html_resources);
SetModified(true);
}
bool Book::IsDataWellFormed(HTMLResource *html_resource)
{
XhtmlDoc::WellFormedError error = XhtmlDoc::WellFormedErrorForSource(html_resource->GetText(),
html_resource->GetEpubVersion());
return error.line == -1;
}
bool Book::IsDataOnDiskWellFormed(HTMLResource *html_resource)
{
XhtmlDoc::WellFormedError error = XhtmlDoc::WellFormedErrorForSource(Utility::ReadUnicodeTextFile(html_resource->GetFullPath()),
html_resource->GetEpubVersion());
return error.line == -1;
}
bool Book::RenameClassInHTML(const QString css_bookpath, const QString oldname, const QString newname)
{
const QList<HTMLResource *> html_resources = m_Mainfolder->GetResourceTypeList<HTMLResource>(false);
QFuture< bool > rfuture;
rfuture = QtConcurrent::mapped(html_resources, std::bind(Book::RenameClassInHTMLFileMapped,
std::placeholders::_1,
css_bookpath,
oldname,
newname));
bool result = true;
for (int i = 0; i < rfuture.results().count(); i++) {
result = result && rfuture.resultAt(i);
}
return result;
}
bool Book::RenameClassInHTMLFileMapped(HTMLResource* html_resource,
const QString css_bookpath,
const QString oldname,
const QString newname)
{
QStringList linked_stylesheets = html_resource->GetLinkedStylesheets();
QString xhtmltext = html_resource->GetText();
if (linked_stylesheets.contains(css_bookpath)) {
QWriteLocker locker(&html_resource->GetLock());
CSSToolbox tb;
QString newtext = tb.rename_class_in_text(oldname, newname, xhtmltext);
if (xhtmltext != newtext) {
html_resource->SetText(newtext);
}
}
return true;
}
void Book::ReformatAllHTML(bool to_valid)
{
QApplication::setOverrideCursor(Qt::WaitCursor);
SaveAllResourcesToDisk();
QList<HTMLResource *> html_resources = m_Mainfolder->GetResourceTypeList<HTMLResource>(true);
bool book_modified = CleanSource::ReformatAll(html_resources, to_valid ? CleanSource::Mend : CleanSource::MendPrettify);
if (book_modified) {
SetModified();
}
QApplication::restoreOverrideCursor();
}
Resource *Book::PreviousResource(Resource *resource)
{
QList<HTMLResource *> html_resources = m_Mainfolder->GetResourceTypeList<HTMLResource>(true);
HTMLResource *html_resource = qobject_cast<HTMLResource *>(resource);
int previous_file_reading_order = html_resources.indexOf(html_resource) - 1;
if (previous_file_reading_order < 0) {
previous_file_reading_order = 0;
}
HTMLResource *previous_html = html_resources[ previous_file_reading_order ];
return qobject_cast<Resource *>(previous_html);
}
QHash <QString, QList<XhtmlDoc::XMLElement>> Book::GetLinkElements()
{
QHash<QString, QList<XhtmlDoc::XMLElement>> links_in_html;
const QList<HTMLResource *> html_resources = m_Mainfolder->GetResourceTypeList<HTMLResource>(false);
QFuture<std::tuple<QString, QList<XhtmlDoc::XMLElement>>> future = QtConcurrent::mapped(html_resources, GetLinkElementsInHTMLFileMapped);
for (int i = 0; i < future.results().count(); i++) {
QString bookpath;
QList<XhtmlDoc::XMLElement> links;
std::tie(bookpath, links) = future.resultAt(i);
// Each target entry has a list of filenames that contain it
links_in_html[bookpath] = links;
}
return links_in_html;
}
std::tuple<QString, QList<XhtmlDoc::XMLElement>> Book::GetLinkElementsInHTMLFileMapped(HTMLResource *html_resource)
{
return std::make_tuple(html_resource->GetRelativePath(),
XhtmlDoc::GetTagsInDocument(html_resource->GetText(), "a"));
}
QStringList Book::GetStyleUrlsInHTMLFiles()
{
QStringList styles_in_html;
const QList<HTMLResource *> html_resources = m_Mainfolder->GetResourceTypeList<HTMLResource>(false);
QFuture<std::tuple<QString, QStringList>> future = QtConcurrent::mapped(html_resources, GetStyleUrlsInHTMLFileMapped);
for (int i = 0; i < future.results().count(); i++) {
QString bookpath;
QStringList style_bookpaths;
std::tie(bookpath, style_bookpaths) = future.resultAt(i);
// Each target entry has a list of filenames that contain it
styles_in_html.append(style_bookpaths);
}
return styles_in_html;
}
std::tuple<QString, QStringList> Book::GetStyleUrlsInHTMLFileMapped(HTMLResource *html_resource)
{
QString html_bookpath = html_resource->GetRelativePath();
QString startdir = html_resource->GetFolder();
// we need to convert this hreflist to bookpaths if possible
QStringList urllist = XhtmlDoc::GetAllDescendantStyleUrls(html_resource->GetText());
QStringList bookpaths;
QRegularExpression url_file_search("url\\s*\\(\\s*['\"]?([^\\(\\)'\"]*)[\"']?\\)");
foreach (QString url, urllist) {
QRegularExpressionMatch match = url_file_search.match(url);
if (match.hasMatch()) {
QString ahref = match.captured(1);
if (ahref.indexOf(":") == -1) {
bookpaths << Utility::buildBookPath(ahref, startdir);
}
}
}
return std::make_tuple(html_bookpath, bookpaths);
}
QHash<QString, QStringList> Book::GetIdsInHTMLFiles()
{
QHash<QString, QStringList> ids_in_html;
const QList<HTMLResource *> html_resources = m_Mainfolder->GetResourceTypeList<HTMLResource>(false);
QFuture<std::tuple<QString, QStringList>> future = QtConcurrent::mapped(html_resources, GetIdsInHTMLFileMapped);
for (int i = 0; i < future.results().count(); i++) {
QString bookpath;
QStringList ids;
std::tie(bookpath, ids) = future.resultAt(i);
// Each target entry has a list of filenames that contain it
ids_in_html[bookpath] = ids;
}
return ids_in_html;
}
std::tuple<QString, QStringList> Book::GetIdsInHTMLFileMapped(HTMLResource *html_resource)
{
return std::make_tuple(html_resource->GetRelativePath(),
XhtmlDoc::GetAllDescendantIDs(html_resource->GetText()));
}
QStringList Book::GetIdsInHTMLFile(HTMLResource *html_resource)
{
return XhtmlDoc::GetAllDescendantIDs(html_resource->GetText());
}
QStringList Book::GetIdsInHrefs()
{
QStringList ids;
QHash<QString, QStringList> hrefs = GetHrefsInHTMLFiles();
QHashIterator<QString, QStringList> it(hrefs);
while (it.hasNext()) {
it.next();
foreach(QString href, it.value()) {
if (href.contains('#')) {
href = href.right(href.length() - href.indexOf("#") - 1);
if (!href.isEmpty() && !ids.contains(href)) {
ids.append(href);
}
}
}
}
// Return the list of ids used in hrefs in the book
return ids;
}
QHash<QString, QStringList> Book::GetHrefsInHTMLFiles()
{
QHash<QString, QStringList> hrefs_in_html;
const QList<HTMLResource *> html_resources = m_Mainfolder->GetResourceTypeList<HTMLResource>(false);
QFuture<std::tuple<QString, QStringList>> future = QtConcurrent::mapped(html_resources, GetHrefsInHTMLFileMapped);
for (int i = 0; i < future.results().count(); i++) {
QString bookpath;
QStringList hrefs;
std::tie(bookpath, hrefs) = future.resultAt(i);
// Each target entry has a list of filenames that contain it
hrefs_in_html[bookpath] = hrefs;
}
return hrefs_in_html;
}
std::tuple<QString, QStringList> Book::GetHrefsInHTMLFileMapped(HTMLResource *html_resource)
{
return std::make_tuple(html_resource->GetRelativePath(),
XhtmlDoc::GetAllDescendantHrefs(html_resource->GetText()));
}
QStringList Book::GetClassesInHTMLFile(HTMLResource *html_resource)
{
return XhtmlDoc::GetAllDescendantClasses(html_resource->GetText());
}
QHash<QString, QStringList> Book::GetImagesInHTMLFiles()
{
QHash<QString, QStringList> images_in_html;
const QList<HTMLResource *> html_resources = m_Mainfolder->GetResourceTypeList<HTMLResource>(false);
QFuture<std::tuple<QString, QStringList>> future = QtConcurrent::mapped(html_resources, GetImagesInHTMLFileMapped);
for (int i = 0; i < future.results().count(); i++) {
QString bookpath;
QStringList image_files;
std::tie(bookpath, image_files) = future.resultAt(i);
images_in_html[bookpath] = image_files;
}
return images_in_html;
}
QHash< QString, std::pair<int,int> > Book::GetSpellWordCountsInHTMLFiles()
{
QHash< QString, std::pair<int,int> > words_in_html;
const QList<HTMLResource *> html_resources = m_Mainfolder->GetResourceTypeList<HTMLResource>(false);
QFuture<std::tuple<QString, std::pair<int,int> > > future = QtConcurrent::mapped(html_resources, GetWordCountsInHTMLFileMapped);
for (int i = 0; i < future.results().count(); i++) {
QString bookpath;
std::pair<int, int> word_counts;
std::tie(bookpath, word_counts) = future.resultAt(i);
words_in_html[bookpath] = word_counts;
}
return words_in_html;
}
std::tuple<QString, std::pair<int,int> > Book::GetWordCountsInHTMLFileMapped(HTMLResource *html_resource)
{
QString html_bookpath = html_resource->GetRelativePath();
std::pair<int,int> counts;
counts.first = HTMLSpellCheck::CountAllWords(html_resource->GetText());
counts.second = HTMLSpellCheck::CountMisspelledWords(html_resource->GetText());
return std::make_tuple(html_bookpath, counts);
}
QHash<QString, QStringList> Book::GetVideoInHTMLFiles()
{
QHash<QString, QStringList> video_in_html;
const QList<HTMLResource *> html_resources = m_Mainfolder->GetResourceTypeList<HTMLResource>(false);
QFuture<std::tuple<QString, QStringList>> future = QtConcurrent::mapped(html_resources, GetVideoInHTMLFileMapped);
for (int i = 0; i < future.results().count(); i++) {
QString bookpath;
QStringList video_files;
std::tie(bookpath, video_files) = future.resultAt(i);
video_in_html[bookpath] = video_files;
}
return video_in_html;
}
QHash<QString, QStringList> Book::GetAudioInHTMLFiles()
{
QHash<QString, QStringList> audio_in_html;
const QList<HTMLResource *> html_resources = m_Mainfolder->GetResourceTypeList<HTMLResource>(false);
QFuture<std::tuple<QString, QStringList>> future = QtConcurrent::mapped(html_resources, GetAudioInHTMLFileMapped);
for (int i = 0; i < future.results().count(); i++) {
QString bookpath;
QStringList audio_files;
std::tie(bookpath, audio_files) = future.resultAt(i);
audio_in_html[bookpath] = audio_files;
}
return audio_in_html;
}
QHash<QString, QStringList> Book::GetHTMLFilesUsingMedia()
{
QHash<QString, QStringList> html_files;
const QList<HTMLResource *> html_resources = m_Mainfolder->GetResourceTypeList<HTMLResource>(false);
QFuture<std::tuple<QString, QStringList>> future = QtConcurrent::mapped(html_resources, GetMediaInHTMLFileMapped);
for (int i = 0; i < future.results().count(); i++) {
QString html_bookpath;
QStringList media_bookpaths;