-
Notifications
You must be signed in to change notification settings - Fork 28
/
MainWindow.cpp
2214 lines (1950 loc) · 79 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) 2019-2024 Kevin Hendricks, Doug Massay
**
** 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 <QEvent>
#include <QMouseEvent>
#include <QApplication>
#include <QClipboard>
#include <QMimeData>
#include <QDesktopServices>
#include <QFrame>
#include <QVBoxLayout>
#include <QHBoxLayout>
#include <QLabel>
#include <QCheckBox>
#include <QToolBar>
#include <QtWebEngineWidgets>
#include <QtWebEngineCore>
#include <QWebEngineView>
#include <QWebEngineSettings>
#include <QWebEngineProfile>
#include <QDir>
#include <QFileDialog>
#include <QMessageBox>
#include <QRegularExpression>
#include <QRegularExpressionMatch>
#include <QStatusBar>
#include <QThread>
#include <QToolButton>
#include <QSlider>
#include <QTimer>
#include <QFileInfo>
#include <QDebug>
#include "Inspector.h"
#include "SettingsStore.h"
#include "Utility.h"
#include "ClipEditor.h"
#include "ClipsWindow.h"
#include "WebViewEdit.h"
#include "SelectCharacter.h"
#include "SelectFiles.h"
#include "SelectHyperlink.h"
#include "SelectId.h"
#include "Preferences.h"
#include "GumboInterface.h"
#include "HTMLEncodingResolver.h"
#include "SearchToolbar.h"
#include "OPFReader.h"
#include "MainApplication.h"
#include "MainWindow.h"
#define DBG if(0)
static const QString SETTINGS_GROUP = "mainwindow";
static const QString CUSTOM_WEBVIEW_STYLE_FILENAME = "custom_webview_style.css";
static const QString EDIT_WITH_PRE_WRAP = ":not(html):not(body) { white-space: pre-wrap; }";
static const QString BREAK_TAG_INSERT = "<hr class=\"sigil_split_marker\" />";
static const QString DEFAULT_FILENAME = "untitled.xhtml";
static const QStringList HEADERTAGS = QStringList() << "h1" << "h2" << "h3" << "h4" << "h5" << "h6";
static const QStringList DARKCSSLINKS = QStringList() << "qrc:///dark/mac_dark_scrollbar.css"
<< "qrc:///dark/win_dark_scrollbar.css"
<< "qrc:///dark/lin_dark_scrollbar.css";
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;
MainWindow::MainWindow(QString filepath, QString spineno, QWidget *parent)
:
QMainWindow(parent),
m_WebView(new WebViewEdit(this)),
m_Inspector(new Inspector(this)),
m_Filepath(QString()),
m_GoToRequestPending(false),
m_headingMapper(new QSignalMapper(this)),
m_casingChangeMapper(new QSignalMapper(this)),
m_preserveHeadingAttributes(false),
m_SelectCharacter(new SelectCharacter(this)),
m_slZoomSlider(NULL),
m_lbZoomLabel(NULL),
m_updateActionStatePending(false),
m_LastWindowSize(QByteArray()),
m_LastFolderOpen(QString()),
m_using_wsprewrap(false),
m_search(NULL),
m_layout(NULL),
m_SpineList(QStringList()),
m_Base(QString()),
m_ListPtr(-1),
m_UpdatePageInProgress(false),
m_MediaList(QStringList()),
m_MediaKind(QStringList()),
m_MediaBase(QString()),
m_skipPrintWarnings(false),
m_skipPrintPreview(false),
m_WebViewPrinter(new WebViewPrinter(this)),
m_Clips(nullptr),
m_ClipEditor(new ClipEditor(this)),
m_LastPtr(-1)
{
ui.setupUi(this);
// initialize the toolbar UI clip actions
foreach(QAction* clipaction, ui.toolBarClips->actions()) {
if (!clipaction->isSeparator()) {
QString strIndex = clipaction->objectName();
strIndex.replace(QString("actionClip"), QString(""));
clipaction->setData(strIndex.toInt());
m_clactions.append(clipaction);
}
}
UpdateClipsUI();
SetupView();
// start up in edit mode unless the user changes it
ui.actionMode->setChecked(true);
LoadSettings();
ConnectSignalsToSlots();
SetupFileList(filepath, spineno);
SetupNavigationComboBox();
m_ClipEditor->SetCSSList(m_CSSList);
QTimer::singleShot(200, this, SLOT(DoUpdatePage()));
}
MainWindow::~MainWindow()
{
if (m_WebView) {
delete m_WebView;
m_WebView = nullptr;
}
if (m_Inspector) {
if (m_Inspector->isVisible()) {
m_Inspector->StopInspection();
m_Inspector->close();
}
delete m_Inspector;
m_Inspector = nullptr;
}
}
void MainWindow::ApplicationPaletteChanged()
{
// qDebug() << "ApplicationPaletteChanged";
RefreshPage();
}
// Navigation related routines
// initializes m_Base, m_SpineList, m_ListPtr, and m_CurrentFilePath
// Also sets m_SandBoxPath to limit file: urls
void MainWindow::SetupFileList(const QString &filepath, const QString &spineno)
{
m_CurrentFilePath = "";
ui.actionNext->setEnabled(false);
ui.actionPrev->setEnabled(false);
if (filepath.isEmpty()) return;
QFileInfo fi(filepath);
if (!fi.exists() || !fi.isReadable()) return;
m_ListPtr = -1;
if (fi.suffix() == "opf") {
m_ListPtr = 0;
OPFReader opfrdr;
opfrdr.parseOPF(filepath);
QStringList spine_files = opfrdr.GetSpineFilePathList();
if (!spineno.isEmpty()) {
bool okay;
int val = spineno.toInt(&okay);
if ((val >= 0) && (val < spine_files.size())) m_ListPtr = val;
}
m_Base = Utility::longestCommonPath(spine_files, "/");
foreach(QString sf, spine_files) {
m_SpineList << sf.right(sf.length()-m_Base.length());
}
// now collect a list of media file and kind
QStringList media_list;
m_MediaKind.clear();
QStringList audiolist = opfrdr.GetAudioFilePathList();
foreach(QString filepath, audiolist) {
media_list << filepath;
m_MediaKind << "audio";
}
QStringList videolist = opfrdr.GetVideoFilePathList();
foreach(QString filepath, videolist) {
media_list << filepath;
m_MediaKind << "video";
}
QStringList imagelist = opfrdr.GetImageFilePathList();
foreach(QString filepath, imagelist) {
media_list << filepath;
m_MediaKind << "image";
}
QStringList svglist = opfrdr.GetSVGFilePathList();
foreach(QString filepath, svglist) {
media_list << filepath;
m_MediaKind << "svgimage";
}
m_CSSList = opfrdr.GetCSSFilePathList();
m_MediaBase = Utility::longestCommonPath(media_list, "/");
m_MediaList.clear();
foreach(QString mf, media_list) {
m_MediaList << mf.right(mf.length()-m_MediaBase.length());
}
// finally determine the sandbox to play in
QStringList manifestlist = opfrdr.GetManifestFilePathList();
m_SandBoxPath = Utility::longestCommonPath(manifestlist, "/");
if (m_SandBoxPath == "/") m_SandBoxPath = m_Base;
} else {
// note longestCommonPath always ends with "/" but fi.absolutePath() does not
m_Base = fi.absolutePath()+ "/";
m_SpineList << fi.fileName();
m_ListPtr = 0;
// FIXME: how should we determine an appropriate sandbox for this case?
// For Now: limit to the directory holding this file and its parent if not root
m_SandBoxPath = m_Base;
QDir sb(m_Base);
if (sb.cdUp()) {
if (!sb.isRoot()) {
m_SandBoxPath = sb.absolutePath();
}
}
}
// enable or disable InsertFile based on if Media are present
ui.actionInsertFile->setEnabled(!m_MediaList.isEmpty());
m_CurrentFilePath = m_Base + m_SpineList.at(m_ListPtr);
if (m_SpineList.length() > 1) {
ui.actionNext->setEnabled(true);
ui.actionPrev->setEnabled(true);
}
DBG qDebug() << "in SetupFileList" << m_CurrentFilePath;
}
void MainWindow::SetupNavigationComboBox()
{
ui.cbNavigate->clear();
ui.cbNavigate->setSizeAdjustPolicy(QComboBox::AdjustToContents);
ui.cbNavigate->addItems(m_SpineList);
ui.cbNavigate->setCurrentIndex(m_ListPtr);
}
void MainWindow::CBNavigateActivated(int index)
{
if (m_UpdatePageInProgress) {
ui.cbNavigate->setCurrentIndex(m_ListPtr);
return;
}
if ((index > -1) && (index != m_ListPtr)) {
if (AllowSaveIfModified()) {
m_ListPtr = index;
m_CurrentFilePath = m_Base + m_SpineList.at(m_ListPtr);
UpdatePage(m_CurrentFilePath);
}
}
}
void MainWindow::EditNext()
{
if (m_UpdatePageInProgress) return;
int n = m_SpineList.length();
if (n > 1) {
if (AllowSaveIfModified()) {
m_ListPtr++;
if (m_ListPtr >= n) m_ListPtr = 0;
m_CurrentFilePath = m_Base + m_SpineList.at(m_ListPtr);
ui.cbNavigate->setCurrentIndex(m_ListPtr);
UpdatePage(m_CurrentFilePath);
}
}
}
void MainWindow::EditPrev()
{
if (m_UpdatePageInProgress) return;
int n = m_SpineList.length();
if (n > 1) {
if (AllowSaveIfModified()) {
m_ListPtr--;
if (m_ListPtr < 0) m_ListPtr = n - 1;
m_CurrentFilePath = m_Base + m_SpineList.at(m_ListPtr);
ui.cbNavigate->setCurrentIndex(m_ListPtr);
UpdatePage(m_CurrentFilePath);
}
}
}
QString MainWindow::GetCurrentFilePath()
{
QString res;
if (m_ListPtr != -1) {
res = m_SpineList.at(m_ListPtr);
}
return res;
}
QStringList MainWindow::GetAllFilePaths(int skip)
{
QStringList res;
int i = 0;
foreach(QString apath, m_SpineList) {
if (skip != i) {
res << apath;
}
i++;
}
return res;
}
// Mode setting
void MainWindow::ToggleMode(bool edit_mode)
{
m_WebView->SetDocumentEditable(edit_mode);
UpdateWindowTitle();
}
// Zoom Support Related Routines
void MainWindow::ZoomIn()
{
ZoomByStep(true);
}
void MainWindow::ZoomOut()
{
ZoomByStep(false);
}
void MainWindow::ZoomReset()
{
ZoomByFactor(ZOOM_NORMAL);
}
float MainWindow::GetZoomFactor()
{
return m_WebView->GetZoomFactor();
}
void MainWindow::ZoomByStep(bool zoom_in)
{
// We use a negative zoom stepping if we are zooming *out*
float zoom_stepping = zoom_in ? ZOOM_STEP : - ZOOM_STEP;
// If we are zooming in, we round UP;
// on zoom out, we round DOWN.
float rounding_helper = zoom_in ? 0.05f : - 0.05f;
float current_zoom_factor = GetZoomFactor();
float rounded_zoom_factor = Utility::RoundToOneDecimal(current_zoom_factor + rounding_helper);
// If the rounded value is nearly the same as the original value,
// then the original was rounded to begin with and so we
// add the zoom increment
if (qAbs(current_zoom_factor - rounded_zoom_factor) < 0.01f) {
ZoomByFactor(Utility::RoundToOneDecimal(current_zoom_factor + zoom_stepping));
}
// ...otherwise we first zoom to the rounded value
else {
ZoomByFactor(rounded_zoom_factor);
}
}
void MainWindow::ZoomByFactor(float new_zoom_factor)
{
if (new_zoom_factor > ZOOM_MAX || new_zoom_factor < ZOOM_MIN) {
return;
}
m_WebView->SetZoomFactor(new_zoom_factor);
}
void MainWindow::SliderZoom(int slider_value)
{
float new_zoom_factor = SliderRangeToZoomFactor(slider_value);
float current_zoom_factor = GetZoomFactor();
// We try to prevent infinite loops...
if (!qFuzzyCompare(new_zoom_factor, current_zoom_factor)) {
ZoomByFactor(new_zoom_factor);
}
}
void MainWindow::UpdateZoomSlider(float new_zoom_factor)
{
m_slZoomSlider->setValue(ZoomFactorToSliderRange(new_zoom_factor));
}
void MainWindow::UpdateZoomLabel(int slider_value)
{
float zoom_factor = SliderRangeToZoomFactor(slider_value);
UpdateZoomLabel(zoom_factor);
}
void MainWindow::UpdateZoomLabel(float new_zoom_factor)
{
m_lbZoomLabel->setText(QString("%1% ").arg(qRound(new_zoom_factor * 100)));
}
int MainWindow::ZoomFactorToSliderRange(float zoom_factor)
{
// We want a precise value for the 100% zoom,
// so we pick up all float values near it.
if (qFuzzyCompare(zoom_factor, ZOOM_NORMAL)) {
return ZOOM_SLIDER_MIDDLE;
}
// We actually use two ranges: one for the below 100% zoom,
// and one for the above 100%. This is so that the 100% mark
// rests in the middle of the slider.
if (zoom_factor < ZOOM_NORMAL) {
double range = ZOOM_NORMAL - ZOOM_MIN;
double normalized_value = zoom_factor - ZOOM_MIN;
double range_proportion = normalized_value / range;
return ZOOM_SLIDER_MIN + qRound(range_proportion * (ZOOM_SLIDER_MIDDLE - ZOOM_SLIDER_MIN));
}
double range = ZOOM_MAX - ZOOM_NORMAL;
double normalized_value = zoom_factor - ZOOM_NORMAL;
double range_proportion = normalized_value / range;
return ZOOM_SLIDER_MIDDLE + qRound(range_proportion * ZOOM_SLIDER_MIDDLE);
}
float MainWindow::SliderRangeToZoomFactor(int slider_range_value)
{
// We want a precise value for the 100% zoom
if (slider_range_value == ZOOM_SLIDER_MIDDLE) {
return ZOOM_NORMAL;
}
// We actually use two ranges: one for the below 100% zoom,
// and one for the above 100%. This is so that the 100% mark
// rests in the middle of the slider.
if (slider_range_value < ZOOM_SLIDER_MIDDLE) {
double range = ZOOM_SLIDER_MIDDLE - ZOOM_SLIDER_MIN;
double normalized_value = slider_range_value - ZOOM_SLIDER_MIN;
double range_proportion = normalized_value / range;
return ZOOM_MIN + range_proportion * (ZOOM_NORMAL - ZOOM_MIN);
}
double range = ZOOM_SLIDER_MAX - ZOOM_SLIDER_MIDDLE;
double normalized_value = slider_range_value - ZOOM_SLIDER_MIDDLE;
double range_proportion = normalized_value / range;
return ZOOM_NORMAL + range_proportion * (ZOOM_MAX - ZOOM_NORMAL);
}
// End of Zoom related routines
void MainWindow::resizeEvent(QResizeEvent *event)
{
QMainWindow::resizeEvent(event);
UpdateWindowTitle();
}
void MainWindow::hideEvent(QHideEvent * event)
{
if (m_Inspector) {
m_Inspector->StopInspection();
m_Inspector->close();
}
if ((m_WebView) && m_WebView->isVisible()) {
m_WebView->hide();
}
}
void MainWindow::showEvent(QShowEvent * event)
{
// perform the show for all children of this widget
if ((m_WebView) && !m_WebView->isVisible()) {
m_WebView->show();
}
QMainWindow::showEvent(event);
raise();
emit Shown();
}
bool MainWindow::IsVisible()
{
return m_WebView->isVisible();
}
bool MainWindow::HasFocus()
{
if (!m_WebView->isVisible()) {
return false;
}
return m_WebView->hasFocus();
}
void MainWindow::SetupView()
{
// QWebEngineView events are routed to their parent
m_WebView->installEventFilter(this);
#if 1 // !defined(Q_OS_WIN32) && !defined(Q_OS_MAC)
// this may be needed by all platforms in the future
QWidget * fp = m_WebView->focusProxy();
if (fp) fp->installEventFilter(this);
#endif
QApplication::setOverrideCursor(Qt::WaitCursor);
setAttribute(Qt::WA_DeleteOnClose);
QFrame *frame = new QFrame(this);
m_layout = new QVBoxLayout(frame);
frame->setLayout(m_layout);
m_layout->addWidget(m_WebView);
m_layout->setContentsMargins(0, 0, 0, 0);
frame->setObjectName("PrimaryFrame");
setCentralWidget(frame);
m_Inspector->setObjectName("Inspector");
addDockWidget(Qt::RightDockWidgetArea, m_Inspector);
m_Inspector->hide();
m_Clips = new ClipsWindow(this);
m_Clips->setObjectName("ClipsWindow");
addDockWidget(Qt::LeftDockWidgetArea, m_Clips);
m_Clips->hide();
// Creating the zoom controls in the status bar
m_slZoomSlider = new QSlider(Qt::Horizontal, statusBar());
m_slZoomSlider->setTracking(false);
m_slZoomSlider->setTickInterval(ZOOM_SLIDER_MIDDLE);
m_slZoomSlider->setTickPosition(QSlider::TicksBelow);
m_slZoomSlider->setFixedWidth(ZOOM_SLIDER_WIDTH);
m_slZoomSlider->setMinimum(ZOOM_SLIDER_MIN);
m_slZoomSlider->setMaximum(ZOOM_SLIDER_MAX);
m_slZoomSlider->setValue(ZOOM_SLIDER_MIDDLE);
QToolButton *zoom_out = new QToolButton(statusBar());
zoom_out->setDefaultAction(ui.actionZoomOut);
QToolButton *zoom_in = new QToolButton(statusBar());
zoom_in->setDefaultAction(ui.actionZoomIn);
m_lbZoomLabel = new QLabel(QString("100% "), statusBar());
statusBar()->addPermanentWidget(m_lbZoomLabel);
statusBar()->addPermanentWidget(zoom_out);
statusBar()->addPermanentWidget(m_slZoomSlider);
statusBar()->addPermanentWidget(zoom_in);
// Handle special case of two different icons for one action
QIcon icon = ui.actionMode->icon();
icon.addFile(QString::fromUtf8(":/icons/mode-preview.svg"), QSize(), QIcon::Normal, QIcon::Off);
icon.addFile(QString::fromUtf8(":/icons/mode-edit.svg"), QSize(), QIcon::Normal, QIcon::On);
ui.actionMode->setIcon(icon);
// Headings QToolButton
ui.tbHeadings->setPopupMode(QToolButton::InstantPopup);
// Preferences and About
ui.actionPreferences->setMenuRole(QAction::PreferencesRole);
ui.actionPreferences->setEnabled(true);
ui.actionAbout->setMenuRole(QAction::AboutRole);
ui.actionAbout->setEnabled(true);
ui.actionOpen->setEnabled(true);
ui.actionSave->setEnabled(true);
ui.actionPrint->setEnabled(true);
ui.actionExit->setEnabled(true);
ui.actionUndo->setEnabled(true);
ui.actionRedo->setEnabled(true);
ui.actionCut->setEnabled(true);
ui.actionCopy->setEnabled(true);
ui.actionPaste->setEnabled(true);
ui.actionSelectAll->setEnabled(true);
ui.actionInsertSpecialCharacter->setEnabled(true);
ui.actionInsertSGFSectionMarker->setEnabled(true);
ui.actionInsertBulletedList ->setEnabled(true);
ui.actionInsertNumberedList ->setEnabled(true);
ui.actionInsertId->setEnabled(true);
ui.actionInsertHyperlink->setEnabled(true);
ui.actionInsertFile->setEnabled(!m_MediaList.isEmpty());
ui.actionHeading1->setEnabled(true);
ui.actionHeading2->setEnabled(true);
ui.actionHeading3->setEnabled(true);
ui.actionHeading4->setEnabled(true);
ui.actionHeading5->setEnabled(true);
ui.actionHeading6->setEnabled(true);
ui.actionHeadingNormal->setEnabled(true);
ui.actionBold ->setEnabled(true);
ui.actionItalic ->setEnabled(true);
ui.actionUnderline ->setEnabled(true);
ui.actionStrikethrough->setEnabled(true);
ui.actionSubscript ->setEnabled(true);
ui.actionSuperscript ->setEnabled(true);
ui.actionCasingLowercase ->setEnabled(true);
ui.actionCasingUppercase ->setEnabled(true);
ui.actionCasingTitlecase ->setEnabled(true);
ui.actionCasingCapitalize ->setEnabled(true);
ui.actionAlignLeft ->setEnabled(true);
ui.actionAlignCenter ->setEnabled(true);
ui.actionAlignRight ->setEnabled(true);
ui.actionAlignJustify->setEnabled(true);
ui.actionDecreaseIndent->setEnabled(true);
ui.actionIncreaseIndent->setEnabled(true);
ui.actionZoomIn->setEnabled(true);
ui.actionZoomOut->setEnabled(true);
ui.actionZoomReset->setEnabled(true);
ui.actionInspect->setEnabled(true);
sizeMenuIcons();
m_WebView->Zoom();
UpdateZoomSlider(GetZoomFactor());
UpdateZoomLabel(GetZoomFactor());
QApplication::restoreOverrideCursor();
}
void MainWindow::SelectionChanged()
{
if (!m_updateActionStatePending) {
m_updateActionStatePending = true;
QTimer::singleShot(200, this, SLOT(UpdateActionState()));
}
}
void MainWindow::UpdateActionState() {
if (!m_WebView->hasSelection()) {
ui.actionBold->setChecked(false);
ui.actionItalic->setChecked(false);
ui.actionStrikethrough->setChecked(false);
ui.actionUnderline->setChecked(false);
ui.actionSubscript->setChecked(false);
ui.actionSuperscript->setChecked(false);
ui.actionCasingLowercase->setEnabled(false);
ui.actionCasingUppercase->setEnabled(false);
ui.actionCasingTitlecase->setEnabled(false);
ui.actionCasingCapitalize->setEnabled(false);
ui.actionHeading1->setChecked(false);
ui.actionHeading2->setChecked(false);
ui.actionHeading3->setChecked(false);
ui.actionHeading4->setChecked(false);
ui.actionHeading5->setChecked(false);
ui.actionHeading6->setChecked(false);
ui.actionHeadingNormal->setChecked(false);
} else {
ui.actionBold->setChecked(m_WebView->QueryCommandState("bold"));
ui.actionItalic->setChecked(m_WebView->QueryCommandState("italic"));
ui.actionStrikethrough->setChecked(m_WebView->QueryCommandState("strikeThrough"));
ui.actionUnderline->setChecked(m_WebView->QueryCommandState("underline"));
ui.actionSubscript->setChecked(m_WebView->QueryCommandState("subscript"));
ui.actionSuperscript->setChecked(m_WebView->QueryCommandState("superscript"));
ui.actionCasingLowercase->setEnabled(true);
ui.actionCasingUppercase->setEnabled(true);
ui.actionCasingTitlecase->setEnabled(true);
ui.actionCasingCapitalize->setEnabled(true);
CheckHeadingLevel(m_WebView->GetCaretElementName());
}
m_updateActionStatePending = false;
}
void MainWindow::ChangeCasing(int casing_mode)
{
Utility::Casing casing;
switch (casing_mode) {
case Utility::Casing_Lowercase: {
casing = Utility::Casing_Lowercase;
break;
}
case Utility::Casing_Uppercase: {
casing = Utility::Casing_Uppercase;
break;
}
case Utility::Casing_Titlecase: {
casing = Utility::Casing_Titlecase;
break;
}
case Utility::Casing_Capitalize: {
casing = Utility::Casing_Capitalize;
break;
}
default:
return;
}
m_WebView->ApplyCaseChangeToSelection(casing);
}
void MainWindow::CheckHeadingLevel(const QString &element_name)
{
ui.actionHeading1->setChecked(false);
ui.actionHeading2->setChecked(false);
ui.actionHeading3->setChecked(false);
ui.actionHeading4->setChecked(false);
ui.actionHeading5->setChecked(false);
ui.actionHeading6->setChecked(false);
ui.actionHeadingNormal->setChecked(false);
if (!element_name.isEmpty()) {
if ((element_name[ 0 ].toLower() == QChar('h')) && (element_name[ 1 ].isDigit())) {
QString heading_name = QString(element_name[ 1 ]);
if (heading_name == "1") {
ui.actionHeading1->setChecked(true);
} else if (heading_name == "2") {
ui.actionHeading2->setChecked(true);
} else if (heading_name == "3") {
ui.actionHeading3->setChecked(true);
} else if (heading_name == "4") {
ui.actionHeading4->setChecked(true);
} else if (heading_name == "5") {
ui.actionHeading5->setChecked(true);
} else if (heading_name == "6") {
ui.actionHeading6->setChecked(true);
}
} else {
ui.actionHeadingNormal->setChecked(true);
}
}
}
void MainWindow::DoUpdatePage()
{
if (!m_CurrentFilePath.isEmpty()) {
QFileInfo fi(m_CurrentFilePath);
if (fi.exists() && fi.isReadable()) {
ui.actionMode->setChecked(true);
UpdatePage(m_CurrentFilePath);
}
}
}
void MainWindow::UpdatePage(const QString &filename_url, const QString &source)
{
m_UpdatePageInProgress = true;
QString text;
QString file_path = filename_url;
if (!source.isEmpty()) {
text = source;
} else {
try {
// This will read in the data and properly convert to unicode
// from whatever encoding it is in now
text = HTMLEncodingResolver::ReadHTMLFile(filename_url);
// This will convert all html to xhtml and remove any
// improper xml header and add the proper xml header
GumboInterface gi(text, "any_version");
text = gi.getxhtml();
} catch (std::exception &e) {
Utility::DisplayStdErrorDialog(tr("File load failed"), e.what());
text = "<html><head><title></title></head><body><h1>" + tr("File Load Failed") + "</h1></body></html>";
file_path = "";
m_CurrentFilePath = "";
}
}
//if isDarkMode is set, inject a local style in head
SettingsStore settings;
if (Utility::IsDarkMode() && settings.previewDark()) {
text = Utility::AddDarkCSS(text);
}
SettingsStore ss;
// to prevent the WebEngine from inserting extraneous non-breaking space characters
// during editing, the official editing api says we should set white-space:pre-wrap
// on the elements we want to edit. In our case this is just about everything
m_using_wsprewrap = ss.useWSPreWrap();
if (ss.useWSPreWrap()) {
int endheadpos = text.indexOf("</head>");
if (endheadpos > 1) {
QString inject_editstyle = "<style type=\"text/css\">" + EDIT_WITH_PRE_WRAP + "</style>";
text.insert(endheadpos, inject_editstyle);
}
}
// If the user has set a default stylesheet inject it
if (!m_usercssurl.isEmpty()) {
int endheadpos = text.indexOf("</head>");
if (endheadpos > 1) {
QString inject_userstyles =
"<link rel=\"stylesheet\" type=\"text/css\" "
"href=\"" + m_usercssurl + "\" />";
DBG qDebug() << "WebView injecting stylesheet: " << inject_userstyles;
text.insert(endheadpos, inject_userstyles);
}
}
#if 0
// If this page uses mathml tags, inject a polyfill
// MathJax.js so that the mathml appears in the WebView Window
QRegularExpression mathused("<\\s*math [^>]*>");
QRegularExpressionMatch mo = mathused.match(text);
if (mo.hasMatch()) {
int endheadpos = text.indexOf("</head>");
if (endheadpos > 1) {
QString inject_mathjax =
"<script type=\"text/javascript\" async=\"async\" "
"src=\"" + m_mathjaxurl + "\"></script>\n";
text.insert(endheadpos, inject_mathjax);
}
}
#endif
m_Filepath = file_path;
m_WebView->CustomSetDocument(file_path, text);
// this next bit is allowing javascript to run before
// the page is finished loading somehow?
// but we explicitly prevent that
// Wait until the preview is loaded before moving cursor.
while (!m_WebView->IsLoadingFinished()) {
qApp->processEvents(QEventLoop::ExcludeUserInputEvents);
}
if (!m_WebView->WasLoadOkay()) qDebug() << "WV loadFinished with okay set to false!";
DBG qDebug() << "WebViewWindow UpdatePage load is Finished";
UpdateWindowTitle();
m_WebView->show();
m_WebView->GrabFocus();
// now set the mode: edit or preview
ToggleMode(ui.actionMode->isChecked());
QTimer::singleShot(100, this, SLOT(SetInitialSource()));
}
void MainWindow::SetInitialSource()
{
m_source = GetSource();
m_UpdatePageInProgress = false;
}
void MainWindow::ScrollTo(QList<ElementIndex> location)
{
DBG qDebug() << "received a WebViewWindow ScrollTo event";
if (!m_WebView->isVisible()) {
return;
}
m_WebView->StoreCaretLocationUpdate(location);
m_WebView->ExecuteCaretUpdate();
}
void MainWindow::UpdateWindowTitle()
{
if ((m_WebView) && m_WebView->isVisible()) {
int height = m_WebView->height();
int width = m_WebView->width();
QString mode = "-- " + tr("mode: Preview") + " --";
if (ui.actionMode->isChecked()) {
mode = "-- " + tr("mode: Edit") + " --";
}
setWindowTitle("PageEdit " + mode + " (" + QString::number(width) + "x" + QString::number(height) + ")");
}
}
QList<ElementIndex> MainWindow::GetCaretLocation()
{
DBG qDebug() << "WebView in GetCaretLocation";
QList<ElementIndex> hierarchy = m_WebView->GetCaretLocation();
// foreach(ElementIndex ei, hierarchy) {
// qDebug() << "name: " << ei.name << " index: " << ei.index;
// }
return hierarchy;
}
void MainWindow::SetZoomFactor(float factor)
{
m_WebView->SetZoomFactor(factor);
}
void MainWindow::EmitGoToPreviewLocationRequest()
{
DBG qDebug() << "EmitGoToPreviewLocationRequest request: " << m_GoToRequestPending;
if (m_GoToRequestPending) {
m_GoToRequestPending = false;
emit GoToPreviewLocationRequest();
}
}
bool MainWindow::eventFilter(QObject *object, QEvent *event)
{
switch (event->type()) {
case QEvent::ChildAdded:
if (object == m_WebView) {
DBG qDebug() << "child add event";
const QChildEvent *childEvent(static_cast<QChildEvent*>(event));
if (childEvent->child()) {
childEvent->child()->installEventFilter(this);
}
}
break;
case QEvent::MouseButtonPress:
{
DBG qDebug() << "Preview mouse button press event " << object;
const QMouseEvent *mouseEvent(static_cast<QMouseEvent*>(event));
if (mouseEvent) {
if (mouseEvent->button() == Qt::LeftButton) {
DBG qDebug() << "Detected Left Mouse Button Press Event";
QString hoverurl = m_WebView->GetHoverUrl();
DBG qDebug() << "hover url is: " << hoverurl;
if (!hoverurl.isEmpty() && !ui.actionMode->isChecked()) {
// we are taking a link so save the current location
m_LastPtr = m_ListPtr;
m_LastLocation = m_WebView->GetCaretLocation();
}
}
if (mouseEvent->button() == Qt::RightButton) {
DBG qDebug() << "Detected Right Mouse Button Press Event";
}
}
}
break;
case QEvent::MouseButtonRelease:
{
DBG qDebug() << "Preview mouse button release event " << object;
const QMouseEvent *mouseEvent(static_cast<QMouseEvent*>(event));
if (mouseEvent) {
if (mouseEvent->button() == Qt::LeftButton) {
DBG qDebug() << "Detected Left Mouse Button Release Event";
}
if (mouseEvent->button() == Qt::RightButton) {
DBG qDebug() << "Detected Right Mouse Button Release Event";
}
}
}
break;
case QEvent::Resize:
{
if (object == m_WebView) {
const QResizeEvent *resizeEvent(static_cast<QResizeEvent*>(event));
if (resizeEvent) {
DBG qDebug() << "Detected ResizeEvent: " << resizeEvent->oldSize() << resizeEvent->size();
QTimer::singleShot(100, this, SLOT(UpdateWindowTitle()));
}
}
}
break;
case QEvent::KeyPress:
{
// Assume any key presses are directed at WebEngineView via the delegate
}
break;
default:
break;
}
return QObject::eventFilter(object, event);
}
void MainWindow::LinkReturn()
{
// requires the Preview Mode to function
if (ui.actionMode->isChecked()) return;
// return to last location before link
if ((m_LastPtr != -1) && !m_LastLocation.isEmpty()) {
if (m_LastPtr != m_ListPtr) {
if (AllowSaveIfModified()) {
m_ListPtr = m_LastPtr;
ui.cbNavigate->setCurrentIndex(m_ListPtr);
m_CurrentFilePath = m_Base + m_SpineList.at(m_ListPtr);
UpdatePage(m_CurrentFilePath);
}
}
ScrollTo(m_LastLocation);
}
m_LastPtr = -1;
m_LastLocation.clear();
}