-
-
Notifications
You must be signed in to change notification settings - Fork 2.1k
/
MainWindow.cpp
3473 lines (3038 loc) · 150 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 "MainWindow.h"
#include "ui_MainWindow.h"
#include "Application.h"
#include "EditIndexDialog.h"
#include "AboutDialog.h"
#include "EditTableDialog.h"
#include "ImportCsvDialog.h"
#include "ExportDataDialog.h"
#include "Settings.h"
#include "PreferencesDialog.h"
#include "EditDialog.h"
#include "sqlitetablemodel.h"
#include "SqlExecutionArea.h"
#include "VacuumDialog.h"
#include "DbStructureModel.h"
#include "version.h"
#include "sqlite.h"
#include "CipherDialog.h"
#include "ExportSqlDialog.h"
#include "SqlUiLexer.h"
#include "FileDialog.h"
#include "FilterTableHeader.h"
#include "RemoteDock.h"
#include "FindReplaceDialog.h"
#include "RunSql.h"
#include "ExtendedTableWidget.h"
#include "Data.h"
#include <chrono>
#include <QFile>
#include <QTextStream>
#include <QWhatsThis>
#include <QMessageBox>
#include <QPersistentModelIndex>
#include <QDragEnterEvent>
#include <QScrollBar>
#include <QMimeData>
#include <QDesktopServices>
#include <QXmlStreamReader>
#include <QXmlStreamWriter>
#include <QInputDialog>
#include <QProgressDialog>
#include <QTextEdit>
#include <QClipboard>
#include <QShortcut>
#include <QUrlQuery>
#include <QDataStream> // This include seems to only be necessary for the Windows build
#include <QPrinter>
#include <QPrintPreviewDialog>
#include <QToolButton>
#ifdef Q_OS_MACX //Needed only on macOS
#include <QOpenGLWidget>
#endif
#include <limits>
const int MainWindow::MaxRecentFiles;
// These are needed for reading and writing object files
QDataStream& operator>>(QDataStream& ds, sqlb::ObjectIdentifier& objid)
{
// Read in the item
QVariant v;
ds >> v;
// If it is a string list, we can treat it as an object identifier. If it isn't, we assume it's just a
// single string and use interpret it as the table name in the main schema. This is done for backwards
// compatability with old project file formats.
QStringList str = v.toStringList();
if(str.isEmpty())
{
objid = sqlb::ObjectIdentifier("main", v.toString().toStdString());
} else {
objid.setSchema(str.first().toStdString());
if(str.size() >= 2)
objid.setName(str.last().toStdString());
}
return ds;
}
// This is a temporary helper function. Delete it once we clean up the project file loading.
static std::vector<sqlb::SortedColumn> toSortOrderVector(int index, Qt::SortOrder mode)
{
std::vector<sqlb::SortedColumn> vector;
vector.emplace_back(index, mode == Qt::AscendingOrder ? sqlb::Ascending : sqlb::Descending);
return vector;
}
MainWindow::MainWindow(QWidget* parent)
: QMainWindow(parent),
ui(new Ui::MainWindow),
db(),
editDock(new EditDialog(this)),
plotDock(new PlotDock(this)),
remoteDock(new RemoteDock(this)),
findReplaceDialog(new FindReplaceDialog(this)),
execute_sql_worker(nullptr),
isProjectModified(false)
{
ui->setupUi(this);
init();
activateFields(false);
updateRecentFileActions();
}
MainWindow::~MainWindow()
{
delete ui;
}
void MainWindow::init()
{
// Load window settings
tabifyDockWidget(ui->dockLog, ui->dockPlot);
tabifyDockWidget(ui->dockLog, ui->dockSchema);
tabifyDockWidget(ui->dockLog, ui->dockRemote);
#ifdef Q_OS_MACX
// Add OpenGL Context for macOS
QOpenGLWidget *ogl = new QOpenGLWidget(this);
ui->verticalLayout->addWidget(ogl);
ogl->setHidden(true);
#endif
// Automatic update check
#ifdef CHECKNEWVERSION
connect(&RemoteNetwork::get(), &RemoteNetwork::networkReady, [this]() {
// Check for a new version if automatic update check aren't disabled in the settings dialog
if(Settings::getValue("checkversion", "enabled").toBool())
{
RemoteNetwork::get().fetch(QUrl("https://download.sqlitebrowser.org/currentrelease"), RemoteNetwork::RequestTypeCustom,
QString(), [this](const QByteArray& reply) {
QList<QByteArray> info = reply.split('\n');
if(info.size() >= 2)
{
QString version = info.at(0).trimmed();
QString url = info.at(1).trimmed();
checkNewVersion(version, url);
}
});
}
});
#endif
// Connect SQL logging and database state setting to main window
connect(&db, &DBBrowserDB::dbChanged, this, &MainWindow::dbState, Qt::QueuedConnection);
connect(&db, &DBBrowserDB::sqlExecuted, this, &MainWindow::logSql, Qt::QueuedConnection);
connect(&db, &DBBrowserDB::requestCollation, this, &MainWindow::requestCollation);
// Initialise table browser first
ui->tableBrowser->init(&db);
// Set project modified flag when the settings in the table browser were changed
connect(ui->tableBrowser, &TableBrowser::projectModified, this, [this]() {
isProjectModified = true;
});
connect(ui->tableBrowser->model(), &SqliteTableModel::dataChanged, this, &MainWindow::dataTableSelectionChanged);
connect(ui->tableBrowser, &TableBrowser::selectionChanged, this, &MainWindow::dataTableSelectionChanged);
connect(ui->tableBrowser, &TableBrowser::selectionChangedByDoubleClick, this, &MainWindow::doubleClickTable);
connect(ui->tableBrowser, &TableBrowser::updatePlot, this, &MainWindow::attachPlot);
connect(ui->tableBrowser, &TableBrowser::createView, this, &MainWindow::saveAsView);
connect(ui->tableBrowser, &TableBrowser::requestFileOpen, this, [this](const QString& file) {
fileOpen(file);
});
connect(ui->tableBrowser, &TableBrowser::statusMessageRequested, ui->statusbar, [this](const QString& message) {
ui->statusbar->showMessage(message);
});
m_currentTabTableModel = ui->tableBrowser->model();
// Set up DB structure tab
dbStructureModel = new DbStructureModel(db, this);
connect(&db, &DBBrowserDB::structureUpdated, this, [this]() {
sqlb::ObjectIdentifier old_table = ui->tableBrowser->currentlyBrowsedTableName();
dbStructureModel->reloadData();
populateStructure(old_table);
});
ui->dbTreeWidget->setModel(dbStructureModel);
ui->dbTreeWidget->setColumnWidth(DbStructureModel::ColumnName, 300);
ui->dbTreeWidget->setColumnHidden(DbStructureModel::ColumnObjectType, true);
ui->dbTreeWidget->setColumnHidden(DbStructureModel::ColumnSchema, true);
// Set up DB schema dock
ui->treeSchemaDock->setModel(dbStructureModel);
ui->treeSchemaDock->setColumnHidden(DbStructureModel::ColumnObjectType, true);
ui->treeSchemaDock->setColumnHidden(DbStructureModel::ColumnSchema, true);
// Set up the table combo box in the Browse Data tab
ui->tableBrowser->setStructure(dbStructureModel);
// Create docks
ui->dockEdit->setWidget(editDock);
ui->dockPlot->setWidget(plotDock);
ui->dockRemote->setWidget(remoteDock);
// Set up edit dock
editDock->setReadOnly(true);
// Restore window geometry
restoreGeometry(Settings::getValue("MainWindow", "geometry").toByteArray());
// Save default and restore window state
defaultWindowState = saveState();
restoreState(Settings::getValue("MainWindow", "windowState").toByteArray());
// Save default and restore open tab order if the openTabs setting is saved.
defaultOpenTabs = saveOpenTabs();
restoreOpenTabs(Settings::getValue("MainWindow", "openTabs").toString());
// Restore dock state settings
ui->comboLogSubmittedBy->setCurrentIndex(ui->comboLogSubmittedBy->findText(Settings::getValue("SQLLogDock", "Log").toString()));
// Add keyboard shortcuts
QShortcut* shortcutBrowseRefreshF5 = new QShortcut(QKeySequence("F5"), this);
connect(shortcutBrowseRefreshF5, &QShortcut::activated, this, &MainWindow::refresh);
QShortcut* shortcutBrowseRefreshCtrlR = new QShortcut(QKeySequence("Ctrl+R"), this);
connect(shortcutBrowseRefreshCtrlR, &QShortcut::activated, this, &MainWindow::refresh);
// Add print shortcut for the DB Structure tab (dbTreeWidget) with context to the widget, so other print shortcuts aren't eclipsed.
QShortcut* shortcutPrint = new QShortcut(QKeySequence(QKeySequence::Print), ui->dbTreeWidget, nullptr, nullptr, Qt::WidgetShortcut);
connect(shortcutPrint, &QShortcut::activated, this, &MainWindow::printDbStructure);
QShortcut* closeTabShortcut = new QShortcut(tr("Ctrl+W"), ui->tabSqlAreas, nullptr, nullptr, Qt::WidgetWithChildrenShortcut);
connect(closeTabShortcut, &QShortcut::activated, this, [this]() {
if(ui->tabSqlAreas->currentIndex() >= 0)
closeSqlTab(ui->tabSqlAreas->currentIndex());
});
// Create the actions for the recently opened dbs list
for(int i = 0; i < MaxRecentFiles; ++i) {
recentFileActs[i] = new QAction(this);
recentFileActs[i]->setVisible(false);
connect(recentFileActs[i], &QAction::triggered, this, &MainWindow::openRecentFile);
}
for(int i = 0; i < MaxRecentFiles; ++i)
ui->fileMenu->insertAction(ui->fileExitAction, recentFileActs[i]);
recentSeparatorAct = ui->fileMenu->insertSeparator(ui->fileExitAction);
// Create popup menus
popupTableMenu = new QMenu(this);
popupTableMenu->addAction(ui->actionEditBrowseTable);
popupTableMenu->addAction(ui->editModifyObjectAction);
popupTableMenu->addAction(ui->editDeleteObjectAction);
popupTableMenu->addSeparator();
popupTableMenu->addAction(ui->actionEditCopyCreateStatement);
popupTableMenu->addAction(ui->actionExportCsvPopup);
popupSchemaDockMenu = new QMenu(this);
popupSchemaDockMenu->addAction(ui->actionPopupSchemaDockBrowseTable);
popupSchemaDockMenu->addSeparator();
popupSchemaDockMenu->addAction(ui->actionDropQualifiedCheck);
popupSchemaDockMenu->addAction(ui->actionEnquoteNamesCheck);
popupOpenDbMenu = new QMenu(this);
popupOpenDbMenu->addAction(ui->fileOpenAction);
popupOpenDbMenu->addAction(ui->fileOpenReadOnlyAction);
ui->fileOpenActionPopup->setMenu(popupOpenDbMenu);
popupSaveSqlFileMenu = new QMenu(this);
popupSaveSqlFileMenu->addAction(ui->actionSqlSaveFile);
popupSaveSqlFileMenu->addAction(ui->actionSqlSaveFileAs);
ui->actionSqlSaveFilePopup->setMenu(popupSaveSqlFileMenu);
popupSaveSqlResultsMenu = new QMenu(this);
popupSaveSqlResultsMenu->addAction(ui->actionSqlResultsExportCsv);
popupSaveSqlResultsMenu->addAction(ui->actionSqlResultsSaveAsView);
ui->actionSqlResultsSave->setMenu(popupSaveSqlResultsMenu);
qobject_cast<QToolButton*>(ui->toolbarSql->widgetForAction(ui->actionSqlResultsSave))->setPopupMode(QToolButton::InstantPopup);
// Add menu item for log dock
ui->viewMenu->insertAction(ui->viewDBToolbarAction, ui->dockLog->toggleViewAction());
ui->viewMenu->actions().at(0)->setShortcut(QKeySequence(tr("Ctrl+L")));
ui->viewMenu->actions().at(0)->setIcon(QIcon(":/icons/log_dock"));
// Add menu item for plot dock
ui->viewMenu->insertAction(ui->viewDBToolbarAction, ui->dockPlot->toggleViewAction());
ui->viewMenu->actions().at(1)->setShortcut(QKeySequence(tr("Ctrl+D")));
ui->viewMenu->actions().at(1)->setIcon(QIcon(":/icons/log_dock"));
// Add menu item for schema dock
ui->viewMenu->insertAction(ui->viewDBToolbarAction, ui->dockSchema->toggleViewAction());
ui->viewMenu->actions().at(2)->setShortcut(QKeySequence(tr("Ctrl+I")));
ui->viewMenu->actions().at(2)->setIcon(QIcon(":/icons/log_dock"));
// Add menu item for edit dock
ui->viewMenu->insertAction(ui->viewDBToolbarAction, ui->dockEdit->toggleViewAction());
ui->viewMenu->actions().at(3)->setShortcut(QKeySequence(tr("Ctrl+E")));
ui->viewMenu->actions().at(3)->setIcon(QIcon(":/icons/log_dock"));
// Add menu item for plot dock
ui->viewMenu->insertAction(ui->viewDBToolbarAction, ui->dockRemote->toggleViewAction());
ui->viewMenu->actions().at(4)->setIcon(QIcon(":/icons/log_dock"));
// Set checked state if toolbar is visible
ui->viewDBToolbarAction->setChecked(!ui->toolbarDB->isHidden());
ui->viewExtraDBToolbarAction->setChecked(!ui->toolbarExtraDB->isHidden());
ui->viewProjectToolbarAction->setChecked(!ui->toolbarProject->isHidden());
// Add separator between docks and toolbars
ui->viewMenu->insertSeparator(ui->viewDBToolbarAction);
// Connect the tabCloseRequested to the actual closeTab function.
// This must be done before the connections for checking the actions in the View menu so
// they are updated accordingly.
connect(ui->mainTab, &QTabWidget::tabCloseRequested, this, &MainWindow::closeTab);
// Add entries for toggling the visibility of main tabs
for (QWidget* widget : {ui->structure, ui->browser, ui->pragmas, ui->query}) {
QAction* action = ui->viewMenu->addAction(QIcon(":/icons/open_sql"), widget->accessibleName());
action->setObjectName(widget->accessibleName());
action->setCheckable(true);
action->setChecked(ui->mainTab->indexOf(widget) != -1);
connect(action, &QAction::toggled, [=](bool show) { toggleTabVisible(widget, show); });
// Connect tabCloseRequested for setting checked the appropiate menu entry.
// Note these are called after the actual tab is closed only because they are connected
// after connecting closeTab.
connect(ui->mainTab, &QTabWidget::tabCloseRequested, [=](int /*index*/) {
action->setChecked(ui->mainTab->indexOf(widget) != -1);
});
}
ui->viewMenu->addSeparator();
QMenu* layoutMenu = new QMenu(tr("Window Layout"), this);
ui->viewMenu->addMenu(layoutMenu);
QAction* resetLayoutAction = layoutMenu->addAction(tr("Reset Window Layout"));
resetLayoutAction->setShortcut(QKeySequence(tr("Alt+0")));
connect(resetLayoutAction, &QAction::triggered, [=]() {
restoreState(defaultWindowState);
restoreOpenTabs(defaultOpenTabs);
ui->viewDBToolbarAction->setChecked(!ui->toolbarDB->isHidden());
ui->viewExtraDBToolbarAction->setChecked(!ui->toolbarExtraDB->isHidden());
ui->viewProjectToolbarAction->setChecked(!ui->toolbarProject->isHidden());
});
QAction* simplifyLayoutAction = layoutMenu->addAction(tr("Simplify Window Layout"));
simplifyLayoutAction->setShortcut(QKeySequence(tr("Shift+Alt+0")));
connect(simplifyLayoutAction, &QAction::triggered, [=]() {
ui->viewMenu->findChild<QAction *>(ui->pragmas->accessibleName())->activate(QAction::Trigger);
ui->dockLog->hide();
ui->dockPlot->hide();
ui->dockSchema->hide();
ui->dockEdit->hide();
ui->dockRemote->hide();
});
QAction* atBottomLayoutAction = layoutMenu->addAction(tr("Dock Windows at Bottom"));
connect(atBottomLayoutAction, &QAction::triggered, [=]() {
moveDocksTo(Qt::BottomDockWidgetArea);
});
QAction* atLeftLayoutAction = layoutMenu->addAction(tr("Dock Windows at Left Side"));
connect(atLeftLayoutAction, &QAction::triggered, [=]() {
moveDocksTo(Qt::LeftDockWidgetArea);
});
QAction* atTopLayoutAction = layoutMenu->addAction(tr("Dock Windows at Top"));
connect(atTopLayoutAction, &QAction::triggered, [=]() {
moveDocksTo(Qt::TopDockWidgetArea);
});
// Set Alt+[1-4] shortcuts for opening the corresponding tab in that position.
// Note that it is safe to call setCurrentIndex with a tab that is currently closed,
// since setCurrentIndex does nothing in that case.
QShortcut* setTab1Shortcut = new QShortcut(QKeySequence("Alt+1"), this);
connect(setTab1Shortcut, &QShortcut::activated, [this]() { ui->mainTab->setCurrentIndex(0); });
QShortcut* setTab2Shortcut = new QShortcut(QKeySequence("Alt+2"), this);
connect(setTab2Shortcut, &QShortcut::activated, [this]() { ui->mainTab->setCurrentIndex(1); });
QShortcut* setTab3Shortcut = new QShortcut(QKeySequence("Alt+3"), this);
connect(setTab3Shortcut, &QShortcut::activated, [this]() { ui->mainTab->setCurrentIndex(2); });
QShortcut* setTab4Shortcut = new QShortcut(QKeySequence("Alt+4"), this);
connect(setTab4Shortcut, &QShortcut::activated, [this]() { ui->mainTab->setCurrentIndex(3); });
// If we're not compiling in SQLCipher, hide its FAQ link in the help menu
#ifndef ENABLE_SQLCIPHER
ui->actionSqlCipherFaq->setVisible(false);
#endif
// Set statusbar fields
statusBusyLabel = new QLabel(ui->statusbar);
statusBusyLabel->setEnabled(false);
statusBusyLabel->setVisible(false);
statusBusyLabel->setToolTip(tr("The database is currenctly busy."));
ui->statusbar->addPermanentWidget(statusBusyLabel);
statusStopButton = new QToolButton(ui->statusbar);
statusStopButton->setVisible(false);
statusStopButton->setIcon(QIcon(":icons/cancel"));
statusStopButton->setToolTip(tr("Click here to interrupt the currently running query."));
statusStopButton->setMaximumSize(ui->statusbar->geometry().height() - 6, ui->statusbar->geometry().height() - 6);
statusStopButton->setAutoRaise(true);
ui->statusbar->addPermanentWidget(statusStopButton);
statusEncryptionLabel = new QLabel(ui->statusbar);
statusEncryptionLabel->setEnabled(false);
statusEncryptionLabel->setVisible(false);
statusEncryptionLabel->setText(tr("Encrypted"));
statusEncryptionLabel->setToolTip(tr("Database is encrypted using SQLCipher"));
ui->statusbar->addPermanentWidget(statusEncryptionLabel);
statusReadOnlyLabel = new QLabel(ui->statusbar);
statusReadOnlyLabel->setEnabled(false);
statusReadOnlyLabel->setVisible(false);
statusReadOnlyLabel->setText(tr("Read only"));
statusReadOnlyLabel->setToolTip(tr("Database file is read only. Editing the database is disabled."));
ui->statusbar->addPermanentWidget(statusReadOnlyLabel);
statusEncodingLabel = new QLabel(ui->statusbar);
statusEncodingLabel->setEnabled(false);
statusEncodingLabel->setText("UTF-8");
statusEncodingLabel->setToolTip(tr("Database encoding"));
ui->statusbar->addPermanentWidget(statusEncodingLabel);
// When changing the text of the toolbar actions, also automatically change their icon text and their tooltip text
connect(ui->editModifyObjectAction, &QAction::changed, [=]() {
ui->editModifyObjectAction->setIconText(ui->editModifyObjectAction->text());
ui->editModifyObjectAction->setToolTip(ui->editModifyObjectAction->text());
});
connect(ui->editDeleteObjectAction, &QAction::changed, [=]() {
ui->editDeleteObjectAction->setIconText(ui->editDeleteObjectAction->text());
ui->editDeleteObjectAction->setToolTip(ui->editDeleteObjectAction->text());
});
// When clicking the interrupt query button in the status bar, ask SQLite to interrupt the current query
connect(statusStopButton, &QToolButton::clicked, [this]() {
db.interruptQuery();
});
// Connect some more signals and slots
connect(editDock, &EditDialog::recordTextUpdated, this, &MainWindow::updateRecordText);
connect(editDock, &EditDialog::requestUrlOrFileOpen, this, &MainWindow::openUrlOrFile);
connect(ui->dbTreeWidget->selectionModel(), &QItemSelectionModel::currentChanged, this, &MainWindow::changeTreeSelection);
connect(ui->dockEdit, &QDockWidget::visibilityChanged, this, &MainWindow::toggleEditDock);
connect(remoteDock, SIGNAL(openFile(QString)), this, SLOT(fileOpen(QString)));
connect(ui->actionDropQualifiedCheck, &QAction::toggled, dbStructureModel, &DbStructureModel::setDropQualifiedNames);
connect(ui->actionEnquoteNamesCheck, &QAction::toggled, dbStructureModel, &DbStructureModel::setDropEnquotedNames);
connect(&db, &DBBrowserDB::databaseInUseChanged, this, &MainWindow::updateDatabaseBusyStatus);
ui->actionDropQualifiedCheck->setChecked(Settings::getValue("SchemaDock", "dropQualifiedNames").toBool());
ui->actionEnquoteNamesCheck->setChecked(Settings::getValue("SchemaDock", "dropEnquotedNames").toBool());
connect(ui->tableBrowser->model(), &SqliteTableModel::finishedFetch, [this](){
auto& settings = ui->tableBrowser->settings(ui->tableBrowser->currentlyBrowsedTableName());
plotDock->updatePlot(ui->tableBrowser->model(), &settings, true, false);
});
connect(ui->actionSqlStop, &QAction::triggered, [this]() {
if(execute_sql_worker && execute_sql_worker->isRunning())
execute_sql_worker->stop();
});
// Connect tool pragmas
connect(ui->actionIntegrityCheck, &QAction::triggered, [this]() {
runSqlNewTab("PRAGMA integrity_check;", ui->actionIntegrityCheck->text(), "https://www.sqlite.org/pragma.html#pragma_integrity_check");
});
connect(ui->actionQuickCheck, &QAction::triggered, [this]() {
runSqlNewTab("PRAGMA quick_check;", ui->actionQuickCheck->text(), "https://www.sqlite.org/pragma.html#pragma_quick_check");
});
connect(ui->actionForeignKeyCheck, &QAction::triggered, [this]() {
runSqlNewTab("PRAGMA foreign_key_check;", ui->actionForeignKeyCheck->text(), "https://www.sqlite.org/pragma.html#pragma_foreign_key_check");
});
connect(ui->actionOptimize, &QAction::triggered, [this]() {
runSqlNewTab("PRAGMA optimize;", ui->actionOptimize->text(), "https://www.sqlite.org/pragma.html#pragma_optimize");
});
// Action for switching the table via the Database Structure tab
connect(ui->actionPopupSchemaDockBrowseTable, &QAction::triggered, [this]() {
sqlb::ObjectIdentifier obj(ui->treeSchemaDock->model()->data(ui->treeSchemaDock->currentIndex().sibling(ui->treeSchemaDock->currentIndex().row(), DbStructureModel::ColumnSchema), Qt::EditRole).toString().toStdString(),
ui->treeSchemaDock->model()->data(ui->treeSchemaDock->currentIndex().sibling(ui->treeSchemaDock->currentIndex().row(), DbStructureModel::ColumnName), Qt::EditRole).toString().toStdString());
switchToBrowseDataTab(obj);
refresh(); // Required in case the Browse Data tab already was the active main tab
});
// Set other window settings
setAcceptDrops(true);
setWindowTitle(QApplication::applicationName());
// Add the documentation of shortcuts, which aren't otherwise visible in the user interface, to some buttons.
addShortcutsTooltip(ui->actionDbPrint);
addShortcutsTooltip(ui->actionSqlOpenTab);
addShortcutsTooltip(ui->actionSqlPrint);
addShortcutsTooltip(ui->actionExecuteSql, {shortcutBrowseRefreshF5->key(), shortcutBrowseRefreshCtrlR->key()});
addShortcutsTooltip(ui->actionSqlExecuteLine);
addShortcutsTooltip(ui->actionSqlFind);
addShortcutsTooltip(ui->actionSqlFindReplace);
addShortcutsTooltip(ui->actionSqlToggleComment);
// Load all settings
reloadSettings();
#ifndef ENABLE_SQLCIPHER
// Only show encryption menu action when SQLCipher support is enabled
ui->actionEncryption->setVisible(false);
#endif
/* Remove all the '&' signs from the dock titles. On at least Windows and
* OSX, Qt doesn't seem to support them properly, so they end up being
* visible instead of creating a keyboard shortcut
*/
ui->dockEdit->setWindowTitle(ui->dockEdit->windowTitle().remove('&'));
ui->dockLog->setWindowTitle(ui->dockLog->windowTitle().remove('&'));
ui->dockPlot->setWindowTitle(ui->dockPlot->windowTitle().remove('&'));
ui->dockSchema->setWindowTitle(ui->dockSchema->windowTitle().remove('&'));
ui->dockRemote->setWindowTitle(ui->dockRemote->windowTitle().remove('&'));
}
bool MainWindow::fileOpen(const QString& fileName, bool openFromProject, bool readOnly)
{
bool retval = false;
QString wFile = fileName;
// QFile::exist will produce error message if passed empty string.
// Test string length before usage w/ QFile to silence warning
if (wFile.isEmpty() || !QFile::exists(wFile))
{
wFile = FileDialog::getOpenFileName(
OpenDatabaseFile,
this,
tr("Choose a database file")
#ifndef Q_OS_MAC // Filters on OS X are buggy
, FileDialog::getSqlDatabaseFileFilter()
#endif
);
}
// catch situation where user has canceled file selection from dialog
if(!wFile.isEmpty() && QFile::exists(wFile) )
{
// Close the database. If the user didn't want to close it, though, stop here
if (db.isOpen())
if(!fileClose())
return false;
// Try opening it as a project file first
if(loadProject(wFile, readOnly))
{
retval = true;
} else {
// No project file; so it should be a database file
if(db.open(wFile, readOnly))
{
// Close all open but empty SQL tabs
for(int i=ui->tabSqlAreas->count()-1;i>=0;i--)
{
if(qobject_cast<SqlExecutionArea*>(ui->tabSqlAreas->widget(i))->getSql().trimmed().isEmpty())
closeSqlTab(i, true);
}
statusEncodingLabel->setText(db.getPragma("encoding"));
statusEncryptionLabel->setVisible(db.encrypted());
statusReadOnlyLabel->setVisible(db.readOnly());
setCurrentFile(wFile);
if(!openFromProject) {
addToRecentFilesMenu(wFile, readOnly);
// When a new DB file has been open while a project is open, set the project modified.
if(!currentProjectFilename.isEmpty())
isProjectModified = true;
}
if(ui->tabSqlAreas->count() == 0)
openSqlTab(true);
if(ui->mainTab->currentWidget() == ui->browser)
populateTable();
else if(ui->mainTab->currentWidget() == ui->pragmas)
loadPragmas();
// Update remote dock
remoteDock->fileOpened(wFile);
retval = true;
} else {
QMessageBox::warning(this, qApp->applicationName(), tr("Could not open database file.\nReason: %1").arg(db.lastError()));
return false;
}
}
}
return retval;
}
void MainWindow::fileNew()
{
QString fileName = FileDialog::getSaveFileName(
CreateDatabaseFile,
this,
tr("Choose a filename to save under"),
FileDialog::getSqlDatabaseFileFilter());
if(!fileName.isEmpty())
{
if(QFile::exists(fileName))
QFile::remove(fileName);
db.create(fileName);
setCurrentFile(fileName);
addToRecentFilesMenu(fileName);
statusEncodingLabel->setText(db.getPragma("encoding"));
statusEncryptionLabel->setVisible(false);
statusReadOnlyLabel->setVisible(false);
populateTable();
if(ui->tabSqlAreas->count() == 0)
openSqlTab(true);
createTable();
}
}
void MainWindow::fileNewInMemoryDatabase()
{
db.create(":memory:");
setCurrentFile(tr("In-Memory database"));
statusEncodingLabel->setText(db.getPragma("encoding"));
statusEncryptionLabel->setVisible(false);
statusReadOnlyLabel->setVisible(false);
remoteDock->fileOpened(":memory:");
populateTable();
if(ui->tabSqlAreas->count() == 0)
openSqlTab(true);
createTable();
}
void MainWindow::populateStructure(const sqlb::ObjectIdentifier& old_table)
{
// Refresh the structure tab
ui->dbTreeWidget->setRootIndex(dbStructureModel->index(1, 0)); // Show the 'All' part of the db structure
ui->dbTreeWidget->expandToDepth(0);
ui->treeSchemaDock->setRootIndex(dbStructureModel->index(1, 0)); // Show the 'All' part of the db structure
ui->treeSchemaDock->expandToDepth(0);
// Refresh the browse data tab
ui->tableBrowser->setStructure(dbStructureModel, old_table);
// Cancel here if no database is opened
if(!db.isOpen())
return;
// Update table and column names for syntax highlighting
SqlUiLexer::QualifiedTablesMap qualifiedTablesMap;
for(const auto& it : db.schemata)
{
SqlUiLexer::TablesAndColumnsMap tablesToColumnsMap;
for(const auto& jt : it.second)
{
if(jt.second->type() == sqlb::Object::Types::Table || jt.second->type() == sqlb::Object::Types::View)
{
QString objectname = QString::fromStdString(jt.second->name());
sqlb::FieldInfoList fi = jt.second->fieldInformation();
for(const sqlb::FieldInfo& f : fi)
tablesToColumnsMap[objectname].push_back(QString::fromStdString(f.name));
}
}
qualifiedTablesMap[QString::fromStdString(it.first)] = tablesToColumnsMap;
}
SqlTextEdit::sqlLexer->setTableNames(qualifiedTablesMap);
ui->editLogApplication->reloadKeywords();
ui->editLogUser->reloadKeywords();
for(int i=0;i<ui->tabSqlAreas->count();i++)
qobject_cast<SqlExecutionArea*>(ui->tabSqlAreas->widget(i))->getEditor()->reloadKeywords();
// Resize SQL column to fit contents
ui->dbTreeWidget->resizeColumnToContents(DbStructureModel::ColumnSQL);
ui->treeSchemaDock->resizeColumnToContents(DbStructureModel::ColumnSQL);
// Resize also the Name column in the Dock since it has usually
// short content and there is little space there.
ui->treeSchemaDock->resizeColumnToContents(DbStructureModel::ColumnName);
}
void MainWindow::populateTable()
{
// Early exit if the Browse Data tab isn't visible as there is no need to update it in this case
if(ui->mainTab->currentWidget() != ui->browser)
return;
QApplication::setOverrideCursor(Qt::WaitCursor);
ui->tableBrowser->updateTable();
QApplication::restoreOverrideCursor();
}
bool MainWindow::fileClose()
{
// Stop any running SQL statements before closing the database
if(execute_sql_worker && execute_sql_worker->isRunning())
{
if(QMessageBox::warning(this, qApp->applicationName(),
tr("You are still executing SQL statements. Closing the database now will stop their execution, possibly "
"leaving the database in an inconsistent state. Are you sure you want to close the database?"),
QMessageBox::Yes, QMessageBox::Cancel | QMessageBox::Default | QMessageBox::Escape) == QMessageBox::Cancel)
return false;
execute_sql_worker->stop();
execute_sql_worker->wait();
}
// Close the database but stop the closing process here if the user pressed the cancel button in there
if(!db.close())
return false;
setCurrentFile(QString());
loadPragmas();
statusEncryptionLabel->setVisible(false);
statusReadOnlyLabel->setVisible(false);
// Reset the table browser of the Browse Data tab
ui->tableBrowser->reset();
// Clear edit dock
editDock->setCurrentIndex(QModelIndex());
// Clear the SQL Log
ui->editLogApplication->clear();
ui->editLogUser->clear();
ui->editLogErrorLog->clear();
// Remove completion and highlighting for identifiers
SqlTextEdit::sqlLexer->setTableNames(SqlUiLexer::QualifiedTablesMap());
for(int i=0; i < ui->tabSqlAreas->count(); i++)
qobject_cast<SqlExecutionArea*>(ui->tabSqlAreas->widget(i))->getEditor()->reloadKeywords();
// Clear remote dock
remoteDock->fileOpened(QString());
return true;
}
void MainWindow::closeEvent( QCloseEvent* event )
{
if(closeFiles())
{
Settings::setValue("MainWindow", "geometry", saveGeometry());
Settings::setValue("MainWindow", "windowState", saveState());
Settings::setValue("MainWindow", "openTabs", saveOpenTabs());
Settings::setValue("SQLLogDock", "Log", ui->comboLogSubmittedBy->currentText());
Settings::setValue("SchemaDock", "dropQualifiedNames", ui->actionDropQualifiedCheck->isChecked());
Settings::setValue("SchemaDock", "dropEnquotedNames", ui->actionEnquoteNamesCheck->isChecked());
SqlExecutionArea::saveState();
QMainWindow::closeEvent(event);
} else {
event->ignore();
}
}
bool MainWindow::closeFiles()
{
bool ignoreUnattachedBuffers = false;
// Ask for saving all modified open SQL files in their files and all the unattached tabs in a project file.
for(int i=0; i<ui->tabSqlAreas->count(); i++)
// Ask for saving and comply with cancel answer.
if(!askSaveSqlTab(i, ignoreUnattachedBuffers))
return false;
return closeProject();
}
bool MainWindow::closeProject()
{
if(!currentProjectFilename.isEmpty() && isProjectModified) {
QMessageBox::StandardButton reply = QMessageBox::question
(nullptr,
QApplication::applicationName(),
tr("Do you want to save the changes made to the project file '%1'?").
arg(QFileInfo(currentProjectFilename).fileName()),
QMessageBox::Save | QMessageBox::Discard | QMessageBox::Cancel);
switch(reply) {
case QMessageBox::Save:
saveProject();
break;
case QMessageBox::Cancel:
return false;
default:
break;
}
}
currentProjectFilename.clear();
return db.close();
}
void MainWindow::attachPlot(ExtendedTableWidget* tableWidget, SqliteTableModel* model, BrowseDataTableSettings* settings, bool keepOrResetSelection)
{
plotDock->updatePlot(model, settings, true, keepOrResetSelection);
// Disconnect previous connection
disconnect(plotDock, SIGNAL(pointsSelected(int,int)), nullptr, nullptr);
if(tableWidget) {
// Connect plot selection to the current table results widget.
connect(plotDock, SIGNAL(pointsSelected(int,int)), tableWidget, SLOT(selectTableLines(int, int)));
connect(tableWidget, &ExtendedTableWidget::destroyed, plotDock, &PlotDock::resetPlot);
// Disconnect requestUrlOrFileOpen in order to make sure that there is only one connection. Otherwise we can open it several times.
disconnect(tableWidget, &ExtendedTableWidget::requestUrlOrFileOpen, this, &MainWindow::openUrlOrFile);
connect(tableWidget, &ExtendedTableWidget::requestUrlOrFileOpen, this, &MainWindow::openUrlOrFile);
}
}
void MainWindow::refresh()
{
// What the Refresh function does depends on the currently active tab. This way the keyboard shortcuts (F5 and Ctrl+R)
// always perform some meaningful task; they just happen to be context dependent in the function they trigger.
QWidget* currentTab = ui->mainTab->currentWidget();
if (currentTab == ui->structure) {
// Refresh the schema
db.updateSchema();
} else if (currentTab == ui->browser) {
// Refresh the schema and reload the current table
populateTable();
} else if (currentTab == ui->pragmas) {
// Reload pragma values
loadPragmas();
} else if (currentTab == ui->query) {
// (Re-)Run the current SQL query
executeQuery();
}
}
void MainWindow::createTable()
{
EditTableDialog dialog(db, sqlb::ObjectIdentifier(), true, this);
if(dialog.exec())
{
populateTable();
}
}
void MainWindow::createIndex()
{
EditIndexDialog dialog(db, sqlb::ObjectIdentifier(), true, this);
if(dialog.exec())
populateTable();
}
void MainWindow::compact()
{
VacuumDialog dialog(&db, this);
dialog.exec();
}
void MainWindow::deleteObject()
{
// Get name and type of object to delete
sqlb::ObjectIdentifier name(ui->dbTreeWidget->model()->data(ui->dbTreeWidget->currentIndex().sibling(ui->dbTreeWidget->currentIndex().row(), DbStructureModel::ColumnSchema), Qt::EditRole).toString().toStdString(),
ui->dbTreeWidget->model()->data(ui->dbTreeWidget->currentIndex().sibling(ui->dbTreeWidget->currentIndex().row(), DbStructureModel::ColumnName), Qt::EditRole).toString().toStdString());
QString type = ui->dbTreeWidget->model()->data(ui->dbTreeWidget->currentIndex().sibling(ui->dbTreeWidget->currentIndex().row(), DbStructureModel::ColumnObjectType), Qt::EditRole).toString();
// Due to different grammar in languages (e.g. gender or declension), each message must be given separately to translation.
QString message;
if (type == "table")
message = tr("Are you sure you want to delete the table '%1'?\nAll data associated with the table will be lost.");
else if (type == "view")
message = tr("Are you sure you want to delete the view '%1'?");
else if (type == "trigger")
message = tr("Are you sure you want to delete the trigger '%1'?");
else if (type == "index")
message = tr("Are you sure you want to delete the index '%1'?");
// Ask user if he really wants to delete that table
if(QMessageBox::warning(this, QApplication::applicationName(), message.arg(QString::fromStdString(name.name())),
QMessageBox::Yes | QMessageBox::No, QMessageBox::No) == QMessageBox::Yes)
{
// Delete the table
QString statement = QString("DROP %1 %2;").arg(type.toUpper(), QString::fromStdString(name.toString()));
if(!db.executeSQL(statement.toStdString()))
{
if (type == "table")
message = tr("Error: could not delete the table.");
else if (type == "view")
message = tr("Error: could not delete the view.");
else if (type == "trigger")
message = tr("Error: could not delete the trigger.");
else if (type == "index")
message = tr("Error: could not delete the index.");
QString error = tr("Message from database engine:\n%1").arg(db.lastError());
QMessageBox::warning(this, QApplication::applicationName(), message + " " + error);
} else {
populateTable();
changeTreeSelection();
}
}
}
void MainWindow::editObject()
{
if(!ui->dbTreeWidget->selectionModel()->hasSelection())
return;
// Get name and type of the object to edit
sqlb::ObjectIdentifier name(ui->dbTreeWidget->model()->data(ui->dbTreeWidget->currentIndex().sibling(ui->dbTreeWidget->currentIndex().row(), DbStructureModel::ColumnSchema), Qt::EditRole).toString().toStdString(),
ui->dbTreeWidget->model()->data(ui->dbTreeWidget->currentIndex().sibling(ui->dbTreeWidget->currentIndex().row(), DbStructureModel::ColumnName), Qt::EditRole).toString().toStdString());
QString type = ui->dbTreeWidget->model()->data(ui->dbTreeWidget->currentIndex().sibling(ui->dbTreeWidget->currentIndex().row(), DbStructureModel::ColumnObjectType), Qt::EditRole).toString();
if(type == "table")
{
// For a safe and possibly complex table modification we must follow the steps documented in
// https://www.sqlite.org/lang_altertable.html
// Paragraph (first procedure): Making Other Kinds Of Table Schema Changes
QString foreign_keys = db.getPragma("foreign_keys");
if (foreign_keys == "1") {
if(db.getDirty() && QMessageBox::question(this,
QApplication::applicationName(),
tr("Editing the table requires to save all pending changes now.\nAre you sure you want to save the database?"),
QMessageBox::Save | QMessageBox::Default,
QMessageBox::Cancel | QMessageBox::Escape) != QMessageBox::Save)
return;
// Commit all changes so the foreign_keys can be effective.
fileSave();
db.setPragma("foreign_keys", "0");
}
EditTableDialog dialog(db, name, false, this);
bool ok = dialog.exec();
// If foreign_keys were enabled, we must commit or rollback the transaction so the foreign_keys pragma can be restored.
if (foreign_keys == "1") {
if (!db.querySingleValueFromDb("PRAGMA " + sqlb::escapeIdentifier(name.schema()) + ".foreign_key_check").isNull()) {
// Raise warning for accepted modification. When rejected, warn user also since we know now that the table has problems,
// but it wasn't our fault.
if (ok)
QMessageBox::warning(this, QApplication::applicationName(),
tr("Error checking foreign keys after table modification. The changes will be reverted."));
else
QMessageBox::warning(this, QApplication::applicationName(),
tr("This table did not pass a foreign-key check.<br/>"
"You should run 'Tools | Foreign-Key Check' and fix the reported issues."));
db.revertAll();
} else {
// Commit all changes so the foreign_keys can be effective.
fileSave();
}
db.setPragma("foreign_keys", foreign_keys);
}
if(ok) {
ui->tableBrowser->clearFilters();
populateTable();
}
} else if(type == "index") {
EditIndexDialog dialog(db, name, false, this);
if(dialog.exec())
populateTable();
} else if(type == "view") {
sqlb::ViewPtr view = db.getObjectByName<sqlb::View>(name);
runSqlNewTab(QString("DROP VIEW %1;\n%2").arg(QString::fromStdString(name.toString())).arg(QString::fromStdString(view->sql())),
tr("Edit View %1").arg(QString::fromStdString(name.toDisplayString())),
"https://www.sqlite.org/lang_createview.html",
/* autoRun */ false);
} else if(type == "trigger") {
sqlb::TriggerPtr trigger = db.getObjectByName<sqlb::Trigger>(name);
runSqlNewTab(QString("DROP TRIGGER %1;\n%2").arg(QString::fromStdString(name.toString())).arg(QString::fromStdString(trigger->sql())),
tr("Edit Trigger %1").arg(QString::fromStdString(name.toDisplayString())),
"https://www.sqlite.org/lang_createtrigger.html",
/* autoRun */ false);
}
}
void MainWindow::helpWhatsThis()
{
QWhatsThis::enterWhatsThisMode ();
}
void MainWindow::helpAbout()
{
AboutDialog dialog(this);
dialog.exec();
}
void MainWindow::updateRecordText(const QPersistentModelIndex& idx, const QByteArray& text, bool isBlob)
{
m_currentTabTableModel->setTypedData(idx, isBlob, text);
}
void MainWindow::toggleEditDock(bool visible)
{
if (!visible) {
// Update main window
ui->tableBrowser->setFocus();
} else {
// fill edit dock with actual data, when the current index has changed while the dock was invisible.
// (note that this signal is also emitted when the widget is docked or undocked, so we have to avoid
// reloading data when the user is editing and (un)docks the editor).
if (editDock->currentIndex() != ui->tableBrowser->currentIndex())
editDock->setCurrentIndex(ui->tableBrowser->currentIndex());
}
}
void MainWindow::doubleClickTable(const QModelIndex& index)
{
// Cancel on invalid index
if (!index.isValid()) {
return;
}
// * Don't allow editing of other objects than tables and editable views
bool isEditingAllowed = !db.readOnly() && m_currentTabTableModel == ui->tableBrowser->model() &&
ui->tableBrowser->model()->isEditable(index);
// Enable or disable the Apply, Null, & Import buttons in the Edit Cell
// dock depending on the value of the "isEditingAllowed" bool above
editDock->setReadOnly(!isEditingAllowed);
editDock->setCurrentIndex(index);