-
-
Notifications
You must be signed in to change notification settings - Fork 1.3k
/
Copy pathbasetracktablemodel.cpp
1286 lines (1224 loc) · 47 KB
/
basetracktablemodel.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 "library/basetracktablemodel.h"
#include <QBuffer>
#include <QGuiApplication>
#include <QMimeData>
#include <QScreen>
#include <QtGlobal>
#include "library/coverartcache.h"
#include "library/dao/trackschema.h"
#include "library/starrating.h"
#include "library/tabledelegates/bpmdelegate.h"
#include "library/tabledelegates/checkboxdelegate.h"
#include "library/tabledelegates/colordelegate.h"
#include "library/tabledelegates/coverartdelegate.h"
#include "library/tabledelegates/keydelegate.h"
#include "library/tabledelegates/locationdelegate.h"
#include "library/tabledelegates/multilineeditdelegate.h"
#include "library/tabledelegates/previewbuttondelegate.h"
#include "library/tabledelegates/stardelegate.h"
#include "library/trackcollection.h"
#include "library/trackcollectionmanager.h"
#include "mixer/playerinfo.h"
#include "mixer/playermanager.h"
#include "moc_basetracktablemodel.cpp"
#include "track/keyutils.h"
#include "track/track.h"
#include "util/assert.h"
#include "util/clipboard.h"
#include "util/color/colorpalette.h"
#include "util/color/predefinedcolorpalettes.h"
#include "util/datetime.h"
#include "util/db/sqlite.h"
#include "util/logger.h"
#include "widget/wlibrary.h"
#include "widget/wtracktableview.h"
namespace {
const mixxx::Logger kLogger("BaseTrackTableModel");
constexpr double kRelativeHeightOfCoverartToolTip =
0.165; // Height of the image for the cover art tooltip (Relative to the available screen size)
const QStringList kDefaultTableColumns = {
LIBRARYTABLE_ALBUM,
LIBRARYTABLE_ALBUMARTIST,
LIBRARYTABLE_ARTIST,
LIBRARYTABLE_BPM,
LIBRARYTABLE_BPM_LOCK,
LIBRARYTABLE_BITRATE,
LIBRARYTABLE_CHANNELS,
LIBRARYTABLE_COLOR,
LIBRARYTABLE_COMMENT,
LIBRARYTABLE_COMPOSER,
LIBRARYTABLE_COVERART,
LIBRARYTABLE_DATETIMEADDED,
LIBRARYTABLE_DURATION,
LIBRARYTABLE_FILETYPE,
LIBRARYTABLE_GENRE,
LIBRARYTABLE_GROUPING,
LIBRARYTABLE_KEY,
TRACKLOCATIONSTABLE_LOCATION,
LIBRARYTABLE_PLAYED,
LIBRARYTABLE_PREVIEW,
LIBRARYTABLE_RATING,
LIBRARYTABLE_REPLAYGAIN,
LIBRARYTABLE_SAMPLERATE,
LIBRARYTABLE_TIMESPLAYED,
LIBRARYTABLE_LAST_PLAYED_AT,
LIBRARYTABLE_TITLE,
LIBRARYTABLE_TRACKNUMBER,
LIBRARYTABLE_YEAR,
};
inline QSqlDatabase cloneDatabase(
const QSqlDatabase& prototype) {
const auto connectionName =
QUuid::createUuid().toString(QUuid::WithoutBraces);
auto cloned = QSqlDatabase::cloneDatabase(
prototype,
connectionName);
DEBUG_ASSERT(cloned.isValid());
if (prototype.isOpen() && !cloned.open()) {
kLogger.warning()
<< "Failed to open cloned database connection"
<< cloned
<< cloned.lastError();
}
return cloned;
}
QSqlDatabase cloneDatabase(
TrackCollectionManager* pTrackCollectionManager) {
VERIFY_OR_DEBUG_ASSERT(pTrackCollectionManager &&
pTrackCollectionManager->internalCollection()) {
return QSqlDatabase();
}
return cloneDatabase(
pTrackCollectionManager->internalCollection()->database());
}
} // anonymous namespace
// static
constexpr int BaseTrackTableModel::kBpmColumnPrecisionDefault;
constexpr int BaseTrackTableModel::kBpmColumnPrecisionMinimum;
constexpr int BaseTrackTableModel::kBpmColumnPrecisionMaximum;
constexpr bool BaseTrackTableModel::kKeyColorsEnabledDefault;
int BaseTrackTableModel::s_bpmColumnPrecision =
kBpmColumnPrecisionDefault;
bool BaseTrackTableModel::s_keyColorsEnabled = kKeyColorsEnabledDefault;
std::optional<ColorPalette> BaseTrackTableModel::s_keyColorPalette;
// static
void BaseTrackTableModel::setBpmColumnPrecision(int precision) {
VERIFY_OR_DEBUG_ASSERT(precision >= BaseTrackTableModel::kBpmColumnPrecisionMinimum) {
precision = BaseTrackTableModel::kBpmColumnPrecisionMinimum;
}
VERIFY_OR_DEBUG_ASSERT(precision <= BaseTrackTableModel::kBpmColumnPrecisionMaximum) {
precision = BaseTrackTableModel::kBpmColumnPrecisionMaximum;
}
s_bpmColumnPrecision = precision;
}
// static
void BaseTrackTableModel::setKeyColorsEnabled(bool keyColorsEnabled) {
s_keyColorsEnabled = keyColorsEnabled;
}
// static
void BaseTrackTableModel::setKeyColorPalette(const ColorPalette& palette) {
s_keyColorPalette = palette;
}
bool BaseTrackTableModel::s_bApplyPlayedTrackColor =
kApplyPlayedTrackColorDefault;
void BaseTrackTableModel::setApplyPlayedTrackColor(bool apply) {
s_bApplyPlayedTrackColor = apply;
}
// static
QStringList BaseTrackTableModel::defaultTableColumns() {
return kDefaultTableColumns;
}
BaseTrackTableModel::BaseTrackTableModel(
QObject* parent,
TrackCollectionManager* pTrackCollectionManager,
const char* settingsNamespace)
: QAbstractTableModel(parent),
TrackModel(cloneDatabase(pTrackCollectionManager), settingsNamespace),
m_pTrackCollectionManager(pTrackCollectionManager),
m_previewDeckGroup(PlayerManager::groupForPreviewDeck(0)),
m_backgroundColorOpacity(WLibrary::kDefaultTrackTableBackgroundColorOpacity),
m_trackPlayedColor(QColor(WTrackTableView::kDefaultTrackPlayedColor)),
m_trackMissingColor(QColor(WTrackTableView::kDefaultTrackMissingColor)) {
connect(&pTrackCollectionManager->internalCollection()->getTrackDAO(),
&TrackDAO::forceModelUpdate,
this,
&BaseTrackTableModel::slotRefreshAllRows);
connect(&PlayerInfo::instance(),
&PlayerInfo::trackChanged,
this,
&BaseTrackTableModel::slotTrackChanged);
CoverArtCache* pCache = CoverArtCache::instance();
if (pCache) {
connect(pCache,
&CoverArtCache::coverFound,
this,
&BaseTrackTableModel::slotCoverFound);
}
}
void BaseTrackTableModel::initTableColumnsAndHeaderProperties(
const QStringList& tableColumns) {
m_columnCache.setColumns(tableColumns);
if (m_columnHeaders.size() < tableColumns.size()) {
m_columnHeaders.resize(tableColumns.size());
}
initHeaderProperties();
}
void BaseTrackTableModel::initHeaderProperties() {
setHeaderProperties(
ColumnCache::COLUMN_LIBRARYTABLE_ALBUM,
tr("Album"),
defaultColumnWidth() * 4);
setHeaderProperties(
ColumnCache::COLUMN_LIBRARYTABLE_ALBUMARTIST,
tr("Album Artist"),
defaultColumnWidth() * 4);
setHeaderProperties(
ColumnCache::COLUMN_LIBRARYTABLE_ARTIST,
tr("Artist"),
defaultColumnWidth() * 4);
setHeaderProperties(
ColumnCache::COLUMN_LIBRARYTABLE_BITRATE,
tr("Bitrate"),
defaultColumnWidth());
setHeaderProperties(
ColumnCache::COLUMN_LIBRARYTABLE_BPM,
tr("BPM"),
defaultColumnWidth() * 2);
setHeaderProperties(
ColumnCache::COLUMN_LIBRARYTABLE_CHANNELS,
tr("Channels"),
defaultColumnWidth() / 2);
setHeaderProperties(
ColumnCache::COLUMN_LIBRARYTABLE_COLOR,
tr("Color"),
defaultColumnWidth() / 2);
setHeaderProperties(
ColumnCache::COLUMN_LIBRARYTABLE_COMMENT,
tr("Comment"),
defaultColumnWidth() * 6);
setHeaderProperties(
ColumnCache::COLUMN_LIBRARYTABLE_COMPOSER,
tr("Composer"),
defaultColumnWidth() * 4);
setHeaderProperties(
ColumnCache::COLUMN_LIBRARYTABLE_COVERART,
tr("Cover Art"),
defaultColumnWidth() / 2);
setHeaderProperties(
ColumnCache::COLUMN_LIBRARYTABLE_DATETIMEADDED,
tr("Date Added"),
defaultColumnWidth() * 3);
setHeaderProperties(
ColumnCache::COLUMN_LIBRARYTABLE_LAST_PLAYED_AT,
tr("Last Played"),
defaultColumnWidth() * 3);
setHeaderProperties(
ColumnCache::COLUMN_LIBRARYTABLE_DURATION,
tr("Duration"),
defaultColumnWidth());
setHeaderProperties(
ColumnCache::COLUMN_LIBRARYTABLE_FILETYPE,
tr("Type"),
defaultColumnWidth());
setHeaderProperties(
ColumnCache::COLUMN_LIBRARYTABLE_GENRE,
tr("Genre"),
defaultColumnWidth() * 4);
setHeaderProperties(
ColumnCache::COLUMN_LIBRARYTABLE_GROUPING,
tr("Grouping"),
defaultColumnWidth() * 4);
setHeaderProperties(
ColumnCache::COLUMN_LIBRARYTABLE_KEY,
tr("Key"),
defaultColumnWidth());
setHeaderProperties(
ColumnCache::COLUMN_TRACKLOCATIONSTABLE_LOCATION,
tr("Location"),
defaultColumnWidth() * 6);
setHeaderProperties(
ColumnCache::COLUMN_LIBRARYTABLE_PREVIEW,
tr("Preview"),
defaultColumnWidth() / 2);
setHeaderProperties(
ColumnCache::COLUMN_LIBRARYTABLE_RATING,
tr("Rating"),
defaultColumnWidth() * 2);
setHeaderProperties(
ColumnCache::COLUMN_LIBRARYTABLE_REPLAYGAIN,
tr("ReplayGain"),
defaultColumnWidth() * 2);
setHeaderProperties(
ColumnCache::COLUMN_LIBRARYTABLE_SAMPLERATE,
tr("Samplerate"),
defaultColumnWidth());
setHeaderProperties(
ColumnCache::COLUMN_LIBRARYTABLE_TIMESPLAYED,
tr("Played"),
defaultColumnWidth() * 2);
setHeaderProperties(
ColumnCache::COLUMN_LIBRARYTABLE_TITLE,
tr("Title"),
defaultColumnWidth() * 4);
setHeaderProperties(
ColumnCache::COLUMN_LIBRARYTABLE_TRACKNUMBER,
tr("Track #"),
defaultColumnWidth());
setHeaderProperties(
ColumnCache::COLUMN_LIBRARYTABLE_YEAR,
tr("Year"),
defaultColumnWidth());
}
void BaseTrackTableModel::setHeaderProperties(
ColumnCache::Column column,
const QString& title,
int defaultWidth) {
int section = fieldIndex(column);
if (section < 0) {
// Skipping header properties for unsupported column
return;
}
if (section >= m_columnHeaders.size()) {
m_columnHeaders.resize(section + 1);
}
m_columnHeaders[section].column = column;
setHeaderData(
section,
Qt::Horizontal,
m_columnCache.columnName(column),
TrackModel::kHeaderNameRole);
setHeaderData(
section,
Qt::Horizontal,
title,
Qt::DisplayRole);
setHeaderData(
section,
Qt::Horizontal,
defaultWidth,
TrackModel::kHeaderWidthRole);
}
bool BaseTrackTableModel::setHeaderData(
int section,
Qt::Orientation orientation,
const QVariant& value,
int role) {
VERIFY_OR_DEBUG_ASSERT(section >= 0) {
return false;
}
VERIFY_OR_DEBUG_ASSERT(section < m_columnHeaders.size()) {
return false;
}
if (orientation != Qt::Horizontal) {
// We only care about horizontal headers.
return false;
}
m_columnHeaders[section].header[role] = value;
emit headerDataChanged(orientation, section, section);
return true;
}
QVariant BaseTrackTableModel::headerData(
int section,
Qt::Orientation orientation,
int role) const {
if (orientation == Qt::Horizontal) {
switch (role) {
case Qt::DisplayRole: {
QVariant headerValue =
m_columnHeaders.value(section).header.value(role);
if (!headerValue.isValid()) {
// Try EditRole if DisplayRole wasn't present
headerValue = m_columnHeaders.value(section).header.value(Qt::EditRole);
}
if (headerValue.isValid()) {
return headerValue;
} else {
return QVariant(section).toString();
}
}
case TrackModel::kHeaderWidthRole: {
QVariant widthValue = m_columnHeaders.value(section).header.value(role);
if (widthValue.isValid()) {
return widthValue;
} else {
return defaultColumnWidth();
}
}
case TrackModel::kHeaderNameRole: {
return m_columnHeaders.value(section).header.value(role);
}
case Qt::ToolTipRole: {
QVariant tooltip = m_columnHeaders.value(section).header.value(role);
if (tooltip.isValid()) {
return tooltip;
}
break;
}
default:
break;
}
}
return QAbstractTableModel::headerData(section, orientation, role);
}
int BaseTrackTableModel::countValidColumnHeaders() const {
int count = 0;
for (const auto& columnHeader : m_columnHeaders) {
if (columnHeader.column !=
ColumnCache::COLUMN_LIBRARYTABLE_INVALID) {
++count;
}
}
return count;
}
int BaseTrackTableModel::columnCount(const QModelIndex& parent) const {
VERIFY_OR_DEBUG_ASSERT(!parent.isValid()) {
return 0;
}
return countValidColumnHeaders();
}
void BaseTrackTableModel::cutTracks(const QModelIndexList& indices) {
copyTracks(indices);
removeTracks(indices);
}
void BaseTrackTableModel::copyTracks(const QModelIndexList& indices) const {
Clipboard::start();
for (const QModelIndex& index : indices) {
if (index.isValid()) {
Clipboard::add(QUrl::fromLocalFile(getTrackLocation(index)));
}
}
Clipboard::finish();
}
QList<int> BaseTrackTableModel::pasteTracks(const QModelIndex& insertionIndex) {
// Don't paste into locked playlists and crates or into into History
if (isLocked() || !hasCapabilities(TrackModel::Capability::ReceiveDrops)) {
return QList<int>{};
}
int insertionPos = 0;
const QList<QUrl> urls = Clipboard::urls();
const QList<TrackId> trackIds = m_pTrackCollectionManager->resolveTrackIdsFromUrls(urls, true);
if (!trackIds.isEmpty()) {
addTracksWithTrackIds(insertionIndex, trackIds, &insertionPos);
}
QList<int> rows;
for (const auto& trackId : trackIds) {
const auto trackRows = getTrackRows(trackId);
for (int trackRow : trackRows) {
if (insertionPos == 0) {
rows.append(trackRow);
} else {
int pos =
index(
trackRow,
fieldIndex(ColumnCache::
COLUMN_PLAYLISTTRACKSTABLE_POSITION))
.data()
.toInt();
// trackRows includes all instances in the table of the pasted
// tracks. We only want to select the ones we just inserted
if (pos >= insertionPos && pos < insertionPos + trackIds.size()) {
rows.append(trackRow);
}
}
}
}
return rows;
}
bool BaseTrackTableModel::isColumnHiddenByDefault(
int column) {
return column == fieldIndex(ColumnCache::COLUMN_LIBRARYTABLE_ALBUMARTIST) ||
column == fieldIndex(ColumnCache::COLUMN_LIBRARYTABLE_BPM_LOCK) ||
column == fieldIndex(ColumnCache::COLUMN_LIBRARYTABLE_BITRATE) ||
column == fieldIndex(ColumnCache::COLUMN_LIBRARYTABLE_CHANNELS) ||
column == fieldIndex(ColumnCache::COLUMN_LIBRARYTABLE_COMPOSER) ||
column == fieldIndex(ColumnCache::COLUMN_LIBRARYTABLE_FILETYPE) ||
column == fieldIndex(ColumnCache::COLUMN_LIBRARYTABLE_GROUPING) ||
column == fieldIndex(ColumnCache::COLUMN_TRACKLOCATIONSTABLE_LOCATION) ||
column == fieldIndex(ColumnCache::COLUMN_LIBRARYTABLE_PLAYED) ||
column == fieldIndex(ColumnCache::COLUMN_LIBRARYTABLE_REPLAYGAIN) ||
column == fieldIndex(ColumnCache::COLUMN_LIBRARYTABLE_SAMPLERATE) ||
column == fieldIndex(ColumnCache::COLUMN_LIBRARYTABLE_TIMESPLAYED) ||
column == fieldIndex(ColumnCache::COLUMN_LIBRARYTABLE_TRACKNUMBER) ||
column == fieldIndex(ColumnCache::COLUMN_LIBRARYTABLE_YEAR);
}
QAbstractItemDelegate* BaseTrackTableModel::delegateForColumn(
const int index, QObject* pParent) {
auto* pTableView = qobject_cast<WTrackTableView*>(pParent);
VERIFY_OR_DEBUG_ASSERT(pTableView) {
return nullptr;
}
m_backgroundColorOpacity = pTableView->getBackgroundColorOpacity();
// This is the color used for the text of played tracks.
// data() uses this to compose the ForegroundRole QBrush if 'played' is checked.
m_trackPlayedColor = pTableView->getTrackPlayedColor();
connect(pTableView,
&WTrackTableView::trackPlayedColorChanged,
this,
[this](QColor col) {
m_trackPlayedColor = col;
});
// Same for the 'missing' color
m_trackMissingColor = pTableView->getTrackMissingColor();
connect(pTableView,
&WTrackTableView::trackMissingColorChanged,
this,
[this](QColor col) {
m_trackMissingColor = col;
});
if (index == fieldIndex(ColumnCache::COLUMN_LIBRARYTABLE_RATING)) {
return new StarDelegate(pTableView);
} else if (index == fieldIndex(ColumnCache::COLUMN_LIBRARYTABLE_BPM)) {
return new BPMDelegate(pTableView);
} else if (index == fieldIndex(ColumnCache::COLUMN_LIBRARYTABLE_TIMESPLAYED)) {
return new CheckboxDelegate(pTableView, QStringLiteral("LibraryPlayedCheckbox"));
} else if (PlayerManager::numPreviewDecks() > 0 &&
index == fieldIndex(ColumnCache::COLUMN_LIBRARYTABLE_PREVIEW)) {
return new PreviewButtonDelegate(pTableView, index);
} else if (index == fieldIndex(ColumnCache::COLUMN_LIBRARYTABLE_COMMENT)) {
return new MultiLineEditDelegate(pTableView);
} else if (index == fieldIndex(ColumnCache::COLUMN_TRACKLOCATIONSTABLE_LOCATION)) {
return new LocationDelegate(pTableView);
} else if (index == fieldIndex(ColumnCache::COLUMN_LIBRARYTABLE_COLOR)) {
return new ColorDelegate(pTableView);
} else if (index == fieldIndex(ColumnCache::COLUMN_LIBRARYTABLE_COVERART)) {
auto* pCoverArtDelegate =
new CoverArtDelegate(pTableView);
// WLibraryTableView -> CoverArtDelegate
connect(pTableView,
&WLibraryTableView::onlyCachedCoverArt,
pCoverArtDelegate,
&CoverArtDelegate::slotInhibitLazyLoading);
// CoverArtDelegate -> BaseTrackTableModel
connect(pCoverArtDelegate,
&CoverArtDelegate::rowsChanged,
this,
&BaseTrackTableModel::slotRefreshCoverRows);
return pCoverArtDelegate;
} else if (index == fieldIndex(ColumnCache::COLUMN_LIBRARYTABLE_KEY)) {
return new KeyDelegate(pTableView);
}
return nullptr;
}
QVariant BaseTrackTableModel::data(
const QModelIndex& index,
int role) const {
if (!index.isValid()) {
return QVariant();
}
if (role == Qt::BackgroundRole) {
const auto rgbColorValue = rawSiblingValue(
index,
ColumnCache::COLUMN_LIBRARYTABLE_COLOR);
const auto rgbColor = mixxx::RgbColor::fromQVariant(rgbColorValue);
if (!rgbColor) {
return QVariant();
}
auto bgColor = mixxx::RgbColor::toQColor(rgbColor);
DEBUG_ASSERT(bgColor.isValid());
DEBUG_ASSERT(m_backgroundColorOpacity >= 0.0);
DEBUG_ASSERT(m_backgroundColorOpacity <= 1.0);
bgColor.setAlphaF(static_cast<float>(m_backgroundColorOpacity));
return QBrush(bgColor);
} else if (role == Qt::ForegroundRole) {
// Custom text color for missing tracks
// Visible in playlists, crates and Missing feature.
// Check this first so played, missing tracks (unlikely case, but possible)
// get the 'missing' color.
// Note: this is not helpful in Tracks -> Missing, so override it with
// the regular track color (WTrackTableView { color: #xxx; }) like this:
// #DlgMissing WTrackTableView { qproperty-trackMissingColor: #xxx; }
auto missingRaw = rawSiblingValue(
index,
ColumnCache::COLUMN_TRACKLOCATIONSTABLE_FSDELETED);
if (!missingRaw.isNull() &&
missingRaw.canConvert<bool>() &&
missingRaw.toBool()) {
return QVariant::fromValue(m_trackMissingColor);
}
if (s_bApplyPlayedTrackColor) {
// Custom text color for played tracks
auto playedRaw = rawSiblingValue(
index,
ColumnCache::COLUMN_LIBRARYTABLE_PLAYED);
if (!playedRaw.isNull() &&
playedRaw.canConvert<bool>() &&
playedRaw.toBool()) {
return QVariant::fromValue(m_trackPlayedColor);
}
}
}
// Return the preferred (default) width of the Color column.
// This works around inconsistencies when the width is determined by
// color values. See /~https://github.com/mixxxdj/mixxx/issues/12850
if (role == Qt::SizeHintRole) {
const auto field = mapColumn(index.column());
if (field == ColumnCache::COLUMN_LIBRARYTABLE_COLOR) {
return QSize(defaultColumnWidth() / 2, 0);
}
}
// Only retrieve a value for supported roles
if (role != Qt::DisplayRole &&
role != Qt::EditRole &&
role != Qt::CheckStateRole &&
role != Qt::ToolTipRole &&
role != kDataExportRole &&
role != Qt::TextAlignmentRole &&
role != Qt::DecorationRole) {
return QVariant();
}
return roleValue(index, rawValue(index), role);
}
QVariant BaseTrackTableModel::rawSiblingValue(
const QModelIndex& index,
ColumnCache::Column siblingField) const {
VERIFY_OR_DEBUG_ASSERT(index.isValid()) {
return QVariant();
}
VERIFY_OR_DEBUG_ASSERT(siblingField != ColumnCache::COLUMN_LIBRARYTABLE_INVALID) {
return QVariant();
}
const int siblingColumn = fieldIndex(siblingField);
if (siblingColumn < 0) {
// Unsupported or unknown column/field
// FIXME: This should never happen but it does. But why??
return QVariant();
}
const QModelIndex siblingIndex = index.sibling(index.row(), siblingColumn);
return rawValue(siblingIndex);
}
bool BaseTrackTableModel::setData(
const QModelIndex& index,
const QVariant& value,
int role) {
const int column = index.column();
if (role == Qt::CheckStateRole) {
const auto field = mapColumn(index.column());
if (field == ColumnCache::COLUMN_LIBRARYTABLE_INVALID) {
return false;
}
const auto checked = value.toInt() > 0;
switch (field) {
case ColumnCache::COLUMN_LIBRARYTABLE_TIMESPLAYED: {
// Override sets to TIMESPLAYED and redirect them to PLAYED
QModelIndex playedIndex = index.sibling(
index.row(),
fieldIndex(ColumnCache::COLUMN_LIBRARYTABLE_PLAYED));
return setData(playedIndex, checked, Qt::EditRole);
}
case ColumnCache::COLUMN_LIBRARYTABLE_BPM: {
QModelIndex bpmLockedIndex = index.sibling(
index.row(),
fieldIndex(ColumnCache::COLUMN_LIBRARYTABLE_BPM_LOCK));
return setData(bpmLockedIndex, checked, Qt::EditRole);
}
default:
return false;
}
}
TrackPointer pTrack = getTrack(index);
if (!pTrack) {
return false;
}
// Do not save the track here. Changing the track dirties it and the caching
// system will automatically save the track once it is unloaded from
// memory. rryan 10/2010
return setTrackValueForColumn(pTrack, column, value, role);
}
QVariant BaseTrackTableModel::composeCoverArtToolTipHtml(
const QModelIndex& index) const {
// Determine height of the cover art image depending on the screen size
// Assuming that the view is on whatever Qt considers the primary screen.
QGuiApplication* app = static_cast<QGuiApplication*>(QCoreApplication::instance());
VERIFY_OR_DEBUG_ASSERT(app) {
qWarning() << "Unable to get application's QGuiApplication instance, "
"cannot determine primary screen";
return QVariant();
}
QScreen* pViewScreen = app->primaryScreen();
unsigned int absoluteHeightOfCoverartToolTip = static_cast<int>(
pViewScreen->availableGeometry().height() *
kRelativeHeightOfCoverartToolTip);
const auto coverInfo = getCoverInfo(index);
if (!coverInfo.hasImage()) {
return QPixmap();
}
m_toolTipIndex = index;
QPixmap pixmap = CoverArtCache::getCachedCover(
coverInfo,
absoluteHeightOfCoverartToolTip);
if (pixmap.isNull()) {
// Cache miss -> Don't show a tooltip, refresh cache
// Height used for the width, in assumption that covers are squares
CoverArtCache::requestUncachedCover(
this,
coverInfo,
absoluteHeightOfCoverartToolTip);
//: Tooltip text on the cover art column shown when the cover is read from disk
return tr("Fetching image ...");
}
QByteArray data;
QBuffer buffer(&data);
pixmap.save(&buffer, "BMP"); // Binary bitmap format, without compression effort
QString html = QString(
"<img src='data:image/bmp;base64, %0'>")
.arg(QString::fromLatin1(data.toBase64()));
return html;
}
QVariant BaseTrackTableModel::roleValue(
const QModelIndex& index,
QVariant&& rawValue,
int role) const {
const auto field = mapColumn(index.column());
if (field == ColumnCache::COLUMN_LIBRARYTABLE_INVALID) {
return rawValue;
}
switch (role) {
case Qt::ToolTipRole:
case kDataExportRole:
switch (field) {
case ColumnCache::COLUMN_LIBRARYTABLE_COLOR:
return mixxx::RgbColor::toQString(mixxx::RgbColor::fromQVariant(rawValue));
case ColumnCache::COLUMN_LIBRARYTABLE_COVERART:
return composeCoverArtToolTipHtml(index);
case ColumnCache::COLUMN_LIBRARYTABLE_PREVIEW:
return QVariant();
case ColumnCache::COLUMN_LIBRARYTABLE_RATING:
case ColumnCache::COLUMN_LIBRARYTABLE_TIMESPLAYED:
return rawValue;
default:
// Same value as for Qt::DisplayRole (see below)
break;
}
[[fallthrough]];
// NOTE: for export we need to fall through to Qt::DisplayRole,
// so do not add any other role cases here, or the export
// will be empty
case Qt::DisplayRole:
switch (field) {
case ColumnCache::COLUMN_LIBRARYTABLE_DURATION: {
if (rawValue.isNull()) {
return QVariant();
}
double durationInSeconds;
if (rawValue.canConvert<mixxx::Duration>()) {
const auto duration = rawValue.value<mixxx::Duration>();
VERIFY_OR_DEBUG_ASSERT(duration >= mixxx::Duration::empty()) {
return QVariant();
}
durationInSeconds = duration.toDoubleSeconds();
} else {
VERIFY_OR_DEBUG_ASSERT(rawValue.canConvert<double>()) {
return QVariant();
}
bool ok;
durationInSeconds = rawValue.toDouble(&ok);
VERIFY_OR_DEBUG_ASSERT(ok && durationInSeconds >= 0) {
return QVariant();
}
}
return mixxx::Duration::formatTime(
durationInSeconds,
mixxx::Duration::Precision::SECONDS);
}
case ColumnCache::COLUMN_LIBRARYTABLE_RATING: {
if (rawValue.isNull()) {
return QVariant();
}
VERIFY_OR_DEBUG_ASSERT(rawValue.canConvert<int>()) {
return QVariant();
}
bool ok;
const auto starCount = rawValue.toInt(&ok);
VERIFY_OR_DEBUG_ASSERT(ok && starCount >= StarRating::kMinStarCount) {
return QVariant();
}
return QVariant::fromValue(StarRating(starCount));
}
case ColumnCache::COLUMN_LIBRARYTABLE_TIMESPLAYED: {
if (rawValue.isNull()) {
return QVariant();
}
VERIFY_OR_DEBUG_ASSERT(rawValue.canConvert<int>()) {
return QVariant();
}
bool ok;
const auto timesPlayed = rawValue.toInt(&ok);
VERIFY_OR_DEBUG_ASSERT(ok && timesPlayed >= 0) {
return QVariant();
}
return QString::number(timesPlayed);
}
case ColumnCache::COLUMN_LIBRARYTABLE_DATETIMEADDED:
case ColumnCache::COLUMN_PLAYLISTTRACKSTABLE_DATETIMEADDED: {
VERIFY_OR_DEBUG_ASSERT(rawValue.canConvert<QDateTime>()) {
return QVariant();
}
// TODO: This is a hot code path, executed very often while library scrolling,
// and localDateTimeFromUtc is time consuming, probably because,
// we pass around QDateTime with a wrong time zone set
QDateTime dt = mixxx::localDateTimeFromUtc(rawValue.toDateTime());
if (role == Qt::ToolTipRole || role == kDataExportRole) {
// localized text date: "Wednesday, May 20, 1998 03:40:13 AM CEST"
return dt;
}
if (field == ColumnCache::COLUMN_PLAYLISTTRACKSTABLE_DATETIMEADDED) {
// Timestamp column in history feature:
// Use localized date/time format without text: "5/20/98 03:40 AM"
return mixxx::displayLocalDateTime(dt);
}
// For Date Added, use just the date: "5/20/98"
return dt.date();
}
case ColumnCache::COLUMN_LIBRARYTABLE_LAST_PLAYED_AT: {
QDateTime lastPlayedAt;
#if QT_VERSION >= QT_VERSION_CHECK(6, 0, 0)
if (rawValue.metaType().id() == QMetaType::QString) {
#else
if (rawValue.type() == QVariant::String) {
#endif
// column value
lastPlayedAt = mixxx::sqlite::readGeneratedTimestamp(rawValue);
} else {
// cached in memory (local time)
lastPlayedAt = rawValue.toDateTime().toUTC();
}
if (!lastPlayedAt.isValid()) {
return QVariant();
}
DEBUG_ASSERT(lastPlayedAt.timeSpec() == Qt::UTC);
// TODO: This is a hot code path, executed very often while library scrolling,
// and localDateTimeFromUtc is time consuming, probably because,
// we pass around QDateTime with a wrong time zone set
QDateTime dt = mixxx::localDateTimeFromUtc(lastPlayedAt);
if (role == Qt::ToolTipRole || role == kDataExportRole) {
return dt;
}
return dt.date();
}
case ColumnCache::COLUMN_LIBRARYTABLE_BPM: {
mixxx::Bpm bpm;
if (!rawValue.isNull()) {
if (rawValue.canConvert<mixxx::Bpm>()) {
bpm = rawValue.value<mixxx::Bpm>();
} else {
VERIFY_OR_DEBUG_ASSERT(rawValue.canConvert<double>()) {
return QVariant();
}
bool ok;
const auto bpmValue = rawValue.toDouble(&ok);
VERIFY_OR_DEBUG_ASSERT(ok) {
return QVariant();
}
bpm = mixxx::Bpm(bpmValue);
}
}
if (bpm.isValid()) {
if (role == Qt::ToolTipRole || role == kDataExportRole) {
return QString::number(bpm.value(), 'f', 4);
} else {
// Use the locale here to make the display and editor consistent.
// Custom precision, set in DlgPrefLibrary.
return QLocale().toString(bpm.value(), 'f', s_bpmColumnPrecision);
}
} else {
return QChar('-');
}
}
case ColumnCache::COLUMN_LIBRARYTABLE_BITRATE: {
if (rawValue.isNull()) {
return QVariant();
}
if (rawValue.canConvert<mixxx::audio::Bitrate>()) {
// return value as is
return rawValue;
} else {
VERIFY_OR_DEBUG_ASSERT(rawValue.canConvert<int>()) {
return QVariant();
}
bool ok;
const auto bitrateValue = rawValue.toInt(&ok);
VERIFY_OR_DEBUG_ASSERT(ok) {
return QVariant();
}
if (mixxx::audio::Bitrate(bitrateValue).isValid()) {
// return value as is
return rawValue;
} else {
// clear invalid values
return QVariant();
}
}
}
case ColumnCache::COLUMN_LIBRARYTABLE_KEY:
// The Key value is determined by either the KEY_ID or KEY column
return KeyUtils::keyFromKeyTextAndIdFields(
rawValue,
rawSiblingValue(
index, ColumnCache::COLUMN_LIBRARYTABLE_KEY_ID));
case ColumnCache::COLUMN_LIBRARYTABLE_REPLAYGAIN: {
if (rawValue.isNull()) {
return QVariant();
}
double rgRatio;
if (rawValue.canConvert<mixxx::ReplayGain>()) {
rgRatio = rawValue.value<mixxx::ReplayGain>().getRatio();
} else {
VERIFY_OR_DEBUG_ASSERT(rawValue.canConvert<double>()) {
return QVariant();
}
bool ok;
rgRatio = rawValue.toDouble(&ok);
VERIFY_OR_DEBUG_ASSERT(ok) {
return QVariant();
}
}
return mixxx::ReplayGain::ratioToString(rgRatio);
}
case ColumnCache::COLUMN_LIBRARYTABLE_CHANNELS:
// Not yet supported
DEBUG_ASSERT(rawValue.isNull());
break;
case ColumnCache::COLUMN_LIBRARYTABLE_SAMPLERATE:
// Not yet supported
DEBUG_ASSERT(rawValue.isNull());
break;
case ColumnCache::COLUMN_LIBRARYTABLE_URL:
// Not yet supported
DEBUG_ASSERT(rawValue.isNull());
break;
default:
// Otherwise, just use the column value
break;
}
break;
case Qt::EditRole:
switch (field) {
case ColumnCache::COLUMN_LIBRARYTABLE_BPM: {
bool ok;
const auto bpmValue = rawValue.toDouble(&ok);
if (!ok) {
return mixxx::Bpm::kValueUndefined;
}
return mixxx::Bpm{bpmValue}.valueOr(mixxx::Bpm::kValueUndefined);
}
case ColumnCache::COLUMN_LIBRARYTABLE_TIMESPLAYED:
return index.sibling(
index.row(),
fieldIndex(ColumnCache::COLUMN_LIBRARYTABLE_PLAYED))
.data()
.toBool();
case ColumnCache::COLUMN_LIBRARYTABLE_RATING:
VERIFY_OR_DEBUG_ASSERT(rawValue.canConvert<int>()) {
return QVariant();
}
return QVariant::fromValue(StarRating(rawValue.toInt()));
default:
// Otherwise, just use the column value
break;
}
break;
case Qt::CheckStateRole: {
QVariant boolValue;
switch (field) {
case ColumnCache::COLUMN_LIBRARYTABLE_PREVIEW:
boolValue = rawValue;
break;
case ColumnCache::COLUMN_LIBRARYTABLE_TIMESPLAYED:
boolValue = rawSiblingValue(
index,
ColumnCache::COLUMN_LIBRARYTABLE_PLAYED);
break;
case ColumnCache::COLUMN_LIBRARYTABLE_BPM:
boolValue = rawSiblingValue(
index,
ColumnCache::COLUMN_LIBRARYTABLE_BPM_LOCK);
break;
default:
// No check state supported
return QVariant();
}
// Flags in the database are stored as integers that are
// convertible to bool.
if (!boolValue.isNull() && boolValue.canConvert<bool>()) {
return boolValue.toBool() ? Qt::Checked : Qt::Unchecked;
} else {
// Undecidable
return Qt::PartiallyChecked;
}
}
// Right align BPM, duration and bitrate so big/small values can easily be
// spotted by length (number of digits)
case Qt::TextAlignmentRole: {
switch (field) {
case ColumnCache::COLUMN_LIBRARYTABLE_BPM:
case ColumnCache::COLUMN_LIBRARYTABLE_DURATION:
case ColumnCache::COLUMN_LIBRARYTABLE_BITRATE:
case ColumnCache::COLUMN_LIBRARYTABLE_TRACKNUMBER: {