Repository navigation
Expand file tree
/
Copy pathTableBrowser.cpp
More file actions
1847 lines (1570 loc) · 74.3 KB
/
Copy pathTableBrowser.cpp
File metadata and controls
1847 lines (1570 loc) · 74.3 KB
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 "AddRecordDialog.h"
#include "Application.h"
#include "ColumnDisplayFormatDialog.h"
#include "CondFormatManager.h"
#include "Data.h"
#include "DbStructureModel.h"
#include "ExportDataDialog.h"
#include "FilterTableHeader.h"
#include "TableBrowser.h"
#include "Settings.h"
#include "sqlitedb.h"
#include "sqlitetablemodel.h"
#include "ui_TableBrowser.h"
#include <QClipboard>
#include <QInputDialog>
#include <QMenu>
#include <QMessageBox>
#include <QScrollBar>
#include <QShortcut>
#include <QTextCodec>
#include <QColorDialog>
std::map<sqlb::ObjectIdentifier, BrowseDataTableSettings> TableBrowser::m_settings;
QString TableBrowser::m_defaultEncoding;
TableBrowser::TableBrowser(DBBrowserDB* _db, QWidget* parent) :
QWidget(parent),
ui(new Ui::TableBrowser),
gotoValidator(new QIntValidator(0, 0, this)),
db(_db),
dbStructureModel(nullptr),
m_model(nullptr),
m_adjustRows(false),
m_columnsResized(false),
m_columnSearchLastFoundIndex(-1)
{
ui->setupUi(this);
// Set the validator for the goto line edit
ui->editGoto->setValidator(gotoValidator);
// Set custom placeholder text for global filter field and disable conditional formats
ui->editGlobalFilter->setPlaceholderText(tr("Filter in any column"));
ui->editGlobalFilter->setConditionFormatContextMenuEnabled(false);
// Set up popup menus
popupNewRecordMenu = new QMenu(this);
popupNewRecordMenu->addAction(ui->newRecordAction);
popupNewRecordMenu->addAction(ui->insertValuesAction);
ui->actionNewRecord->setMenu(popupNewRecordMenu);
popupSaveFilterAsMenu = new QMenu(this);
popupSaveFilterAsMenu->addAction(ui->actionFilteredTableExportCsv);
popupSaveFilterAsMenu->addAction(ui->actionFilteredTableExportJson);
popupSaveFilterAsMenu->addAction(ui->actionFilterSaveAsView);
ui->actionSaveFilterAsPopup->setMenu(popupSaveFilterAsMenu);
qobject_cast<QToolButton*>(ui->browseToolbar->widgetForAction(ui->actionSaveFilterAsPopup))->setPopupMode(QToolButton::InstantPopup);
popupHeaderMenu = new QMenu(this);
popupHeaderMenu->addAction(ui->actionShowRowidColumn);
popupHeaderMenu->addAction(ui->actionFreezeColumns);
popupHeaderMenu->addAction(ui->actionHideColumns);
popupHeaderMenu->addAction(ui->actionShowAllColumns);
popupHeaderMenu->addAction(ui->actionSelectColumn);
popupHeaderMenu->addSeparator();
popupHeaderMenu->addAction(ui->actionUnlockViewEditing);
popupHeaderMenu->addAction(ui->actionBrowseTableEditDisplayFormat);
popupHeaderMenu->addSeparator();
popupHeaderMenu->addAction(ui->actionSetTableEncoding);
popupHeaderMenu->addAction(ui->actionSetAllTablesEncoding);
popupHeaderMenu->addSeparator();
popupHeaderMenu->addAction(ui->actionCopyColumnName);
connect(ui->actionSelectColumn, &QAction::triggered, this, [this]() {
ui->dataTable->selectColumn(ui->actionBrowseTableEditDisplayFormat->property("clicked_column").toInt());
});
connect(ui->actionFreezeColumns, &QAction::triggered, this, [this](bool checked) {
if(checked)
freezeColumns(ui->actionBrowseTableEditDisplayFormat->property("clicked_column").toUInt() + 1);
else
freezeColumns(0);
});
// Set up shortcuts
QShortcut* dittoRecordShortcut = new QShortcut(QKeySequence("Ctrl+\""), this, nullptr, nullptr, Qt::WidgetWithChildrenShortcut);
connect(dittoRecordShortcut, &QShortcut::activated, this, [this]() {
int currentRow = ui->dataTable->currentIndex().row();
duplicateRecord(currentRow);
});
// Lambda function for keyboard shortcuts for selecting next/previous table in Browse Data tab
connect(ui->dataTable, &ExtendedTableWidget::switchTable, this, [this](bool next) {
int index = ui->comboBrowseTable->currentIndex();
int num_items = ui->comboBrowseTable->count();
if(next)
{
if(++index >= num_items)
index = 0;
} else {
if(--index < 0)
index = num_items - 1;
}
ui->comboBrowseTable->setCurrentIndex(index);
refresh();
});
// This is a workaround needed for QDarkStyleSheet.
// See https://github.com/ColinDuquesnoy/QDarkStyleSheet/issues/169
QStyledItemDelegate* styledItemDelegate = new QStyledItemDelegate(ui->comboBrowseTable);
ui->comboBrowseTable->setItemDelegate(styledItemDelegate);
// Add the documentation of shortcuts, which aren't otherwise visible in the user interface, to some buttons.
addShortcutsTooltip(ui->actionRefresh, {QKeySequence(tr("Ctrl+R"))});
addShortcutsTooltip(ui->actionPrintTable);
// Set up filters
connect(ui->dataTable->filterHeader(), &FilterTableHeader::filterChanged, this, &TableBrowser::updateFilter);
connect(ui->dataTable->filterHeader(), &FilterTableHeader::filterFocused, this, [this]() {
emit prepareForFilter();
});
connect(ui->dataTable->filterHeader(), &FilterTableHeader::addCondFormat, this, &TableBrowser::addCondFormatFromFilter);
connect(ui->dataTable->filterHeader(), &FilterTableHeader::allCondFormatsCleared, this, &TableBrowser::clearAllCondFormats);
connect(ui->dataTable->filterHeader(), &FilterTableHeader::condFormatsEdited, this, &TableBrowser::editCondFormats);
connect(ui->dataTable, &ExtendedTableWidget::editCondFormats, this, &TableBrowser::editCondFormats);
connect(ui->dataTable, &ExtendedTableWidget::dataAboutToBeEdited, this, &TableBrowser::dataAboutToBeEdited);
// Set up global filter
connect(ui->editGlobalFilter, &FilterLineEdit::filterFocused, this, [this]() {
emit prepareForFilter();
});
connect(ui->editGlobalFilter, &FilterLineEdit::delayedTextChanged, this, [this](const QString& value) {
// Split up filter values
#if QT_VERSION < QT_VERSION_CHECK(5, 14, 0)
QStringList values = value.trimmed().split(" ", QString::SkipEmptyParts);
#else
QStringList values = value.trimmed().split(" ", Qt::SkipEmptyParts);
#endif
std::vector<QString> filters;
std::copy(values.begin(), values.end(), std::back_inserter(filters));
ui->actionClearFilters->setEnabled(m_model->filterCount() > 0 || !ui->editGlobalFilter->text().isEmpty());
// Have they changed?
BrowseDataTableSettings& settings = m_settings[currentlyBrowsedTableName()];
if(filters != settings.globalFilters)
{
// Set global filters
m_model->updateGlobalFilter(filters);
updateRecordsetLabel();
// Save them
settings.globalFilters = filters;
emit projectModified();
}
});
connect(ui->dataTable, &ExtendedTableWidget::doubleClicked, this, &TableBrowser::selectionChangedByDoubleClick);
connect(ui->dataTable->filterHeader(), &FilterTableHeader::sectionClicked, this, &TableBrowser::headerClicked);
connect(ui->dataTable->filterHeader(), &QHeaderView::sectionDoubleClicked, ui->dataTable, &QTableView::selectColumn);
connect(ui->dataTable->verticalScrollBar(), &QScrollBar::valueChanged, this, &TableBrowser::updateRecordsetLabel);
connect(ui->dataTable->horizontalHeader(), &QHeaderView::sectionResized, this, &TableBrowser::updateRecordsetLabel);
connect(ui->dataTable->verticalHeader(), &QHeaderView::sectionResized, this, &TableBrowser::updateRecordsetLabel);
connect(ui->dataTable->horizontalHeader(), &QHeaderView::sectionResized, this, &TableBrowser::updateColumnWidth);
connect(ui->dataTable->horizontalHeader(), &QHeaderView::customContextMenuRequested, this, &TableBrowser::showDataColumnPopupMenu);
connect(ui->dataTable->verticalHeader(), &QHeaderView::customContextMenuRequested, this, &TableBrowser::showRecordPopupMenu);
connect(ui->dataTable, &ExtendedTableWidget::openFileFromDropEvent, this, &TableBrowser::requestFileOpen);
connect(ui->dataTable, &ExtendedTableWidget::selectedRowsToBeDeleted, this, &TableBrowser::deleteRecord);
connect(ui->dataTable, &ExtendedTableWidget::foreignKeyClicked, this, [this](const sqlb::ObjectIdentifier& table, const std::string& column, const QByteArray& value) {
// Just select the column that was just clicked instead of selecting an entire range which
// happens because of the Ctrl and Shift keys.
ui->dataTable->selectionModel()->select(ui->dataTable->currentIndex(), QItemSelectionModel::ClearAndSelect);
// Emit the foreign key clicked signal
emit foreignKeyClicked(table, column, value);
});
connect(ui->actionAddDock, &QAction::triggered, this, [this]() {
emit newDockRequested();
});
connect(ui->actionRefresh, &QAction::triggered, this, [this]() {
db->updateSchema();
refresh();
});
connect(ui->fontComboBox, &QFontComboBox::currentFontChanged, this, [this](const QFont &font) {
modifyFormat([font](CondFormat& format) { format.setFontFamily(font.family()); });
});
connect(ui->fontSizeBox, static_cast<void (QSpinBox::*)(int)>(&QSpinBox::valueChanged), this,
[this](int pointSize) {
modifyFormat([pointSize](CondFormat& format) { format.setFontPointSize(pointSize); });
});
connect(ui->actionFontColor, &QAction::triggered, this, [this]() {
QColor color = QColorDialog::getColor(QColor(m_model->data(currentIndex(), Qt::ForegroundRole).toString()));
if(color.isValid())
modifyFormat([color](CondFormat& format) { format.setForegroundColor(color); });
});
connect(ui->actionBackgroundColor, &QAction::triggered, this, [this]() {
QColor color = QColorDialog::getColor(QColor(m_model->data(currentIndex(), Qt::BackgroundRole).toString()));
if(color.isValid())
modifyFormat([color](CondFormat& format) { format.setBackgroundColor(color); });
});
connect(ui->actionBold, &QAction::toggled, this, [this](bool checked) {
modifyFormat([checked](CondFormat& format) { format.setBold(checked); });
});
connect(ui->actionItalic, &QAction::toggled, this, [this](bool checked) {
modifyFormat([checked](CondFormat& format) { format.setItalic(checked); });
});
connect(ui->actionUnderline, &QAction::toggled, this, [this](bool checked) {
modifyFormat([checked](CondFormat& format) { format.setUnderline(checked); });
});
connect(ui->actionLeftAlign, &QAction::triggered, this, [this]() {
ui->actionLeftAlign->setChecked(true);
ui->actionRightAlign->setChecked(false);
ui->actionCenter->setChecked(false);
ui->actionJustify->setChecked(false);
modifyFormat([](CondFormat& format) { format.setAlignment(CondFormat::AlignLeft); });
});
connect(ui->actionRightAlign, &QAction::triggered, this, [this]() {
ui->actionLeftAlign->setChecked(false);
ui->actionRightAlign->setChecked(true);
ui->actionCenter->setChecked(false);
ui->actionJustify->setChecked(false);
modifyFormat([](CondFormat& format) { format.setAlignment(CondFormat::AlignRight); });
});
connect(ui->actionCenter, &QAction::triggered, this, [this]() {
ui->actionLeftAlign->setChecked(false);
ui->actionRightAlign->setChecked(false);
ui->actionCenter->setChecked(true);
ui->actionJustify->setChecked(false);
modifyFormat([](CondFormat& format) { format.setAlignment(CondFormat::AlignCenter); });
});
connect(ui->actionJustify, &QAction::triggered, this, [this]() {
ui->actionLeftAlign->setChecked(false);
ui->actionRightAlign->setChecked(false);
ui->actionCenter->setChecked(false);
ui->actionJustify->setChecked(true);
modifyFormat([](CondFormat& format) { format.setAlignment(CondFormat::AlignJustify); });
});
connect(ui->actionEditCondFormats, &QAction::triggered, this, [this]() { editCondFormats(static_cast<size_t>(currentIndex().column())); });
connect(ui->actionClearFormat, &QAction::triggered, this, [this]() {
for (const size_t column : ui->dataTable->selectedCols())
clearAllCondFormats(column);
for (const QModelIndex& index : ui->dataTable->selectionModel()->selectedIndexes())
clearRowIdFormats(index);
});
connect(ui->dataTable, &ExtendedTableWidget::currentIndexChanged, this, [this](const QModelIndex ¤t, const QModelIndex &) {
// Get cell current format for updating the format toolbar values. Block signals, so the format change is not reapplied.
QString font_string = m_model->data(current, Qt::FontRole).toString();
QFont font;
if(!font_string.isEmpty())
font.fromString(font_string);
ui->fontComboBox->blockSignals(true);
ui->fontComboBox->setCurrentFont(font);
ui->fontComboBox->blockSignals(false);
ui->fontSizeBox->blockSignals(true);
ui->fontSizeBox->setValue(font.pointSize());
ui->fontSizeBox->blockSignals(false);
ui->actionBold->blockSignals(true);
ui->actionBold->setChecked(font.bold());
ui->actionBold->blockSignals(false);
ui->actionItalic->blockSignals(true);
ui->actionItalic->setChecked(font.italic());
ui->actionItalic->blockSignals(false);
ui->actionUnderline->blockSignals(true);
ui->actionUnderline->setChecked(font.underline());
ui->actionUnderline->blockSignals(false);
Qt::Alignment align = Qt::Alignment(m_model->data(current, Qt::TextAlignmentRole).toInt());
ui->actionLeftAlign->blockSignals(true);
ui->actionLeftAlign->setChecked(align.testFlag(Qt::AlignLeft));
ui->actionLeftAlign->blockSignals(false);
ui->actionRightAlign->blockSignals(true);
ui->actionRightAlign->setChecked(align.testFlag(Qt::AlignRight));
ui->actionRightAlign->blockSignals(false);
ui->actionCenter->blockSignals(true);
ui->actionCenter->setChecked(align.testFlag(Qt::AlignCenter));
ui->actionCenter->blockSignals(false);
ui->actionJustify->blockSignals(true);
ui->actionJustify->setChecked(align.testFlag(Qt::AlignJustify));
ui->actionJustify->blockSignals(false);
});
connect(ui->actionToggleFormatToolbar, &QAction::toggled, ui->formatFrame, &QFrame::setVisible);
ui->actionToggleFormatToolbar->setChecked(false);
ui->formatFrame->setVisible(false);
// Set up find frame
ui->frameFind->hide();
QShortcut* shortcutHideFindFrame = new QShortcut(QKeySequence("ESC"), ui->editFindExpression);
connect(shortcutHideFindFrame, &QShortcut::activated, ui->buttonFindClose, &QToolButton::click);
QShortcut* shortcutActionFind = new QShortcut(QKeySequence("Ctrl+F"), this, nullptr, nullptr, Qt::WidgetWithChildrenShortcut);
connect(shortcutActionFind, &QShortcut::activated, ui->actionFind, &QAction::trigger);
connect(ui->actionFind, &QAction::triggered, this, [this](bool checked) {
if(checked)
{
ui->frameColumnSearch->hide();
ui->actionFindColumn->setChecked(false);
ui->widgetReplace->hide();
ui->frameFind->show();
ui->editFindExpression->setFocus();
ui->actionReplace->setChecked(false);
} else {
ui->buttonFindClose->click();
}
});
QShortcut* shortcutActionReplace = new QShortcut(QKeySequence("Ctrl+H"), this, nullptr, nullptr, Qt::WidgetWithChildrenShortcut);
connect(shortcutActionReplace, &QShortcut::activated, ui->actionReplace, &QAction::trigger);
connect(ui->actionReplace, &QAction::triggered, this, [this](bool checked) {
if(checked)
{
ui->frameColumnSearch->hide();
ui->actionFindColumn->setChecked(false);
ui->widgetReplace->show();
ui->frameFind->show();
ui->editFindExpression->setFocus();
ui->actionFind->setChecked(false);
} else {
ui->buttonFindClose->click();
}
});
connect(ui->editFindExpression, &QLineEdit::returnPressed, ui->buttonFindNext, &QToolButton::click);
connect(ui->editFindExpression, &QLineEdit::textChanged, this, [this]() {
// When the text has changed but neither Return nor F3 or similar nor any buttons were pressed, we want to include the current
// cell in the search as well. This makes sure the selected cell does not jump around every time the text is changed but only
// when the current cell does not match the search expression anymore.
find(ui->editFindExpression->text(), true, true);
});
connect(ui->buttonFindClose, &QToolButton::clicked, this, [this](){
ui->dataTable->setFocus();
ui->frameFind->hide();
ui->actionFind->setChecked(false);
ui->actionReplace->setChecked(false);
});
connect(ui->buttonFindPrevious, &QToolButton::clicked, this, [this](){
find(ui->editFindExpression->text(), false);
});
connect(ui->buttonFindNext, &QToolButton::clicked, this, [this](){
find(ui->editFindExpression->text(), true);
});
connect(ui->buttonReplaceNext, &QToolButton::clicked, this, [this](){
find(ui->editFindExpression->text(), true, true, ReplaceMode::ReplaceNext);
});
connect(ui->buttonReplaceAll, &QToolButton::clicked, this, [this](){
find(ui->editFindExpression->text(), true, true, ReplaceMode::ReplaceAll);
});
QShortcut* shortcutActionFilter = new QShortcut(QKeySequence("Ctrl+Shift+F"), this, nullptr, nullptr, Qt::WidgetWithChildrenShortcut);
connect(shortcutActionFilter, &QShortcut::activated, this, [this](){
// Restore cursor because in the ExtendedTableWidget it is changed to a hand when Ctrl+Shift
// is pressed.
QApplication::restoreOverrideCursor();
FilterTableHeader* header = qobject_cast<FilterTableHeader*>(ui->dataTable->horizontalHeader());
// Set the focus to the current column if valid, otherwise, set focus to the first visible
// column.
if(!header) {
ui->dataTable->horizontalHeader()->setFocus();
} else if(currentIndex().isValid()) {
header->setFocusColumn(static_cast<size_t>(currentIndex().column()));
} else {
for(int col = 0; col < ui->dataTable->model()->columnCount(); col++)
{
if(!ui->dataTable->isColumnHidden(col)) {
header->setFocusColumn(static_cast<size_t>(col));
break;
}
}
}
});
QShortcut* shortcutActionGlobalFilter = new QShortcut(QKeySequence("F3"), this, nullptr, nullptr, Qt::WidgetWithChildrenShortcut);
connect(shortcutActionGlobalFilter, &QShortcut::activated, this, [this](){
ui->editGlobalFilter->setFocus();
});
// Recreate the model
if(m_model)
delete m_model;
m_model = new SqliteTableModel(*db, this, QString(), true);
// Connect slots
connect(m_model, &SqliteTableModel::finishedFetch, this, &TableBrowser::fetchedData);
// Set up column search frame
ui->frameColumnSearch->hide();
connect(ui->actionFindColumn, &QAction::triggered, this, [this](bool checked) {
if(checked) {
ui->frameFind->hide();
ui->actionFind->setChecked(false);
ui->actionReplace->setChecked(false);
ui->frameColumnSearch->show();
ui->editColumnSearchExpression->setFocus();
} else {
ui->frameColumnSearch->hide();
}
});
connect(ui->buttonColumnSearchClose, &QToolButton::clicked, this, [this]() {
ui->frameColumnSearch->hide();
ui->actionFindColumn->setChecked(false);
});
connect(ui->editColumnSearchExpression, &QLineEdit::returnPressed, ui->buttonColumnSearchNext, &QToolButton::click);
connect(ui->editColumnSearchExpression, &QLineEdit::textChanged, this, [this]() {
findNextColumn(true, true);
});
connect(ui->buttonColumnSearchNext, &QToolButton::clicked, this, [this]() {
findNextColumn(true, false);
});
connect(ui->buttonColumnSearchPrevious, &QToolButton::clicked, this, [this]() {
findNextColumn(false, false);
});
// Load initial settings
reloadSettings();
}
TableBrowser::~TableBrowser()
{
delete gotoValidator;
delete ui;
}
void TableBrowser::reset()
{
// Reset the model
m_model->reset();
// Reset the recordset label inside the Browse tab now
updateRecordsetLabel();
// Clear filters
clearFilters();
// Reset the plot dock model and connection
emit updatePlot(nullptr, nullptr, nullptr, true);
}
void TableBrowser::resetSharedSettings()
{
// Remove all stored table information browse data tab
m_settings.clear();
m_defaultEncoding = QString();
}
sqlb::ObjectIdentifier TableBrowser::currentlyBrowsedTableName() const
{
return sqlb::ObjectIdentifier(dbStructureModel->index(ui->comboBrowseTable->currentIndex(),
DbStructureModel::ColumnSchema,
ui->comboBrowseTable->rootModelIndex()).data().toString().toStdString(),
ui->comboBrowseTable->currentData(Qt::EditRole).toString().toStdString()); // Use the edit role here to make sure we actually get the
// table name without the schema bit in front of it.
}
BrowseDataTableSettings& TableBrowser::settings(const sqlb::ObjectIdentifier& object)
{
return m_settings[object];
}
void TableBrowser::setSettings(const sqlb::ObjectIdentifier& table, const BrowseDataTableSettings& table_settings)
{
m_settings[table] = table_settings;
}
void TableBrowser::setStructure(QAbstractItemModel* model, const sqlb::ObjectIdentifier& old_table)
{
dbStructureModel = model;
ui->comboBrowseTable->blockSignals(true);
ui->comboBrowseTable->setModel(model);
ui->comboBrowseTable->setRootModelIndex(dbStructureModel->index(0, 0)); // Show the 'browsable' section of the db structure tree
ui->comboBrowseTable->blockSignals(false);
int old_table_index = ui->comboBrowseTable->findText(QString::fromStdString(old_table.toDisplayString()));
if(old_table_index == -1 && ui->comboBrowseTable->count()) // If the old table couldn't be found anymore but there is another table, select that
ui->comboBrowseTable->setCurrentIndex(0);
else if(old_table_index == -1) // If there aren't any tables to be selected anymore, clear the table view
clear();
else // Under normal circumstances just select the old table again
ui->comboBrowseTable->setCurrentIndex(old_table_index);
emit currentTableChanged(currentlyBrowsedTableName());
}
QModelIndex TableBrowser::currentIndex() const
{
return ui->dataTable->currentIndex();
}
void TableBrowser::setEnabled(bool enable)
{
ui->browseToolbar->setEnabled(enable);
ui->editGlobalFilter->setEnabled(enable);
ui->formatFrame->setEnabled(enable);
ui->frameFind->setEnabled(enable);
ui->buttonNext->setEnabled(enable);
ui->buttonPrevious->setEnabled(enable);
ui->buttonBegin->setEnabled(enable);
ui->buttonEnd->setEnabled(enable);
ui->buttonGoto->setEnabled(enable);
ui->editGoto->setEnabled(enable);
updateInsertDeleteRecordButton();
}
void TableBrowser::refresh()
{
// If the list of table names is empty, i.e. there are no tables to browse, clear the view
// to make sure any left over data is removed and do not add any new information.
if(ui->comboBrowseTable->model()->rowCount(ui->comboBrowseTable->rootModelIndex()) == 0)
{
clear();
return;
}
// Reset the minimum width of the vertical header which could have been modified in updateFilter
// or in headerClicked.
ui->dataTable->verticalHeader()->setMinimumWidth(0);
// Reset the model if it was cleared before
// Because setting a new model creates a new selection mode, reconnect the slots to its signals.
if(ui->dataTable->model() == nullptr)
{
ui->dataTable->setModel(m_model);
connect(ui->dataTable->selectionModel(), &QItemSelectionModel::currentChanged, this, &TableBrowser::selectionChanged);
connect(ui->dataTable->selectionModel(), &QItemSelectionModel::selectionChanged, this, [this](const QItemSelection&, const QItemSelection&) {
updateInsertDeleteRecordButton();
const QModelIndexList& sel = ui->dataTable->selectionModel()->selectedIndexes();
QString statusMessage;
if (sel.count() > 1) {
int rows = static_cast<int>(ui->dataTable->rowsInSelection().size());
statusMessage = tr("%n row(s)", "", rows);
int columns = static_cast<int>(ui->dataTable->colsInSelection().size());
statusMessage += tr(", %n column(s)", "", columns);
if (sel.count() < Settings::getValue("databrowser", "complete_threshold").toInt()) {
double sum = 0;
double first = m_model->data(sel.first(), Qt::EditRole).toDouble();
double min = first;
double max = first;
for (const QModelIndex& index : sel) {
double dblData = m_model->data(index, Qt::EditRole).toDouble();
sum += dblData;
min = std::min(min, dblData);
max = std::max(max, dblData);
}
statusMessage += tr(". Sum: %1; Average: %2; Min: %3; Max: %4").arg(sum).arg(sum/sel.count()).arg(min).arg(max);
}
}
emit statusMessageRequested(statusMessage);
});
}
// Delete settings of no-longer existent tables
for (auto it = m_settings.cbegin(); it != m_settings.cend(); ) {
if (!db->getTableByName(it->first)) {
it = m_settings.erase(it);
} else {
++it;
}
}
// Retrieve the stored data for this table if there is any. If there are no settings for this table,
// this will insert and return a settings object with default values.
const sqlb::ObjectIdentifier tablename = currentlyBrowsedTableName();
const BrowseDataTableSettings& storedData = m_settings[tablename];
// Set column widths to match contents when no column widths were provided in the stored settings.
// This needs to be done before setting the query because the data is returned asynchronously and
// so this information can be needed any time.
if(storedData.columnWidths.empty())
m_columnsResized = false;
// Current table changed
emit currentTableChanged(tablename);
// Build query and apply settings
applyModelSettings(storedData, buildQuery(storedData, tablename));
applyViewportSettings(storedData, tablename);
emit updatePlot(ui->dataTable, m_model, &m_settings[tablename], true);
// Reset the last found index for column search
m_columnSearchLastFoundIndex = -1;
}
void TableBrowser::clearFilters()
{
ui->dataTable->filterHeader()->clearFilters();
ui->editGlobalFilter->clear();
}
void TableBrowser::reloadSettings()
{
ui->dataTable->reloadSettings();
ui->browseToolbar->setToolButtonStyle(static_cast<Qt::ToolButtonStyle>(Settings::getValue("General", "toolbarStyleBrowse").toInt()));
m_model->reloadSettings();
}
void TableBrowser::setCurrentTable(const sqlb::ObjectIdentifier& name)
{
int index = ui->comboBrowseTable->findText(QString::fromStdString(name.toDisplayString()));
if(index != -1)
ui->comboBrowseTable->setCurrentIndex(index);
}
void TableBrowser::clear()
{
// This function unset the model in the data view. So if no model is set at the moment,
// this indicates that this function has already been called and does not need to
// executed another time.
if (!ui->dataTable->model())
return;
// Unset the model
ui->dataTable->setModel(nullptr);
// Remove any filters, not just the values but the fields too
if(qobject_cast<FilterTableHeader*>(ui->dataTable->horizontalHeader()))
qobject_cast<FilterTableHeader*>(ui->dataTable->horizontalHeader())->generateFilters(0);
ui->editGlobalFilter->clear();
}
void TableBrowser::updateFilter(size_t column, const QString& value)
{
// Set minimum width to the vertical header in order to avoid flickering while a filter is being updated.
ui->dataTable->verticalHeader()->setMinimumWidth(ui->dataTable->verticalHeader()->width());
// Update the filter in the model and its query
const std::string column_name = model()->headerData(static_cast<int>(column), Qt::Horizontal, Qt::EditRole).toString().toStdString();
m_model->updateFilter(column_name, value);
ui->actionClearFilters->setEnabled(m_model->filterCount() > 0 || !ui->editGlobalFilter->text().isEmpty());
// Save the new filter settings
BrowseDataTableSettings& settings = m_settings[currentlyBrowsedTableName()];
if(value.isEmpty())
{
if(settings.filterValues.erase(column_name) > 0)
emit projectModified();
} else {
if (settings.filterValues[column_name] != value) {
settings.filterValues[column_name] = value;
emit projectModified();
}
}
}
void TableBrowser::addCondFormatFromFilter(size_t column, const QString& value)
{
QFont font = QFont(Settings::getValue("databrowser", "font").toString());
font.setPointSize(Settings::getValue("databrowser", "fontsize").toInt());
// Create automatically a new conditional format with the next serial background color according to the theme and the regular foreground
// color and font in the settings.
CondFormat newCondFormat(value, QColor(Settings::getValue("databrowser", "reg_fg_colour").toString()),
m_condFormatPalette.nextSerialColor(Palette::appHasDarkTheme()),
font,
CondFormat::AlignLeft,
m_model->encoding());
addCondFormat(false, column, newCondFormat);
}
void TableBrowser::addCondFormat(bool isRowIdFormat, size_t column, const CondFormat& newCondFormat)
{
BrowseDataTableSettings& settings = m_settings[currentlyBrowsedTableName()];
std::vector<CondFormat>& formats = isRowIdFormat ? settings.rowIdFormats[column] : settings.condFormats[column];
m_model->addCondFormat(isRowIdFormat, column, newCondFormat);
// Conditionless formats are pushed back and others inserted at the beginning, so they aren't eclipsed.
if (newCondFormat.filter().isEmpty())
formats.push_back(newCondFormat);
else
formats.insert(formats.begin(), newCondFormat);
emit projectModified();
}
void TableBrowser::clearAllCondFormats(size_t column)
{
m_model->setCondFormats(false, column, {});
m_settings[currentlyBrowsedTableName()].condFormats[column].clear();
emit projectModified();
}
void TableBrowser::clearRowIdFormats(const QModelIndex index)
{
std::vector<CondFormat>& rowIdFormats = m_settings[currentlyBrowsedTableName()].rowIdFormats[static_cast<size_t>(index.column())];
rowIdFormats.erase(std::remove_if(rowIdFormats.begin(), rowIdFormats.end(), [&](const CondFormat& format) {
return format.filter() == QString("=%1").arg(m_model->data(index.sibling(index.row(), 0)).toString());
}), rowIdFormats.end());
m_model->setCondFormats(true, static_cast<size_t>(index.column()), rowIdFormats);
emit projectModified();
}
void TableBrowser::editCondFormats(size_t column)
{
CondFormatManager condFormatDialog(m_settings[currentlyBrowsedTableName()].condFormats[column],
m_model->encoding(), this);
condFormatDialog.setWindowTitle(tr("Conditional formats for \"%1\"").
arg(m_model->headerData(static_cast<int>(column), Qt::Horizontal, Qt::EditRole).toString()));
if (condFormatDialog.exec()) {
std::vector<CondFormat> condFormatVector = condFormatDialog.getCondFormats();
m_model->setCondFormats(false, column, condFormatVector);
m_settings[currentlyBrowsedTableName()].condFormats[column] = condFormatVector;
emit projectModified();
}
}
void TableBrowser::modifySingleFormat(const bool isRowIdFormat, const QString& filter, const QModelIndex refIndex, std::function<void(CondFormat&)> changeFunction)
{
const size_t column = static_cast<size_t>(refIndex.column());
BrowseDataTableSettings& settings = m_settings[currentlyBrowsedTableName()];
std::vector<CondFormat>& formats = isRowIdFormat ? settings.rowIdFormats[column] : settings.condFormats[column];
auto it = std::find_if(formats.begin(), formats.end(), [&filter](const CondFormat& format) {
return format.filter() == filter;
});
if(it != formats.end()) {
changeFunction(*it);
m_model->addCondFormat(isRowIdFormat, column, *it);
} else {
// Create a new conditional format based on the current reference index and then modify it as requested using the passed function.
CondFormat newCondFormat(filter, m_model, refIndex, m_model->encoding());
changeFunction(newCondFormat);
addCondFormat(isRowIdFormat, column, newCondFormat);
}
}
void TableBrowser::modifyFormat(std::function<void(CondFormat&)> changeFunction)
{
// Modify the conditional formats from entirely selected columns having the current filter value,
// or modify the row-id formats of selected cells, when the selection does not cover entire columns.
const std::unordered_set<size_t>& columns = ui->dataTable->selectedCols();
if (columns.size() > 0) {
for (size_t column : columns) {
QString filter;
const std::string column_name = model()->headerData(static_cast<int>(column), Qt::Horizontal, Qt::EditRole).toString().toStdString();
if (m_settings[currentlyBrowsedTableName()].filterValues.count(column_name) > 0)
filter = m_settings[currentlyBrowsedTableName()].filterValues.at(column_name);
modifySingleFormat(false, filter, currentIndex().sibling(currentIndex().row(), static_cast<int>(column)), changeFunction);
}
} else {
for(const QModelIndex& index : ui->dataTable->selectionModel()->selectedIndexes()) {
const QString filter = QString("=%1").arg(m_model->data(index.sibling(index.row(), 0)).toString());
modifySingleFormat(true, filter, index, changeFunction);
}
}
emit projectModified();
}
void TableBrowser::updateRecordsetLabel()
{
// Get all the numbers, i.e. the number of the first row and the last row as well as the total number of rows
// Internal row numbers start at 0, but we want to show them starting at 1.
int from = ui->dataTable->verticalHeader()->visualIndexAt(0) + 1;
int total = m_model->rowCount();
int real_total = m_model->realRowCount();
int to = from + ui->dataTable->numVisibleRows() - 1;
if(to < 0)
to = 0;
// Adjust visible rows to contents if necessary, and then take the new visible rows, which might have changed.
if(m_adjustRows) {
for(int i=from-1; i<=to-1; i++)
ui->dataTable->resizeRowToContents(i);
from = ui->dataTable->verticalHeader()->visualIndexAt(0) + 1;
to = from + ui->dataTable->numVisibleRows() - 1;
}
// Update the validator of the goto row field
gotoValidator->setRange(0, total);
// When there is no query for this table (i.e. no table is selected), there is no row count query either which in turn means
// that the row count query will never finish. And because of this the row count will be forever unknown. To avoid always showing
// a misleading "determining row count" text in the UI we set the row count status to complete here for empty queries.
auto row_count_available = m_model->rowCountAvailable();
if(m_model->query().empty())
row_count_available = SqliteTableModel::RowCount::Complete;
// Update the label showing the current position
QString txt;
switch(row_count_available)
{
case SqliteTableModel::RowCount::Unknown:
txt = tr("determining row count...");
break;
case SqliteTableModel::RowCount::Partial:
txt = tr("%L1 - %L2 of >= %L3").arg(from).arg(to).arg(total);
break;
case SqliteTableModel::RowCount::Complete:
txt = tr("%L1 - %L2 of %L3").arg(from).arg(to).arg(real_total);
if (real_total != total) {
txt.append(tr(" (clipped at %L1 rows)").arg(total));
}
break;
}
ui->labelRecordset->setText(txt);
// Enable editing only for tables or views with editing unlocked for which the row count is already available
bool is_table_or_unlocked_view = false;
sqlb::ObjectIdentifier current_table = currentlyBrowsedTableName();
if(!current_table.isEmpty() && !m_model->query().empty())
{
auto obj = db->getTableByName(current_table);
is_table_or_unlocked_view = obj && (
(obj->isView() && m_model->hasPseudoPk()) ||
(!obj->isView()));
}
enableEditing(m_model->rowCountAvailable() != SqliteTableModel::RowCount::Unknown && is_table_or_unlocked_view);
// Show filters unless the table is empty
const bool needs_filters = total > 0 || m_model->filterCount() > 0;
FilterTableHeader* header = qobject_cast<FilterTableHeader*>(ui->dataTable->horizontalHeader());
if(header) {
if(needs_filters && !header->hasFilters()) {
generateFilters();
ui->dataTable->adjustSize();
} else if(!needs_filters && header->hasFilters()) {
ui->dataTable->generateFilters(0, false);
}
}
}
sqlb::Query TableBrowser::buildQuery(const BrowseDataTableSettings& storedData, const sqlb::ObjectIdentifier& tablename) const
{
const auto table = db->getTableByName(tablename);
sqlb::Query query(tablename, table && table->isView());
// Construct a query from the retrieved settings
// Sorting
query.setOrderBy(storedData.sortColumns);
ui->actionClearSorting->setEnabled(storedData.sortColumns.size() > 0);
// Filters
for(auto it=storedData.filterValues.cbegin();it!=storedData.filterValues.cend();++it)
query.where().insert({it->first, CondFormat::filterToSqlCondition(it->second, m_model->encoding())});
// Global filter
for(const auto& f : storedData.globalFilters)
query.globalWhere().push_back(CondFormat::filterToSqlCondition(f, m_model->encoding()));
// Display formats
bool only_defaults = true;
if(table)
{
// When there is at least one custom display format, we have to set all columns for the query explicitly here
for(size_t i=0; i<table->fields.size(); ++i)
{
QString format = contains(storedData.displayFormats, i+1) ? storedData.displayFormats.at(i+1) : QString();
if(format.size())
{
query.selectedColumns().emplace_back(table->fields.at(i).name(), format.toStdString());
only_defaults = false;
} else {
query.selectedColumns().emplace_back(table->fields.at(i).name(), table->fields.at(i).name());
}
}
}
if(only_defaults)
query.selectedColumns().clear();
// Unlock view editing
query.setRowIdColumn(storedData.unlockViewPk.toStdString());
return query;
}
void TableBrowser::applyModelSettings(const BrowseDataTableSettings& storedData, const sqlb::Query& query)
{
// Set query which also resets the model
m_model->setQuery(query);
// Regular conditional formats
for(auto formatIt=storedData.condFormats.cbegin(); formatIt!=storedData.condFormats.cend(); ++formatIt)
m_model->setCondFormats(false, formatIt->first, formatIt->second);
// Row Id formats
for(auto formatIt=storedData.rowIdFormats.cbegin(); formatIt!=storedData.rowIdFormats.cend(); ++formatIt)
m_model->setCondFormats(true, formatIt->first, formatIt->second);
// Encoding
m_model->setEncoding(storedData.encoding);
}
void TableBrowser::applyViewportSettings(const BrowseDataTableSettings& storedData, const sqlb::ObjectIdentifier& tablename)
{
// Show rowid column. This also takes care of the filters.
showRowidColumn(storedData.showRowid);
// Enable editing in general and (un)lock view editing depending on the settings
unlockViewEditing(!storedData.unlockViewPk.isEmpty() && storedData.unlockViewPk != "_rowid_", storedData.unlockViewPk);
// Column hidden status
showAllColumns();
for(auto hiddenIt=storedData.hiddenColumns.cbegin();hiddenIt!=storedData.hiddenColumns.cend();++hiddenIt)
hideColumns(hiddenIt->first, hiddenIt->second);
// Column widths
std::map<int, int> w = storedData.columnWidths; // We're working with a copy here because the map can get modified in the process
for(auto widthIt=w.cbegin();widthIt!=w.cend();++widthIt)
{
if(widthIt->first < ui->dataTable->model()->columnCount())
ui->dataTable->setColumnWidth(widthIt->first, widthIt->second);
}
m_columnsResized = !w.empty();
// Global filters
QString text;
for(const auto& f : storedData.globalFilters)
text += f + " ";
text.chop(1);
ui->editGlobalFilter->setText(text);
// Show/hide some menu options depending on whether this is a table or a view
const auto table = db->getTableByName(tablename);
if(!table->isView())
{
// Table
ui->actionUnlockViewEditing->setVisible(false);
ui->actionShowRowidColumn->setVisible(!table->withoutRowidTable());
} else {
// View
ui->actionUnlockViewEditing->setVisible(true);
ui->actionShowRowidColumn->setVisible(false);
}
// Frozen columns
freezeColumns(storedData.frozenColumns);
}
void TableBrowser::enableEditing(bool enable_edit)
{
// Don't enable anything if this is a read only database
bool edit = enable_edit && !db->readOnly();
// Apply settings
ui->dataTable->setEditTriggers(edit ? QAbstractItemView::SelectedClicked | QAbstractItemView::AnyKeyPressed | QAbstractItemView::EditKeyPressed : QAbstractItemView::NoEditTriggers);
updateInsertDeleteRecordButton();
}
void TableBrowser::showRowidColumn(bool show)
{
// Disconnect the resized signal from the horizontal header. Otherwise it's resetting the automatic column widths
disconnect(ui->dataTable->horizontalHeader(), &QHeaderView::sectionResized, this, &TableBrowser::updateColumnWidth);
// WORKAROUND
// Set the opposite hidden/visible status of what we actually want for the rowid column. This is to work around a Qt bug which
// is present in at least version 5.7.1. The problem is this: when you browse a table/view with n columns, then switch to a table/view
// with less than n columns, you'll be able to resize the first (hidden!) column by resizing the section to the left of the first visible
// column. By doing so the table view gets messed up. But even when not resizing the first hidden column, tab-ing through the fields
// will stop at the not-so-much-hidden rowid column, too. All this can be fixed by this line. I haven't managed to find another workaround
// or way to fix this yet.
ui->dataTable->setColumnHidden(0, show);
// Show/hide rowid column
ui->dataTable->setColumnHidden(0, !show);
if(show)
ui->dataTable->setColumnWidth(0, ui->dataTable->horizontalHeader()->defaultSectionSize());
// Update checked status of the popup menu action
ui->actionShowRowidColumn->setChecked(show);
// Save settings for this table
sqlb::ObjectIdentifier current_table = currentlyBrowsedTableName();
if (m_settings[current_table].showRowid != show) {
emit projectModified();
m_settings[current_table].showRowid = show;
}
// Update the filter row
generateFilters();
// Re-enable signal
connect(ui->dataTable->horizontalHeader(), &QHeaderView::sectionResized, this, &TableBrowser::updateColumnWidth);