forked from notepadqq/notepadqq
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmainwindow.cpp
2675 lines (2222 loc) · 87.6 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
#include "include/mainwindow.h"
#include "include/EditorNS/bannerfilechanged.h"
#include "include/EditorNS/bannerfileremoved.h"
#include "include/EditorNS/bannerindentationdetected.h"
#include "include/EditorNS/editor.h"
#include "include/Extensions/Stubs/windowstub.h"
#include "include/Extensions/extensionsloader.h"
#include "include/Extensions/installextension.h"
#include "include/Sessions/backupservice.h"
#include "include/Sessions/persistentcache.h"
#include "include/Sessions/sessions.h"
#include "include/clickablelabel.h"
#include "include/editortabwidget.h"
#include "include/frmabout.h"
#include "include/frmencodingchooser.h"
#include "include/frmindentationmode.h"
#include "include/frmlinenumberchooser.h"
#include "include/frmpreferences.h"
#include "include/iconprovider.h"
#include "include/notepadqq.h"
#include "include/nqqrun.h"
#include "ui_mainwindow.h"
#include <QClipboard>
#include <QDesktopServices>
#include <QFileDialog>
#include <QInputDialog>
#include <QLineEdit>
#include <QMessageBox>
#include <QMimeData>
#include <QPageSetupDialog>
#include <QScrollArea>
#include <QScrollBar>
#include <QTemporaryFile>
#include <QTimer>
#include <QToolBar>
#include <QToolButton>
#include <QUrl>
#include <QtPrintSupport/QPrintDialog>
#include <QtPrintSupport/QPrintPreviewDialog>
#include <QtPromise>
using namespace QtPromise;
QList<MainWindow*> MainWindow::m_instances = QList<MainWindow*>();
MainWindow::MainWindow(const QString &workingDirectory, const QStringList &arguments, QWidget *parent) :
QMainWindow(parent),
ui(new Ui::MainWindow),
m_topEditorContainer(new TopEditorContainer(this)),
m_settings(NqqSettings::getInstance()),
m_workingDirectory(workingDirectory),
m_advSearchDock(new AdvancedSearchDock(this))
{
ui->setupUi(this);
setAttribute(Qt::WA_DeleteOnClose);
MainWindow::m_instances.append(this);
// Gets company name from QCoreApplication::setOrganizationName(). Same for app name.
setCentralWidget(m_topEditorContainer);
m_docEngine = new DocEngine(m_topEditorContainer);
connect(m_docEngine, &DocEngine::fileOnDiskChanged, this, &MainWindow::on_fileOnDiskChanged);
connect(m_docEngine, &DocEngine::documentSaved, this, &MainWindow::on_documentSaved);
connect(m_docEngine, &DocEngine::documentReloaded, this, &MainWindow::on_documentReloaded);
connect(m_docEngine, &DocEngine::documentLoaded, this, &MainWindow::on_documentLoaded);
loadIcons();
// Printing a WebEnginePage not supported prior to 5.8
#if QT_VERSION < QT_VERSION_CHECK(5,8,0)
ui->actionPrint->setEnabled(false);
ui->actionPrint->setVisible(false);
#endif
// Context menu initialization
m_tabContextMenu = new QMenu(this);
QAction *separator = new QAction(this);
separator->setSeparator(true);
QAction *separatorBottom = new QAction(this);
separatorBottom->setSeparator(true);
m_tabContextMenuActions.append(ui->actionClose);
m_tabContextMenuActions.append(ui->actionClose_All_BUT_Current_Document);
m_tabContextMenuActions.append(ui->actionCloseLeft);
m_tabContextMenuActions.append(ui->actionCloseRight);
m_tabContextMenuActions.append(ui->actionSave);
m_tabContextMenuActions.append(ui->actionSave_as);
m_tabContextMenuActions.append(ui->actionRename);
m_tabContextMenuActions.append(ui->actionPrint);
m_tabContextMenuActions.append(separator);
m_tabContextMenuActions.append(ui->actionCurrent_Full_File_Path_to_Clipboard);
m_tabContextMenuActions.append(ui->actionCurrent_Filename_to_Clipboard);
m_tabContextMenuActions.append(ui->actionCurrent_Directory_Path_to_Clipboard);
m_tabContextMenuActions.append(separatorBottom);
m_tabContextMenuActions.append(ui->actionMove_to_Other_View);
m_tabContextMenuActions.append(ui->actionClone_to_Other_View);
m_tabContextMenuActions.append(ui->actionMove_to_New_Window);
m_tabContextMenuActions.append(ui->actionOpen_in_New_Window);
m_tabContextMenu->addActions(m_tabContextMenuActions);
fixKeyboardShortcuts();
connect(m_topEditorContainer, &TopEditorContainer::customTabContextMenuRequested,
this, &MainWindow::on_customTabContextMenuRequested);
connect(m_topEditorContainer, &TopEditorContainer::tabCloseRequested,
this, &MainWindow::on_tabCloseRequested);
connect(m_topEditorContainer, &TopEditorContainer::currentEditorChanged,
this, &MainWindow::on_currentEditorChanged);
connect(m_topEditorContainer, &TopEditorContainer::editorAdded,
this, &MainWindow::on_editorAdded);
connect(m_topEditorContainer, &TopEditorContainer::editorMouseWheel,
this, &MainWindow::on_editorMouseWheel);
connect(m_topEditorContainer, &TopEditorContainer::tabBarDoubleClicked,
this, &MainWindow::on_tabBarDoubleClicked);
configureStatusBar();
updateRecentDocsInMenu();
setAcceptDrops(true);
generateRunMenu();
// Initialize at least one editor here so things like restoring "zoom"
// work properly
openCommandLineProvidedUrls(workingDirectory, arguments);
configureUserInterface();
loadToolBar();
setupLanguagesMenu();
showExtensionsMenu(Extensions::ExtensionsLoader::extensionRuntimePresent());
//Registers all actions so that NqqSettings knows their default and current shortcuts.
const QList<QAction*> allActions = getActions();
m_settings.Shortcuts.initShortcuts(allActions);
//At this point, all actions still have their default shortcuts so we set all actions'
//shortcuts from settings.
for (QAction* a : allActions){
if (a->objectName().isEmpty())
continue;
QKeySequence shortcut = m_settings.Shortcuts.getShortcut(a->objectName());
a->setShortcut(shortcut);
}
//Register our meta types for signal/slot calls here.
emit Notepadqq::getInstance().newWindow(this);
}
MainWindow::MainWindow(const QStringList &arguments, QWidget *parent)
: MainWindow(QDir::currentPath(), arguments, parent)
{ }
MainWindow::~MainWindow()
{
MainWindow::m_instances.removeAll(this);
delete ui;
delete m_docEngine;
}
QList<MainWindow*> MainWindow::instances()
{
return MainWindow::m_instances;
}
MainWindow *MainWindow::lastActiveInstance()
{
if (m_instances.length() > 0) {
return m_instances.last();
} else {
return nullptr;
}
}
TopEditorContainer *MainWindow::topEditorContainer()
{
return m_topEditorContainer;
}
void MainWindow::configureUserInterface()
{
// Group EOL modes
QActionGroup* eolActionGroup = new QActionGroup(this);
eolActionGroup->addAction(ui->actionWindows_Format);
eolActionGroup->addAction(ui->actionUNIX_Format);
eolActionGroup->addAction(ui->actionMac_Format);
// Group indentation modes
QActionGroup* indentationActionGroup = new QActionGroup(this);
indentationActionGroup->addAction(ui->actionIndentation_Default_Settings);
indentationActionGroup->addAction(ui->actionIndentation_Custom);
// Create the toolbar
m_mainToolBar = new QToolBar("Toolbar");
m_mainToolBar->setIconSize(QSize(16, 16));
m_mainToolBar->setObjectName("toolbar");
addToolBar(m_mainToolBar);
// Wire up toolbar and menubar visibility.
connect(m_mainToolBar, &QToolBar::visibilityChanged, ui->actionShow_Toolbar, &QAction::setChecked);
ui->actionShow_Toolbar->setChecked(m_mainToolBar->isVisible());
ui->menuBar->setVisible(m_settings.MainWindow.getMenuBarVisible());
ui->actionShow_Menubar->setChecked(m_settings.MainWindow.getMenuBarVisible());
// Set popup for actionOpen in toolbar
QToolButton* btnActionOpen = static_cast<QToolButton*>(m_mainToolBar->widgetForAction(ui->actionOpen));
if (btnActionOpen) {
btnActionOpen->setMenu(ui->menuRecent_Files);
btnActionOpen->setPopupMode(QToolButton::MenuButtonPopup);
}
// Restore symbol visibility
bool showAll = m_settings.General.getShowAllSymbols();
ui->actionWord_wrap->setChecked(m_settings.General.getWordWrap());
ui->actionShow_All_Characters->setChecked(showAll);
emit on_actionShow_All_Characters_toggled(showAll);
// Restore math rendering
ui->actionMath_Rendering->setChecked(m_settings.General.getMathRendering());
// Restore full screen
ui->actionFull_Screen->setChecked(isFullScreen());
// Initialize the advanced search dock and hook its signals up
addDockWidget(Qt::BottomDockWidgetArea, m_advSearchDock->getDockWidget());
m_advSearchDock->getDockWidget()
->hide(); // Hidden by default, user preference is applied via restoreWindowSettings()
connect(m_advSearchDock, &AdvancedSearchDock::itemInteracted, this, &MainWindow::searchDockItemInteracted);
// Restore smart indent
ui->actionToggle_Smart_Indent->setChecked(m_settings.General.getSmartIndentation());
on_actionToggle_Smart_Indent_toggled(m_settings.General.getSmartIndentation());
// Restore zoom
const qreal zoom = m_settings.General.getZoom();
for (int i = 0; i < m_topEditorContainer->count(); i++) {
m_topEditorContainer->tabWidget(i)->setZoomFactor(zoom);
}
restoreWindowSettings();
}
void MainWindow::restoreWindowSettings()
{
restoreGeometry(m_settings.MainWindow.getGeometry());
restoreState(m_settings.MainWindow.getWindowState());
if (!isMaximized() && m_instances.count() > 1) {
QPoint curPos = pos();
move(curPos.x() + 50, curPos.y() + 50);
}
}
void MainWindow::loadIcons()
{
// To test fallback icons:
// QIcon::setThemeSearchPaths(QStringList(""));
// Assign (where possible) system theme icons to our actions.
// If a system icon doesn't exist, fallback on the already assigned icon.
// File menu
ui->actionNew->setIcon(IconProvider::fromTheme("document-new"));
ui->actionOpen->setIcon(IconProvider::fromTheme("document-open"));
ui->actionReload_from_Disk->setIcon(IconProvider::fromTheme("view-refresh"));
ui->actionSave->setIcon(IconProvider::fromTheme("document-save"));
ui->actionSave_as->setIcon(IconProvider::fromTheme("document-save-as"));
ui->actionSave_a_Copy_As->setIcon(IconProvider::fromTheme("document-save-as"));
ui->actionSave_All->setIcon(IconProvider::fromTheme("document-save-all"));
ui->actionClose->setIcon(IconProvider::fromTheme("document-close"));
ui->actionClose_All->setIcon(IconProvider::fromTheme("document-close-all"));
ui->menuRecent_Files->setIcon(IconProvider::fromTheme("document-open-recent"));
ui->actionExit->setIcon(IconProvider::fromTheme("application-exit"));
ui->actionPrint->setIcon(IconProvider::fromTheme("document-print"));
ui->actionPrint_Now->setIcon(IconProvider::fromTheme("document-print")); // currently invisible
// Edit menu
ui->actionUndo->setIcon(IconProvider::fromTheme("edit-undo"));
ui->actionRedo->setIcon(IconProvider::fromTheme("edit-redo"));
ui->actionCut->setIcon(IconProvider::fromTheme("edit-cut"));
ui->actionCopy->setIcon(IconProvider::fromTheme("edit-copy"));
ui->actionPaste->setIcon(IconProvider::fromTheme("edit-paste"));
ui->actionDelete->setIcon(IconProvider::fromTheme("edit-delete"));
ui->actionSelect_All->setIcon(IconProvider::fromTheme("edit-select-all"));
// Search menu
ui->actionSearch->setIcon(IconProvider::fromTheme("edit-find"));
ui->actionFind_Next->setIcon(IconProvider::fromTheme("go-next"));
ui->actionFind_Previous->setIcon(IconProvider::fromTheme("go-previous"));
ui->actionReplace->setIcon(IconProvider::fromTheme("edit-find-replace"));
ui->actionGo_to_Line->setIcon(IconProvider::fromTheme("go-jump"));
// View menu
ui->actionShow_All_Characters->setIcon(IconProvider::fromTheme("show-special-chars"));
ui->actionZoom_In->setIcon(IconProvider::fromTheme("zoom-in"));
ui->actionZoom_Out->setIcon(IconProvider::fromTheme("zoom-out"));
ui->actionRestore_Default_Zoom->setIcon(IconProvider::fromTheme("zoom-original"));
ui->actionWord_wrap->setIcon(IconProvider::fromTheme("word-wrap"));
ui->actionMath_Rendering->setIcon(IconProvider::fromTheme("math-rendering"));
ui->actionFull_Screen->setIcon(IconProvider::fromTheme("view-fullscreen"));
// Settings menu
ui->actionPreferences->setIcon(IconProvider::fromTheme("preferences-other"));
// Run menu
ui->actionRun->setIcon(IconProvider::fromTheme("system-run"));
// Window menu
ui->actionOpen_a_New_Window->setIcon(IconProvider::fromTheme("window-new"));
// '?' menu
ui->actionAbout_Qt->setIcon(IconProvider::fromTheme("help-about"));
ui->actionAbout_Notepadqq->setIcon(IconProvider::fromTheme("notepadqq"));
// Macros in toolbar
ui->action_Start_Recording->setIcon(IconProvider::fromTheme("media-record"));
ui->action_Stop_Recording->setIcon(IconProvider::fromTheme("media-playback-stop"));
ui->action_Playback->setIcon(IconProvider::fromTheme("media-playback-start"));
ui->actionRun_a_Macro_Multiple_Times->setIcon(IconProvider::fromTheme("media-seek-forward"));
ui->actionSave_Currently_Recorded_Macro->setIcon(IconProvider::fromTheme("document-save-as"));
}
void MainWindow::configureStatusBar()
{
m_sbDocumentInfoLabel = new QLabel;
m_sbDocumentInfoLabel->setMinimumWidth(1);
statusBar()->addWidget(m_sbDocumentInfoLabel);
auto createStatusButton = [&](const QString& txt, QMenu* mnu = nullptr) {
auto* btn = new QPushButton(txt);
btn->setFlat(true);
btn->setMenu(mnu);
btn->setFocusPolicy(Qt::NoFocus);
#ifdef Q_OS_MACX
// MacOS style issues workaround (see #708)
btn->setStyleSheet(QString("QPushButton { background: %1; }").arg(QPalette().shadow().color().name()));
#endif
statusBar()->addPermanentWidget(btn);
return btn;
};
m_sbFileFormatBtn = createStatusButton("File Format", ui->menu_Language);
m_sbEOLFormatBtn = createStatusButton("EOL", ui->menuEOL_Conversion);
m_sbTextFormatBtn = createStatusButton("Encoding", ui->menu_Encoding);
m_sbOvertypeBtn = createStatusButton("INS");
connect(m_sbOvertypeBtn, &QPushButton::clicked, this, &MainWindow::toggleOverwrite);
}
void MainWindow::loadToolBar()
{
m_mainToolBar->clear();
QString toolbarItems = m_settings.MainWindow.getToolBarItems();
if(toolbarItems.isEmpty())
toolbarItems = getDefaultToolBarString();
auto actions = getActions();
auto parts = toolbarItems.split('|', QString::SkipEmptyParts);
for (const auto& part : parts) {
if(part == "Separator") {
m_mainToolBar->addSeparator();
continue;
}
auto it = std::find_if(actions.begin(), actions.end(), [&part](QAction* ac) {
return ac->objectName() == part;
});
if(it != actions.end())
m_mainToolBar->addAction( *it );
}
}
bool MainWindow::saveTabsToCache()
{
// If saveSession() returns false, something went wrong. Most likely writing to the .xml file.
while (!Sessions::saveSession(m_docEngine, m_topEditorContainer, PersistentCache::cacheSessionPath(), PersistentCache::cacheDirPath())) {
QMessageBox msgBox;
msgBox.setWindowTitle(QCoreApplication::applicationName());
msgBox.setText(tr("Error while trying to save this session. Please ensure the following directory is accessible:\n\n") +
PersistentCache::cacheDirPath() + "\n\n" +
tr("By choosing \"ignore\" your session won't be saved."));
msgBox.setStandardButtons(QMessageBox::Abort | QMessageBox::Retry | QMessageBox::Ignore);
msgBox.setDefaultButton(QMessageBox::Retry);
msgBox.setIcon(QMessageBox::Critical);
int result = msgBox.exec();
if (result == QMessageBox::Abort) {
return false;
} else if (result == QMessageBox::Ignore) {
// Do as if all went well
return true;
}
}
return true;
}
bool MainWindow::finalizeAllTabs()
{
//Close all tabs normally
int tabWidgetsCount = m_topEditorContainer->count();
for (int i = 0; i < tabWidgetsCount; i++) {
EditorTabWidget *tabWidget = m_topEditorContainer->tabWidget(i);
int tabCount = tabWidget->count();
for (int j = 0; j < tabCount; j++) {
int closeResult = closeTab(tabWidget, j, false, false);
if (closeResult == MainWindow::tabCloseResult_Canceled) {
return false;
}
}
}
return true;
}
QList<const QMenu*> MainWindow::getMenus() const {
return ui->menuBar->findChildren<const QMenu*>(QString(), Qt::FindDirectChildrenOnly);
}
DocEngine* MainWindow::getDocEngine() const
{
return m_docEngine;
}
//Return a list of all available action items in the menu
QList<QAction*> MainWindow::getActions() const
{
const QList<const QMenu*> list = ui->menuBar->findChildren<const QMenu*>();
QList<QAction*> allActions;
for (auto&& menu : list) {
if (menu->title() == "&Language")
continue;
for (auto&& action : menu->actions()) {
allActions.append(action);
}
}
return allActions;
}
void MainWindow::setupLanguagesMenu()
{
std::map<QChar, QMenu*> menuInitials;
for (const auto& l : LanguageService::getInstance().languages()) {
QString id = l.id;
QChar letter = l.name.isEmpty() ? '?' : l.name.at(0).toUpper();
QMenu *letterMenu;
if (menuInitials.count(letter) != 0) {
letterMenu = menuInitials[letter];
} else {
letterMenu = new QMenu(letter, this);
menuInitials.emplace(std::make_pair(letter, letterMenu));
ui->menu_Language->insertMenu(0, letterMenu);
}
QAction *action = new QAction(l.name, this);
connect(action, &QAction::triggered, this, [id, this](bool = false) {
currentEditor()->setLanguage(id);
});
letterMenu->insertAction(0, action);
}
}
void MainWindow::fixKeyboardShortcuts()
{
QList<QMenu*> lst;
lst = ui->menuBar->findChildren<QMenu*>();
foreach (QMenu* m, lst)
{
addAction(m->menuAction());
addActions(m->actions());
}
}
QUrl MainWindow::stringToUrl(QString fileName, QString workingDirectory)
{
if (workingDirectory.isEmpty())
workingDirectory = m_workingDirectory;
QUrl f = QUrl(fileName);
if (f.isRelative()) { // No schema
QFileInfo fi(fileName);
if (fi.isRelative()) { // Relative local path
QString absolute = QDir::cleanPath(workingDirectory + QDir::separator() + fileName);
return QUrl::fromLocalFile(absolute);
} else {
return QUrl::fromLocalFile(fileName);
}
} else {
return f;
}
}
void MainWindow::openCommandLineProvidedUrls(const QString &workingDirectory, const QStringList &arguments)
{
const int currentlyOpenTabs = m_topEditorContainer->currentTabWidget()->count();
if (arguments.count() == 0) {
if(currentlyOpenTabs==0){
ui->actionNew->trigger();
}
return;
}
QSharedPointer<QCommandLineParser> parser = Notepadqq::getCommandLineArgumentsParser(arguments);
QStringList rawUrls = parser->positionalArguments();
if (rawUrls.count() == 0 && currentlyOpenTabs == 0)
{
// Open a new empty document
ui->actionNew->trigger();
return;
}
// Open selected files
QList<QUrl> files;
for(int i = 0; i < rawUrls.count(); i++)
{
files.append(stringToUrl(rawUrls.at(i), workingDirectory));
}
m_docEngine->getDocumentLoader()
.setUrls(files)
.setTabWidget(m_topEditorContainer->currentTabWidget())
.execute()
.wait(); // FIXME Transform to async
// Handle --line and --column commandline arguments
if (!parser->isSet("line") && !parser->isSet("column"))
return;
if (rawUrls.size() > 1) {
qWarning() << tr("The '--line' and '--column' arguments will be ignored since more than one file is opened.");
return;
}
int l = 0;
if (parser->isSet("line")) {
bool okay;
l = parser->value("line").toInt(&okay);
if(!okay)
qWarning() << tr("Invalid value for '--line' argument: %1").arg(parser->value("line"));
}
int c = 0;
if (parser->isSet("column")) {
bool okay;
c = parser->value("column").toInt(&okay);
if(!okay)
qWarning() << tr("Invalid value for '--column' argument: %1").arg(parser->value("column"));
}
// This needs to sit inside a timer because CodeMirror apparently chokes on receiving a setCursorPosition()
// right after construction of the Editor.
auto ed = m_topEditorContainer->currentTabWidget()->currentEditor();
QTimer* t = new QTimer();
connect(t, &QTimer::timeout, [t, l, c, ed](){
ed->setCursorPosition(l-1, c-1);
t->deleteLater();
});
t->start(0);
}
void MainWindow::dragEnterEvent(QDragEnterEvent *e)
{
QMainWindow::dragEnterEvent(e);
if (e->mimeData()->hasUrls()) {
e->acceptProposedAction();
}
}
void MainWindow::dropEvent(QDropEvent *e)
{
QMainWindow::dropEvent(e);
QList<QUrl> fileNames = e->mimeData()->urls();
if (fileNames.empty())
return;
m_docEngine->getDocumentLoader()
.setUrls(fileNames)
.setTabWidget(m_topEditorContainer->currentTabWidget())
.execute();
}
void MainWindow::on_editorUrlsDropped(QList<QUrl> urls)
{
EditorTabWidget *tabWidget;
Editor *editor = dynamic_cast<Editor *>(sender());
if (editor) {
tabWidget = m_topEditorContainer->tabWidgetFromEditor(editor);
} else {
tabWidget = m_topEditorContainer->currentTabWidget();
}
if (urls.empty())
return;
// If only one URL is dropped and it's a directory, we query the dir's entry list and open that one instead.
if (urls.size() == 1) {
const QString path = urls.front().toLocalFile();
QFileInfo fileInfo(path);
if (fileInfo.isDir()) {
urls.clear();
for (QFileInfo fi : QDir(path).entryInfoList(QDir::Files)) {
urls.push_back(QUrl::fromLocalFile(fi.filePath()));
}
}
}
m_docEngine->getDocumentLoader()
.setUrls(urls)
.setTabWidget(tabWidget)
.execute();
}
void MainWindow::keyPressEvent(QKeyEvent *ev)
{
if (ev->key() == Qt::Key_Insert) {
if (QApplication::keyboardModifiers().testFlag(Qt::ShiftModifier)) {
on_actionPaste_triggered();
} else if (QApplication::keyboardModifiers().testFlag(Qt::ControlModifier)) {
on_actionCopy_triggered();
} else {
toggleOverwrite();
}
} else if (ev->key() >= Qt::Key_1 && ev->key() <= Qt::Key_9
&& QApplication::keyboardModifiers().testFlag(Qt::AltModifier)) {
m_topEditorContainer->currentTabWidget()->setCurrentIndex(ev->key() - Qt::Key_1);
} else if (QApplication::keyboardModifiers().testFlag(Qt::ControlModifier)
&& ev->key() == Qt::Key_PageDown) {
// switch to the next tab to the right or wrap around if last
EditorTabWidget *curTabWidget = m_topEditorContainer->currentTabWidget();
int nextTabIndex = (curTabWidget->currentIndex() + 1) % curTabWidget->count();
curTabWidget->setCurrentIndex(nextTabIndex);
} else if (QApplication::keyboardModifiers().testFlag(Qt::ControlModifier)
&& ev->key() == Qt::Key_PageUp) {
// switch to the previous tab or wrap around if first
EditorTabWidget *curTabWidget = m_topEditorContainer->currentTabWidget();
int prevTabIndex = (curTabWidget->currentIndex() + curTabWidget->count() - 1)
% curTabWidget->count();
curTabWidget->setCurrentIndex(prevTabIndex);
} else {
QMainWindow::keyPressEvent(ev);
}
}
void MainWindow::changeEvent(QEvent *e)
{
if (e->type() == QEvent::ActivationChange) {
if (isActiveWindow()) {
if (m_instances.length() > 0 && m_instances.last() != this) {
int pos = m_instances.indexOf(this);
if (pos > -1) {
// Move this instance at the end of the list
m_instances.move(pos, m_instances.length() - 1);
}
}
}
}
}
void MainWindow::toggleOverwrite()
{
m_overwrite = !m_overwrite;
m_topEditorContainer->forEachEditor([&](const int /*tabWidgetId*/, const int /*editorId*/, EditorTabWidget */*tabWidget*/, QSharedPointer<Editor> editor) {
editor->setOverwrite(m_overwrite);
return true;
});
if (m_overwrite) {
m_sbOvertypeBtn->setText(tr("OVR"));
} else {
m_sbOvertypeBtn->setText(tr("INS"));
}
}
void MainWindow::on_actionNew_triggered()
{
EditorTabWidget *tabW = m_topEditorContainer->currentTabWidget();
m_docEngine->addNewDocument(m_docEngine->getNewDocumentName(), true, tabW);
}
void MainWindow::setCurrentEditorLanguage(QString language)
{
currentEditor()->setLanguage(language);
}
void MainWindow::on_customTabContextMenuRequested(QPoint point, EditorTabWidget * /*tabWidget*/, int /*tabIndex*/)
{
m_tabContextMenu->exec(point);
}
bool MainWindow::updateSymbols(bool on)
{
// Save the currently toggled symbols when deactivating Show_All_Characters using
// one of the other available symbol actions.
if (!on && ui->actionShow_All_Characters->isChecked()) {
m_settings.General.setTabsVisible(ui->actionShow_Tabs->isChecked());
m_settings.General.setSpacesVisisble(ui->actionShow_Spaces->isChecked());
m_settings.General.setShowEOL(ui->actionShow_End_of_Line->isChecked());
ui->actionShow_All_Characters->blockSignals(true);
ui->actionShow_All_Characters->setChecked(false);
ui->actionShow_All_Characters->blockSignals(false);
m_settings.General.setShowAllSymbols(false);
return true;
} else if (on && !ui->actionShow_All_Characters->isChecked()) {
bool showEOL = ui->actionShow_End_of_Line->isChecked();
bool showTabs = ui->actionShow_Tabs->isChecked();
bool showSpaces = ui->actionShow_Spaces->isChecked();
if (showEOL && showTabs && showSpaces) {
ui->actionShow_All_Characters->setChecked(true);
}
}
return false;
}
void MainWindow::on_actionShow_Tabs_triggered(bool on)
{
m_topEditorContainer->forEachEditorConcurrent([&](const int /*tabWidgetId*/, const int /*editorId*/, EditorTabWidget */*tabWidget*/, QSharedPointer<Editor> editor, std::function<void()> done) {
editor->setTabsVisible(on);
done();
});
if (!updateSymbols(on)) {
m_settings.General.setTabsVisible(on);
}
}
void MainWindow::on_actionShow_Spaces_triggered(bool on)
{
m_topEditorContainer->forEachEditorConcurrent([&](const int /*tabWidgetId*/, const int /*editorId*/, EditorTabWidget */*tabWidget*/, QSharedPointer<Editor> editor, std::function<void()> done) {
editor->setWhitespaceVisible(on);
done();
});
if (!updateSymbols(on)) {
m_settings.General.setSpacesVisisble(on);
}
}
void MainWindow::on_actionShow_End_of_Line_triggered(bool on)
{
m_topEditorContainer->forEachEditorConcurrent([&](const int /*tabWidgetId*/, const int /*editorId*/, EditorTabWidget */*tabWidget*/, QSharedPointer<Editor> editor, std::function<void()> done) {
editor->setEOLVisible(on);
done();
});
if (!updateSymbols(on)) {
m_settings.General.setShowEOL(on);
}
}
void MainWindow::on_actionShow_All_Characters_toggled(bool on)
{
if (on) {
ui->actionShow_End_of_Line->setChecked(true);
ui->actionShow_Tabs->setChecked(true);
ui->actionShow_Spaces->setChecked(true);
} else {
bool showEOL = m_settings.General.getShowEOL();
bool showTabs = m_settings.General.getTabsVisible();
bool showSpaces = m_settings.General.getSpacesVisisble();
if (showEOL && showTabs && showSpaces) {
showEOL = !showEOL;
showTabs = !showTabs;
showSpaces = !showSpaces;
}
ui->actionShow_End_of_Line->setChecked(showEOL);
ui->actionShow_Tabs->setChecked(showTabs);
ui->actionShow_Spaces->setChecked(showSpaces);
}
m_topEditorContainer->forEachEditorConcurrent([&](const int /*tabWidgetId*/, const int /*editorId*/, EditorTabWidget */*tabWidget*/, QSharedPointer<Editor> editor, std::function<void()> done) {
editor->setEOLVisible(ui->actionShow_End_of_Line->isChecked());
editor->setTabsVisible(ui->actionShow_Tabs->isChecked());
editor->setWhitespaceVisible(on);
done();
});
m_settings.General.setShowAllSymbols(on);
}
void MainWindow::on_actionMath_Rendering_toggled(bool on)
{
m_topEditorContainer->forEachEditorConcurrent([&](const int /*tabWidgetId*/, const int /*editorId*/, EditorTabWidget */*tabWidget*/, QSharedPointer<Editor> editor, std::function<void()> done) {
editor->setMathEnabled(on);
done();
});
m_settings.General.setMathRendering(on);
}
void MainWindow::on_actionMove_to_Other_View_triggered()
{
EditorTabWidget *curTabWidget = m_topEditorContainer->currentTabWidget();
EditorTabWidget *destTabWidget = m_topEditorContainer->inactiveTabWidget(true);
destTabWidget->transferEditorTab(true, curTabWidget, curTabWidget->currentIndex());
removeTabWidgetIfEmpty(curTabWidget);
}
void MainWindow::removeTabWidgetIfEmpty(EditorTabWidget *tabWidget) {
if(tabWidget->count() == 0) {
delete tabWidget;
}
}
void MainWindow::on_actionOpen_triggered()
{
QUrl defaultUrl = currentEditor()->filePath();
if (defaultUrl.isEmpty())
defaultUrl = QUrl::fromLocalFile(m_settings.General.getLastSelectedDir());
// See https://github.com/notepadqq/notepadqq/issues/654
BackupServicePauser bsp; bsp.pause();
auto dialogOption =
m_settings.General.getUseNativeFilePicker() ? QFileDialog::Options() : QFileDialog::DontUseNativeDialog;
QList<QUrl> fileNames =
QFileDialog::getOpenFileUrls(this, tr("Open"), defaultUrl, tr("All files (*)"), nullptr, dialogOption);
if (fileNames.empty())
return;
m_docEngine->getDocumentLoader()
.setUrls(fileNames)
.setTabWidget(m_topEditorContainer->currentTabWidget())
.execute();
}
void MainWindow::on_actionOpen_Folder_triggered()
{
QUrl defaultUrl = currentEditor()->filePath();
if (defaultUrl.isEmpty())
defaultUrl = QUrl::fromLocalFile(m_settings.General.getLastSelectedDir());
// See https://github.com/notepadqq/notepadqq/issues/654
BackupServicePauser bsp; bsp.pause();
auto dialogOption =
m_settings.General.getUseNativeFilePicker() ? QFileDialog::Options() : QFileDialog::DontUseNativeDialog;
// Select directory
QString folder = QFileDialog::getExistingDirectory(this, tr("Open Folder"), defaultUrl.toLocalFile(), dialogOption);
if (folder.isEmpty())
return;
// Get files within directory
QDir dir(folder);
QStringList files = dir.entryList(QStringList(), QDir::Files);
// Convert file names to urls
QList<QUrl> fileNames;
for (QString file : files) {
// Exclude hidden and backup files
if (!file.startsWith(".") && !file.endsWith("~")) {
fileNames.append(stringToUrl(file, folder));
}
}
if (fileNames.isEmpty())
return;
m_docEngine->getDocumentLoader()
.setUrls(fileNames)
.setTabWidget(m_topEditorContainer->currentTabWidget())
.execute();
}
int MainWindow::askIfWantToSave(EditorTabWidget *tabWidget, int tab, int reason)
{
QMessageBox msgBox(this);
QString name = tabWidget->tabText(tab).toHtmlEscaped();
msgBox.setWindowTitle(QCoreApplication::applicationName());
msgBox.setStandardButtons(QMessageBox::Save | QMessageBox::Discard | QMessageBox::Cancel);
switch(reason)
{
case askToSaveChangesReason_generic:
msgBox.setText("<h3>" + tr("Do you want to save changes to «%1»?").arg(name) + "</h3>");
msgBox.setButtonText(QMessageBox::Discard, tr("Don't Save"));
break;
case askToSaveChangesReason_tabClosing:
msgBox.setText("<h3>" + tr("Do you want to save changes to «%1» before closing?").arg(name) + "</h3>");
break;
}
msgBox.setInformativeText(tr("If you don't save the changes you made, you'll lose them forever."));
msgBox.setDefaultButton(QMessageBox::Save);
msgBox.setEscapeButton(QMessageBox::Cancel);
QPixmap img = IconProvider::fromTheme("document-save").pixmap(64,64).scaled(64,64,Qt::KeepAspectRatio, Qt::SmoothTransformation);
msgBox.setIconPixmap(img);
msgBox.exec();
return msgBox.standardButton(msgBox.clickedButton());
}
int MainWindow::closeTab(EditorTabWidget *tabWidget, int tab, bool remove, bool force)
{
int result = MainWindow::tabCloseResult_AlreadySaved;
auto editor = tabWidget->editor(tab);
// If the tab is the only existing one, is not associated with a file, and has no contents,
// we'll not close it.
if ( m_topEditorContainer->count()==1 && tabWidget->count()==1 &&
editor->filePath().isEmpty() && editor->value().isEmpty()) {
// If user tried to close last open (clean) tab, check if Nqq should just quit.
if(m_settings.General.getExitOnLastTabClose())
close();
goto cleanup;
}
if (force || editor->isClean() || (editor->filePath().isEmpty() && editor->value().isEmpty())) {
if (remove) m_docEngine->closeDocument(tabWidget, tab);
goto cleanup;
}
// Ask the user to choose what to do with the modified contents.
tabWidget->setCurrentIndex(tab);
switch(askIfWantToSave(tabWidget, tab, askToSaveChangesReason_tabClosing)) {
case QMessageBox::Save: {
switch(save(tabWidget, tab)) {
case DocEngine::saveFileResult_Canceled:
result = MainWindow::tabCloseResult_Canceled;
break;
case DocEngine::saveFileResult_Saved:
if (remove) m_docEngine->closeDocument(tabWidget, tab);
result = MainWindow::tabCloseResult_Saved;
break;
}
break;
}
case QMessageBox::Discard: {
if (remove) m_docEngine->closeDocument(tabWidget, tab);
result = MainWindow::tabCloseResult_NotSaved;
break;
}
case QMessageBox::Cancel: {
// Don't save and cancel closing
result = MainWindow::tabCloseResult_Canceled;
}
}
// Ensure the focus is still on this tabWidget
if (tabWidget->count() > 0) {
tabWidget->currentEditor()->setFocus();
}
cleanup:
if(tabWidget->count() > 0)
return result;
// If we just closed the last tab we'll either
// * close the tabWidget and switch to a different one,
// * close the editor if ExitOnLastTabClose() is enabled, or
// * open a new tab.
if(m_topEditorContainer->count() > 1) {
delete tabWidget;
m_topEditorContainer->tabWidget(0)->currentEditor()->setFocus();
} else {
if(m_settings.General.getExitOnLastTabClose())
close();
else