/
MainWindow.cpp
6303 lines (5447 loc) · 242 KB
/
MainWindow.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 Canada
** Copyright (C) 2015-2020 Doug Massay
** Copyright (C) 2012-2015 John Schember <john@nachtimwald.com>
** Copyright (C) 2012-2013 Dave Heiland
** 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/QFileInfo>
#include <QtCore/QThread>
#include <QtCore/QTimer>
#include <QtConcurrent>
#include <QFuture>
#include <QtGui/QDesktopServices>
#include <QtGui/QImage>
#include <QDesktopWidget>
#include <QGuiApplication>
#include <QScreen>
#include <QtWidgets/QFileDialog>
#include <QtWidgets/QInputDialog>
#include <QtWidgets/QMessageBox>
#include <QtWidgets/QProgressDialog>
#include <QtWidgets/QToolBar>
#include <QtWebEngineWidgets/QWebEngineSettings>
#include <QRegularExpression>
#include <QRegularExpressionMatch>
#ifdef Q_OS_WIN32
#include <QtWinExtras>
#endif
#include <QString>
#include <QStringList>
#include <QFont>
#include <QFontMetrics>
#include <QEvent>
#include <QWindowStateChangeEvent>
#include <QStyleFactory>
#include <QStyle>
#include <QDebug>
#include "BookManipulation/CleanSource.h"
#include "BookManipulation/Index.h"
#include "BookManipulation/FolderKeeper.h"
#include "Dialogs/About.h"
#include "Dialogs/ClipEditor.h"
#include "Dialogs/ClipboardHistorySelector.h"
#include "Dialogs/DeleteStyles.h"
#include "Dialogs/EditTOC.h"
#include "Dialogs/EmptyLayout.h"
#include "Dialogs/HeadingSelector.h"
#include "Dialogs/LinkStylesheets.h"
#include "Dialogs/ManageRepos.h"
#include "Dialogs/MetaEditor.h"
#include "Dialogs/PluginRunner.h"
#include "Dialogs/Preferences.h"
#include "Dialogs/RepoLog.h"
#include "Dialogs/ChgViewer.h"
#include "Dialogs/CPCompare.h"
#include "Dialogs/SearchEditor.h"
#include "Dialogs/SelectCharacter.h"
#include "Dialogs/SelectCheckpoint.h"
#include "Dialogs/SelectFiles.h"
#include "Dialogs/SelectHyperlink.h"
#include "Dialogs/SelectId.h"
#include "Dialogs/SelectIndexTitle.h"
#include "Exporters/ExportEPUB.h"
#include "Exporters/ExporterFactory.h"
#include "Importers/ImporterFactory.h"
#include "Importers/ImportHTML.h"
#include "MainUI/BookBrowser.h"
#include "MainUI/ClipsWindow.h"
#include "MainUI/MainWindow.h"
#include "MainUI/FindReplace.h"
#include "MainUI/PreviewWindow.h"
#include "MainUI/TableOfContents.h"
#include "MainUI/ValidationResultsView.h"
#include "Misc/HTMLSpellCheck.h"
#include "Misc/KeyboardShortcutManager.h"
#include "Misc/Landmarks.h"
#include "Misc/MediaTypes.h"
#include "Misc/OpenExternally.h"
#include "Misc/Plugin.h"
#include "Misc/PluginDB.h"
#include "Misc/PythonRoutines.h"
#include "Misc/SettingsStore.h"
#include "Misc/SleepFunctions.h"
#include "Misc/SpellCheck.h"
#include "Misc/TempFolder.h"
#include "Misc/TOCHTMLWriter.h"
#include "Misc/Utility.h"
#include "MiscEditors/IndexHTMLWriter.h"
#include "ResourceObjects/HTMLResource.h"
#include "ResourceObjects/NCXResource.h"
#include "ResourceObjects/OPFResource.h"
#include "ResourceObjects/NavProcessor.h"
#include "sigil_constants.h"
#include "sigil_exception.h"
#include "SourceUpdates/LinkUpdates.h"
#include "SourceUpdates/WordUpdates.h"
#include "Tabs/FlowTab.h"
#include "Tabs/CSSTab.h"
#include "Tabs/OPFTab.h"
#include "Tabs/TabManager.h"
#include "MainUI/MainApplication.h"
#define DWINGEO if(0)
#define DBG if(0)
static const int TEXT_ELIDE_WIDTH = 300;
static const QString SETTINGS_GROUP = "mainwindow";
const float ZOOM_STEP = 0.1f;
const float ZOOM_MIN = 0.09f;
const float ZOOM_MAX = 5.0f;
const float ZOOM_NORMAL = 1.0f;
static const int ZOOM_SLIDER_MIN = 0;
static const int ZOOM_SLIDER_MAX = 1000;
static const int ZOOM_SLIDER_MIDDLE = 500;
static const int ZOOM_SLIDER_WIDTH = 140;
static const QString DONATE = "http://sigil-ebook.com/donate";
static const QString SIGIL_WEBSITE = "http://sigil-ebook.com";
static const QString USER_GUIDE_URL = "http://sigil-ebook.com/documentation";
static const QString BOOK_BROWSER_NAME = "bookbrowser";
static const QString FIND_REPLACE_NAME = "findreplace";
static const QString TAB_MANAGER_NAME = "tabmgr";
static const QString VALIDATION_RESULTS_VIEW_NAME = "validationresultsname";
static const QString TABLE_OF_CONTENTS_NAME = "tableofcontents";
static const QString PREVIEW_WINDOW_NAME = "previewwindow";
static const QString CLIPS_WINDOW_NAME = "clipswindow";
static const QString FRAME_NAME = "managerframe";
static const QString TAB_STYLE_SHEET = "#managerframe {border-top: 0px solid white;"
"border-left: 1px solid grey;"
"border-right: 1px solid grey;"
"border-bottom: 1px solid grey;} ";
static const QString HTML_TOC_FILE = "TOC.xhtml";
static const QString HTML_INDEX_FILE = "Index.xhtml";
const QString HTML_COVER_FILENAME = "cover.xhtml";
// External constant (sigil_contants.h) used to consolidate the upper clipboard history limit.
const int CLIPBOARD_HISTORY_MAX = 20;
static const QStringList SUPPORTED_SAVE_TYPE = QStringList() << "epub";
static const QString DEFAULT_FILENAME = "untitled.epub";
static const QString CUSTOM_PREVIEW_STYLE_FILENAME = "custom_preview_style.css";
QStringList MainWindow::s_RecentFiles = QStringList();
MainWindow::MainWindow(const QString &openfilepath,
const QString version,
bool is_internal,
QWidget *parent,
Qt::WindowFlags flags)
:
QMainWindow(parent, flags),
m_LastOpenFileWarnings(QStringList()),
m_IsInitialLoad(true),
m_CurrentFilePath(QString()),
m_CurrentFileName(QString()),
m_Book(new Book()),
m_LastFolderOpen(QString()),
m_SaveACopyFilename(QString()),
m_LastInsertedFile(QString()),
m_TabManager(new TabManager(this)),
m_BookBrowser(NULL),
m_Clips(NULL),
m_FindReplace(new FindReplace(this)),
m_TableOfContents(NULL),
m_ValidationResultsView(NULL),
m_PreviewWindow(NULL),
m_slZoomSlider(NULL),
m_lbZoomLabel(NULL),
c_SaveFilters(GetSaveFiltersMap()),
c_LoadFilters(GetLoadFiltersMap()),
m_headingActionGroup(new QActionGroup(this)),
m_casingChangeGroup(new QActionGroup(this)),
m_SearchEditor(new SearchEditor(this)),
m_ClipEditor(new ClipEditor(this)),
m_IndexEditor(new IndexEditor(this)),
m_SpellcheckEditor(new SpellcheckEditor(this)),
m_SelectCharacter(new SelectCharacter(this)),
m_ViewImage(new ViewImage(this)),
m_Reports(new Reports(this)),
m_preserveHeadingAttributes(true),
m_LinkOrStyleBookmark(new LocationBookmark()),
m_ClipboardHistorySelector(new ClipboardHistorySelector(this)),
m_ClipboardHistoryLimit(CLIPBOARD_HISTORY_MAX),
m_LastPasteTarget(NULL),
m_ZoomPreview(false),
m_LastWindowSize(QByteArray()),
m_LastState(QByteArray()),
m_FirstTime(true),
m_PendingLastSizeUpdate(false),
m_SaveLastEnabled(false),
m_PreviousHTMLResource(NULL),
m_PreviousHTMLText(QString()),
m_PreviousHTMLLocation(QList<ElementIndex>()),
m_menuPluginsInput(NULL),
m_menuPluginsOutput(NULL),
m_menuPluginsEdit(NULL),
m_menuPluginsValidation(NULL),
m_pluginList(QStringList()),
m_SaveCSS(false),
m_IsClosing(false)
{
createJumpList();
ui.setupUi(this);
// Telling Qt to delete this window
// from memory when it is closed
setAttribute(Qt::WA_DeleteOnClose);
ExtendUI();
PlatformSpecificTweaks();
// Needs to come before signals connect and after ExtendUI
// (avoiding side-effects)
ReadSettings();
// Ensure the UI is properly set to the saved view state.
SetupPreviewTimer();
ConnectSignalsToSlots();
CreateRecentFilesActions();
UpdateRecentFileActions();
ChangeSignalsWhenTabChanges(NULL, m_TabManager->GetCurrentContentTab());
LoadInitialFile(openfilepath, version, is_internal);
loadPluginsMenu();
}
MainWindow::~MainWindow()
{
// Make sure that any modeless windows that are visible are closed first
// to prevent crashes on Windows.
if (m_SelectCharacter && m_SelectCharacter->isVisible()) {
m_SelectCharacter->close();
m_SelectCharacter = NULL;
}
if (m_ViewImage && m_ViewImage->isVisible()) {
m_ViewImage->close();
m_ViewImage = NULL;
}
#ifdef Q_OS_MAC // speeds cleaningup of old modal dialogs
if (m_ClipboardHistorySelector) delete m_ClipboardHistorySelector;
if (m_LinkOrStyleBookmark) delete m_LinkOrStyleBookmark;
if (m_Reports) delete m_Reports;
if (m_ViewImage) delete m_ViewImage;
if (m_SelectCharacter) delete m_SelectCharacter;
if (m_SpellcheckEditor) delete m_SpellcheckEditor;
if (m_IndexEditor) delete m_IndexEditor;
if (m_ClipEditor) delete m_ClipEditor;
if (m_SearchEditor) delete m_SearchEditor;
if (m_casingChangeGroup) delete m_casingChangeGroup;
if (m_headingActionGroup) delete m_headingActionGroup;
if (m_lbZoomLabel) delete m_lbZoomLabel;
if (m_slZoomSlider) delete m_slZoomSlider;
if (m_ValidationResultsView) delete m_ValidationResultsView;
if (m_TableOfContents) delete m_TableOfContents;
if (m_FindReplace) delete m_FindReplace;
if (m_Clips) delete m_Clips;
if (m_BookBrowser) delete m_BookBrowser;
if (m_TabManager) delete m_TabManager;
if (m_PreviewWindow) delete m_PreviewWindow;
#endif
}
#if 0
// The problem is this routine does not help!
void MainWindow::maybe_fixup_dockwidget_geometry(QDockWidget* dw)
{
QRect screen_rect = qApp->desktop()->availableGeometry(dw);
qDebug() << "dockwidget screen: " << screen_rect;
qDebug() << "dockwidget widget: " << dw->geometry() << dw->isFloating();
qDebug() << "mainwindow screen: " << qApp->desktop()->availableGeometry(this);
if (dw->isFloating()) {
if (!dw->geometry().intersects(screen_rect)) {
qDebug() << "on a no longer available screen";
// shrink it to fit the current screen and move it here
int w = std::min(dw->width(), screen_rect.width() - 10);
int h = std::min(dw->height(), screen_rect.height() - 10);
dw->resize(w, h);
dw->move((screen_rect.width() - w)/2, (screen_rect.height() - h)/2);
}
}
}
#endif
void MainWindow::createJumpList()
{
#ifdef Q_OS_WIN32
QWinJumpList jumplist;
jumplist.recent()->setVisible(true);
#endif
}
// Note on Mac OS X you may only add a QMenu or SubMenu to the MenuBar Once!
// Actions can be removed
void MainWindow::loadPluginsMenu()
{
PluginDB *pdb = PluginDB::instance();
m_menuPlugins = ui.menuPlugins;
m_actionManagePlugins = ui.actionManage_Plugins;
unloadPluginsMenu();
connect(m_actionManagePlugins, SIGNAL(triggered()), this, SLOT(ManagePluginsDialog()));
// Setup up for quick launch of plugins
int i = 0;
foreach(QAction* pa, m_qlactions){
// Use the new signal/slot syntax and use a lambda to
// eliminate the need for the obsoleted QSignalMapper.
// [captured variables]() {...anonymous processing to do...;}
connect(pa, &QAction::triggered, this, [this,i]() {
MainWindow::QuickLaunchPlugin(i);
});
i++;
}
QHash<QString, Plugin *> plugins = pdb->all_plugins();
// first set default icons for quick launch plugin buttons
// Do we need this? Aren't these set in Form_Files/main.ui
i = 1;
foreach(QAction* pa, m_qlactions) {
QString resource = ":/main/plugin_48px_" + QString::number(i) + "pips.png";
pa->setIcon(QIcon(resource));
i++;
}
// now set any custom icons
SettingsStore ss;
QStringList namemap = ss.pluginMap();
int pos = 0;
foreach (QString name, namemap) {
if (!name.isEmpty()) {
Plugin * p = plugins.value(name);
if (p != NULL) {
QString iconpath = p->get_iconpath();
if (!iconpath.isEmpty()) {
m_qlactions.at(pos)->setIcon(QIcon(iconpath));
}
}
}
pos++;
}
updateToolTipsOnPluginIcons();
QStringList keys = plugins.keys();
keys.sort(Qt::CaseInsensitive);
m_pluginList = keys;
foreach(QString key, keys) {
Plugin *p = plugins.value(key);
if (p == NULL) {
continue;
}
QString pname = p->get_name();
QString ptype = p->get_type();
if (ptype == "input") {
if (m_menuPluginsInput == NULL) {
m_menuPluginsInput = m_menuPlugins->addMenu(tr("Input"));
connect(m_menuPluginsInput, SIGNAL(triggered(QAction *)), this, SLOT(runPlugin(QAction *)));
}
m_menuPluginsInput->addAction(pname);
} else if (ptype == "output") {
if (m_menuPluginsOutput == NULL) {
m_menuPluginsOutput = m_menuPlugins->addMenu(tr("Output"));
connect(m_menuPluginsOutput, SIGNAL(triggered(QAction *)), this, SLOT(runPlugin(QAction *)));
}
m_menuPluginsOutput->addAction(pname);
} else if (ptype == "edit") {
if (m_menuPluginsEdit == NULL) {
m_menuPluginsEdit = m_menuPlugins->addMenu(tr("Edit"));
connect(m_menuPluginsEdit, SIGNAL(triggered(QAction *)), this, SLOT(runPlugin(QAction *)));
}
m_menuPluginsEdit->addAction(pname);
} else if (ptype == "validation") {
if (m_menuPluginsValidation == NULL) {
m_menuPluginsValidation = m_menuPlugins->addMenu(tr("Validation"));
connect(m_menuPluginsValidation, SIGNAL(triggered(QAction *)), this, SLOT(runPlugin(QAction *)));
}
m_menuPluginsValidation->addAction(pname);
}
}
}
// Keeps the Plugins menu and ManagePlugins submenu arround even if no plugins added yet
void MainWindow::unloadPluginsMenu()
{
if (m_menuPlugins != NULL) {
if (m_menuPluginsInput != NULL) {
disconnect(m_menuPluginsInput, SIGNAL(triggered(QAction *)), this, SLOT(runPlugin(QAction *)));
m_menuPluginsInput->clear();
m_menuPlugins->removeAction(m_menuPluginsInput->menuAction());
m_menuPluginsInput = NULL;
}
if (m_menuPluginsOutput != NULL) {
disconnect(m_menuPluginsOutput, SIGNAL(triggered(QAction *)), this, SLOT(runPlugin(QAction *)));
m_menuPluginsOutput->clear();
m_menuPlugins->removeAction(m_menuPluginsOutput->menuAction());
m_menuPluginsOutput = NULL;
}
if (m_menuPluginsEdit != NULL) {
disconnect(m_menuPluginsEdit, SIGNAL(triggered(QAction *)), this, SLOT(runPlugin(QAction *)));
m_menuPluginsEdit->clear();
m_menuPlugins->removeAction(m_menuPluginsEdit->menuAction());
m_menuPluginsEdit = NULL;
}
if (m_menuPluginsValidation != NULL) {
disconnect(m_menuPluginsValidation, SIGNAL(triggered(QAction *)), this, SLOT(runPlugin(QAction *)));
m_menuPluginsValidation->clear();
m_menuPlugins->removeAction(m_menuPluginsValidation->menuAction());
m_menuPluginsValidation = NULL;
}
}
disconnect(m_actionManagePlugins, SIGNAL(triggered()), this, SLOT(ManagePluginsDialog()));
foreach(QAction * pa, m_qlactions) {
disconnect(pa, &QAction::triggered, this, nullptr);
}
}
void MainWindow::StandardizeEpub()
{
SaveTabData();
// ask to be sure
QMessageBox::StandardButton button_pressed;
button_pressed = QMessageBox::warning(this, tr("Sigil"),
tr("Are you sure you want to restructure this epub?\nThis action cannot be reversed."),
QMessageBox::Ok | QMessageBox::Cancel);
if (button_pressed != QMessageBox::Ok) {
return;
}
QApplication::setOverrideCursor(Qt::WaitCursor);
// perform well-formed check on all the html resources
QList<HTMLResource *> htmlresources = m_Book->GetHTMLResources();
foreach (HTMLResource * hresource, htmlresources) {
if (!hresource->FileIsWellFormed()) {
QMessageBox::warning(this, tr("Sigil"),
tr("Restructure cancelled: %1, XML not well formed.").arg(hresource->ShortPathName()));
return;
}
}
// make sure opf is in good shape as well
OPFResource* opfresource = m_Book->GetOPF();
if (!opfresource->FileIsWellFormed()) {
QMessageBox::warning(this, tr("Sigil"),
tr("Restructure cancelled: %1, XML not well formed.").arg(opfresource->ShortPathName()));
return;
}
// ditto for ncx if one exists
NCXResource* ncxresource = m_Book->GetNCX();
if (ncxresource && !ncxresource->FileIsWellFormed()) {
QMessageBox::warning(this, tr("Sigil"),
tr("Restructure cancelled: %1, XML not well formed.").arg(ncxresource->ShortPathName()));
return;
}
// we really should parse validate each css file here but
// since we update css files using regular expressions, the full
// parseability is really not critical
// first standardize the opf and ncx names
QList<Resource*> resources;
QStringList newfilenames;
QString opfname = m_Book->GetOPF()->Filename();
if (opfname != "content.opf") {
resources << m_Book->GetOPF();
newfilenames << "content.opf";
}
NCXResource * ncx = m_Book->GetNCX();
if (ncx && (ncx->Filename() != "toc.ncx")) {
resources << m_Book->GetNCX();
newfilenames << "toc.ncx";
}
if (!newfilenames.isEmpty()) {
m_BookBrowser->RenameResourceList(resources, newfilenames);
}
// handle any other name conflicts
FixDuplicateFilenames();
// handle case insensitive filesystems and clashing directory names
bool fs_case_sensitive = false;
QString mainfolder = m_Book->GetFolderKeeper()->GetFullPathToMainFolder();
QString apath = mainfolder + "/oebps/images";
QString bpath = mainfolder + "/OEBPS/Images";
if (QFileInfo(apath) != QFileInfo(bpath)) {
fs_case_sensitive = true;
}
DBG qDebug() << "file system is case sensitive: " << fs_case_sensitive;
if (!fs_case_sensitive) {
// opf is first to handle OEBPS before fighting with its subdirectories
QStringList groups = QStringList() << "opf" << "Text" << "Styles" << "Images"
<< "Fonts" << "Audio" << "Video" << "Misc";
// try renaming all matching existing directories to what we want
QDir mf(mainfolder);
foreach(QString group, groups) {
QString folderpath = m_Book->GetFolderKeeper()->GetStdFolderForGroup(group);
apath = mainfolder + "/" + folderpath.toLower();
bpath = mainfolder + "/" + folderpath;
if (QFileInfo(apath).exists() && QFileInfo(apath).isDir()) {
bool result = mf.rename(folderpath.toLower(), folderpath);
DBG qDebug() << "rename directory: " << folderpath << result;
}
}
}
// finally move all content to their standard folders if need be
MoveContentFilesToStdFolders();
// update what is needed
m_Book->GetFolderKeeper()->updateShortPathNames();
QList<Resource*> allresources = m_Book->GetFolderKeeper()->GetResourceList();
QStringList bookpaths;
QStringList mtypes;
foreach(Resource* res, allresources) {
bookpaths << res->GetRelativePath();
mtypes << res->GetMediaType();
}
m_Book->GetFolderKeeper()->SetGroupFolders(bookpaths, mtypes);
m_BookBrowser->Refresh();
m_Book->SetModified();
QApplication::restoreOverrideCursor();
ShowMessageOnStatusBar(tr("Restructure completed."));
}
void MainWindow::FixDuplicateFilenames()
{
QStringList bookpaths = m_Book->GetFolderKeeper()->GetAllBookPaths();
QStringList problem_bookpaths;
QSet<QString>UsedSet;
foreach(QString bkpath, bookpaths) {
QString aname =bkpath.split('/').last().toLower();
if (UsedSet.contains(aname)) {
problem_bookpaths << bkpath;
}
UsedSet.insert(aname);
}
foreach(QString bkpath, problem_bookpaths) {
QString aname = bkpath.split('/').last().toLower();
QString newname = m_Book->GetFolderKeeper()->GetUniqueFilenameVersion(aname);
Resource * resource = m_Book->GetFolderKeeper()->GetResourceByBookPath(bkpath);
QList<Resource*> resources = QList<Resource*>() << resource;
QStringList newfilenames = QStringList() << newname;
m_BookBrowser->RenameResourceList(resources, newfilenames);
}
return;
}
void MainWindow::MoveContentFilesToStdFolders()
{
QList<Resource*> resources = m_Book->GetFolderKeeper()->GetResourceList();
QList<Resource*> resources_to_move;
QStringList newbookpaths;
QString MainFolder = m_Book->GetFolderKeeper()->GetFullPathToMainFolder();
QDir epub_root(MainFolder);
foreach(Resource* resource, resources) {
QString group = MediaTypes::instance()->GetGroupFromMediaType(resource->GetMediaType(), "other");
if ((group == "other") || group.isEmpty()) continue;
QString stdfolder = m_Book->GetFolderKeeper()->GetStdFolderForGroup(group);
QString filename = resource->Filename();
QString newbookpath = filename;
if (!stdfolder.isEmpty()) {
newbookpath = stdfolder + "/" + filename;
}
if (newbookpath != resource->GetRelativePath()) {
// remember to create the destination directory if needed
if (!stdfolder.isEmpty()) {
epub_root.mkpath(stdfolder);
}
resources_to_move << resource;
newbookpaths << newbookpath;
}
}
if (!newbookpaths.isEmpty()) {
m_BookBrowser->MoveResourceList(resources_to_move, newbookpaths);
}
}
void MainWindow::RepoCommit()
{
QApplication::setOverrideCursor(Qt::WaitCursor);
// make sure that the Sigil-Preferences directory has a "repo" folder
QString localRepo = Utility::DefinePrefsDir() + "/repo";
QDir repoDir(localRepo);
if (!repoDir.exists()) {
repoDir.mkpath(localRepo);
}
// ensure epub opf has valid bookid and retrieve it
QString bookid = m_Book->GetOPF()->GetUUIDIdentifierValue();
// collect additional book info (file name, title, datetime)
QStringList bookinfo;
bookinfo << QFileInfo(m_CurrentFileName).completeBaseName();
bookinfo << m_Book->GetOPF()->GetPrimaryBookTitle();
// follow epub3 spec and update modification date/time for every save and commit
// manually set the book to be modified since modification date setting is normally
// only done upon save or save-as so no need to set the modified flag
bookinfo << m_Book->GetOPF()->AddModificationDateMeta();
m_Book->SetModified();
// finally force all changes to Disk
SaveTabData();
m_Book->GetFolderKeeper()->SuspendWatchingResources();
m_Book->SaveAllResourcesToDisk();
m_Book->GetFolderKeeper()->ResumeWatchingResources();
// get epub root
QString bookroot = m_Book->GetFolderKeeper()->GetFullPathToMainFolder();
// get a full list of epub resource bookpaths
QStringList bookfiles = m_Book->GetFolderKeeper()->GetAllBookPaths();
// add in the META-INF/container.xml file
bookfiles << "META-INF/container.xml";
// now perform the commit using python in a separate thread since this
// may take a while depending on the speed of the filesystem
PythonRoutines pr;
QFuture<QString> future = QtConcurrent::run(&pr, &PythonRoutines::PerformRepoCommitInPython,
localRepo, bookid, bookinfo, bookroot, bookfiles);
future.waitForFinished();
QString commit_result = future.result();
if (commit_result.isEmpty()) {
ShowMessageOnStatusBar(tr("Checkpoint generation failed."));
QApplication::restoreOverrideCursor();
return;
}
QApplication::restoreOverrideCursor();
ShowMessageOnStatusBar(tr("Checkpoint saved."));
}
// handle both the current epub and the general case
void MainWindow::RepoCheckout(QString bookid, QString destdir, QString filename, bool loadnow)
{
QString localRepo = Utility::DefinePrefsDir() + "/repo";
if (destdir.isEmpty()) {
destdir = Utility::DefinePrefsDir() + "/checkouts";
}
QDir coDir(destdir);
if (!coDir.exists()) {
coDir.mkpath(destdir);
}
if (bookid.isEmpty()) {
// use current epub's bookid and create one if needed
bookid = m_Book->GetOPF()->GetUUIDIdentifierValue();
}
if (filename.isEmpty()) {
// use current epub's filename
filename = QFileInfo(m_CurrentFileName).completeBaseName();
}
QApplication::setOverrideCursor(Qt::WaitCursor);
// now perform the operation using python in a separate thread since this
// may take a while depending on the speed of the filesystem
PythonRoutines pr;
QFuture<QStringList> future = QtConcurrent::run(&pr, &PythonRoutines::GetRepoTagsInPython,
localRepo, bookid);
future.waitForFinished();
QStringList tag_results = future.result();
if (tag_results.isEmpty()) {
ShowMessageOnStatusBar(tr("Checkout Failed. No checkpoints found"));
QApplication::restoreOverrideCursor();
return;
}
QApplication::restoreOverrideCursor();
// Now create a Dialog to allow the user to select a tag (checkpoint)
QString tagname;
SelectCheckpoint gettag(tag_results, this);
if (gettag.exec() == QDialog::Accepted) {
QStringList taglst = gettag.GetSelectedEntries();
if (!taglst.isEmpty()) {
tagname = taglst.at(0);
}
}
if (tagname.isEmpty()) {
ShowMessageOnStatusBar(tr("Checkout Failed. No checkpoint selected"));
return;
}
// Save the current state of open tabs, putting the current tab last
QStringList open_tab_bookpaths;
QList<int> open_tab_positions;
Resource * current_resource = m_TabManager->GetCurrentContentTab()->GetLoadedResource();
foreach(ContentTab* tab, m_TabManager->GetContentTabs()) {
Resource* res = tab->GetLoadedResource();
if (res != current_resource) {
open_tab_bookpaths << res->GetRelativePath();
open_tab_positions << tab->GetCursorPosition();
}
}
open_tab_bookpaths << current_resource->GetRelativePath();
open_tab_positions << m_TabManager->GetCurrentContentTab()->GetCursorPosition();
QApplication::setOverrideCursor(Qt::WaitCursor);
QFuture<QString> afuture = QtConcurrent::run(&pr, &PythonRoutines::GenerateEpubFromTagInPython,
localRepo, bookid, tagname, filename, destdir);
afuture.waitForFinished();
QString epub_result = afuture.result();
if (epub_result.isEmpty()) {
ShowMessageOnStatusBar(tr("Epub Generate from Tag Failed."));
QApplication::restoreOverrideCursor();
return;
}
QApplication::restoreOverrideCursor();
ShowMessageOnStatusBar(tr("Epub Generation succeeded"));
if (loadnow) {
// on macOS bad things with checkpoints could happen if we have
// two different epubs open but both with the exact same book id
// so treat macOS just like Linux and Windows when restoring from
// a checkpoint
// For Linux and Windows (and macOS in this one case) will replace
// current book So Throw Up a Dialog to See if they want to proceed
bool proceed = false;
QMessageBox msgBox;
msgBox.setIcon(QMessageBox::Warning);
msgBox.setWindowFlags(Qt::Window | Qt::WindowStaysOnTopHint);
msgBox.setWindowTitle(tr("Repository Checkout"));
msgBox.setText(tr("Your current book will be replaced losing any unsaved changes ... Are you sure you want to proceed?"));
QPushButton *yesButton = msgBox.addButton(QMessageBox::Yes);
QPushButton *noButton = msgBox.addButton(QMessageBox::No);
msgBox.setDefaultButton(noButton);
msgBox.exec();
if (msgBox.clickedButton() == yesButton) {
proceed = true;
}
if (proceed) {
LoadFile(epub_result, true);
// restore what we can of the open tabs
for(int i=0; i < open_tab_bookpaths.length(); i++) {
OpenFile(open_tab_bookpaths.at(i), -1, open_tab_positions.at(i));
}
}
}
}
void MainWindow::RepoDiff(QString bookid)
{
QString localRepo = Utility::DefinePrefsDir() + "/repo";
QDir repoDir(localRepo);
if (!repoDir.exists()) {
// No repo folder, no checkpoints
ShowMessageOnStatusBar(tr("Diff Failed. No checkpoints found"));
return;
}
if (bookid.isEmpty()) {
// use current epub's bookid and create one if needed
bookid = m_Book->GetOPF()->GetUUIDIdentifierValue();
}
QApplication::setOverrideCursor(Qt::WaitCursor);
// force all changes to Disk
SaveTabData();
m_Book->GetFolderKeeper()->SuspendWatchingResources();
m_Book->SaveAllResourcesToDisk();
m_Book->GetFolderKeeper()->ResumeWatchingResources();
// Get tags using python in a separate thread since this
// may take a while depending on the speed of the filesystem
PythonRoutines pr;
QFuture<QStringList> future = QtConcurrent::run(&pr, &PythonRoutines::GetRepoTagsInPython,
localRepo, bookid);
future.waitForFinished();
QStringList tag_results = future.result();
if (tag_results.isEmpty()) {
ShowMessageOnStatusBar(tr("Diff Failed. No checkpoints found"));
QApplication::restoreOverrideCursor();
return;
}
QApplication::restoreOverrideCursor();
// Now use a Dialog to allow the user to select the base tag
QString chkpoint1;
SelectCheckpoint gettagleft(tag_results, this);
if (gettagleft.exec() == QDialog::Accepted) {
QStringList taglst = gettagleft.GetSelectedEntries();
if (!taglst.isEmpty()) {
chkpoint1 = taglst.at(0);
}
}
if (chkpoint1.isEmpty()) {
ShowMessageOnStatusBar(tr("Diff Failed. No checkpoint selected for comparison"));
return;
}
// checkout this tag version and copy it to a tempfolder
TempFolder destdir;
QApplication::setOverrideCursor(Qt::WaitCursor);
QFuture<QString> cfuture = QtConcurrent::run(&pr, &PythonRoutines::CopyTagToDestDirInPython,
localRepo, bookid, chkpoint1, destdir.GetPath() );
cfuture.waitForFinished();
QString copied = cfuture.result();
QApplication::restoreOverrideCursor();
// get the status of the changes since that tag
QString bookroot = m_Book->GetFolderKeeper()->GetFullPathToMainFolder();
QStringList bookfiles = m_Book->GetFolderKeeper()->GetAllBookPaths();
bookfiles << "META-INF/container.xml";
QApplication::setOverrideCursor(Qt::WaitCursor);
QFuture<QList<QStringList> > dfuture = QtConcurrent::run(&pr,
&PythonRoutines::GetCurrentStatusVsDestDirInPython,
bookroot, bookfiles, destdir.GetPath());
dfuture.waitForFinished();
QList<QStringList> sres = dfuture.result();
QApplication::restoreOverrideCursor();
// order is deleted, added, and modified
QStringList dlist(sres.at(0));
QStringList alist(sres.at(1));
QStringList mlist(sres.at(2));
if (dlist.isEmpty() && alist.isEmpty() && mlist.isEmpty()) {
QMessageBox::information(this, tr("Results of Comparison"), tr("No differences were found."));
return;
}
// use CPCompare dialog modally to allow the user to explore the changes
CPCompare comp(bookroot, destdir.GetPath(), dlist, alist, mlist, this);
comp.exec();
}
void MainWindow::RepoManage()
{
ManageRepos mr(this);
mr.exec();
}
void MainWindow::launchExternalXEditor()
{
// Launch external xhtml editor for current tab resource
// ONLY if the current tab resource is a HTMLResource and
// ONLY if an external editor path is set and still exists
HTMLResource *html_resource = NULL;
OPFResource * opf_resource = NULL;
ContentTab *tab = GetCurrentContentTab();
if (tab != NULL) {
html_resource = qobject_cast<HTMLResource *>(tab->GetLoadedResource());
opf_resource = qobject_cast<OPFResource *>(tab->GetLoadedResource());
}
if (!html_resource && !opf_resource) {
ShowMessageOnStatusBar(tr("External XHtml Editor works only on Html Resources or OPF Resources!"));
return;
}
SettingsStore ss;
QString XEditorPath = ss.externalXEditorPath();
if (XEditorPath.isEmpty()) {
ShowMessageOnStatusBar(tr("No External Xhtml Editor has been specified: See Preferences"));
return;
}
// make sure XEditor Path actually exists
QFileInfo xeditorinfo(XEditorPath);
if (!xeditorinfo.exists()) {
ShowMessageOnStatusBar(tr("Specified External Xhtml Editor path does not exist"));
return;
}
Resource * resource;
if (opf_resource) {
resource = qobject_cast<Resource *>(opf_resource);
// an OPF Resource could be used to access every xhtml file in the spine
// so save all of these resources to disk and set a fswatcher on them
QList<Resource *> all_resources = m_Book->GetFolderKeeper()->GetResourceList();
QList<Resource*> spine_resources = m_Book->GetOPF()->GetSpineOrderResources(all_resources);
// first suspend file watching and then save all of these to disk
m_Book->GetFolderKeeper()->SuspendWatchingResources();
resource->SaveToDisk();
foreach(Resource * spineres, spine_resources) {
HTMLResource* xhtmlres = qobject_cast<HTMLResource *>(spineres);
if (xhtmlres) {
spineres->SaveToDisk();
}
}
m_Book->GetFolderKeeper()->ResumeWatchingResources();
// after re-enabling file watching, add all of these to list of files to be watched
foreach(Resource * spineres, spine_resources) {
HTMLResource* xhtmlres = qobject_cast<HTMLResource *>(spineres);
if (xhtmlres) {
m_Book->GetFolderKeeper()->WatchResourceFile(spineres);
}
}
} else {
// single xhtml resource
resource = qobject_cast<Resource *>(html_resource);
m_Book->GetFolderKeeper()->SuspendWatchingResources();
resource->SaveToDisk();
m_Book->GetFolderKeeper()->ResumeWatchingResources();
}
if (OpenExternally::openFile(resource->GetFullPath(), XEditorPath)) {
m_Book->GetFolderKeeper()->WatchResourceFile(resource);
ShowMessageOnStatusBar(tr("Executing External Xhtml Editor"));
return;
}
ShowMessageOnStatusBar(tr("Failed to Launch External Xhtml Editor"));
}
void MainWindow::runPlugin(QAction *action)
{
QString pname = action->text();
#if !defined(Q_OS_WIN32) && !defined(Q_OS_MAC)
// Workaround for a bug in the KDE Qt5 plugin that injects accelerator shortcuts
// into QAction->text(). So return the toolTip() text in those cases where it
// differs from text(). Everybody else uses text().
// https://bugs.kde.org/show_bug.cgi?format=multiple&id=345023
QString altname = action->toolTip();
if (pname != altname && !altname.isEmpty()) {
pname = altname;
}
#endif
{
PluginRunner prunner(m_TabManager, this);
prunner.exec(pname);
}
qApp->processEvents();
}
void MainWindow::SelectResources(QList<Resource *> resources)
{
return m_BookBrowser->SelectResources(resources);
}
QList <Resource *> MainWindow::GetValidSelectedHTMLResources()
{
return m_BookBrowser->ValidSelectedHTMLResources();
}
QList <Resource *> MainWindow::GetAllHTMLResources()
{
return m_BookBrowser->AllHTMLResources();
}
QSharedPointer<Book> MainWindow::GetCurrentBook()
{
return m_Book;
}
BookBrowser *MainWindow::GetBookBrowser()
{
return m_BookBrowser;
}
ContentTab *MainWindow::GetCurrentContentTab()
{
return m_TabManager->GetCurrentContentTab();
}
FlowTab *MainWindow::GetCurrentFlowTab()