-
-
Notifications
You must be signed in to change notification settings - Fork 1.8k
Expand file tree
/
Copy pathautodjfeature.cpp
More file actions
459 lines (410 loc) · 17 KB
/
Copy pathautodjfeature.cpp
File metadata and controls
459 lines (410 loc) · 17 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
#include "library/autodj/autodjfeature.h"
#include <QMenu>
#include <QtDebug>
#include "controllers/keyboard/keyboardeventfilter.h"
#include "library/autodj/autodjprocessor.h"
#include "library/autodj/dlgautodj.h"
#include "library/dao/trackschema.h"
#include "library/library.h"
#include "library/parser.h"
#include "library/trackcollection.h"
#include "library/trackcollectionmanager.h"
#include "library/trackset/crate/cratestorage.h"
#include "library/treeitem.h"
#include "moc_autodjfeature.cpp"
#include "sources/soundsourceproxy.h"
#include "track/track.h"
#include "util/clipboard.h"
#include "util/defs.h"
#include "util/dnd.h"
#include "widget/wlibrary.h"
#include "widget/wlibrarysidebar.h"
namespace {
constexpr int kMaxRetrieveAttempts = 3;
int findOrCreateAutoDjPlaylistId(PlaylistDAO& playlistDAO) {
int playlistId = playlistDAO.getPlaylistIdFromName(AUTODJ_TABLE);
// If the AutoDJ playlist does not exist yet then create it.
if (playlistId < 0) {
playlistId = playlistDAO.createPlaylist(
AUTODJ_TABLE, PlaylistDAO::PLHT_AUTO_DJ);
VERIFY_OR_DEBUG_ASSERT(playlistId >= 0) {
qWarning() << "Failed to create Auto DJ playlist!";
}
}
return playlistId;
}
/// Create a title for the Auto DJ node
QString createAutoDjTitle(const QString& name,
int count,
mixxx::Duration duration,
bool showCountRemaining,
bool showTimeRemaining) {
QString result(name);
// Show duration and track count only if Auto DJ queue has tracks
if (count > 0 && showCountRemaining) {
result.append(QStringLiteral(" ("));
result.append(QString::number(count));
result.append(QStringLiteral(")"));
}
if (count > 0 && showTimeRemaining) {
result.append(QStringLiteral(" "));
result.append(mixxx::Duration::formatTime(
duration.toDoubleSeconds(),
mixxx::Duration::Precision::SECONDS));
}
return result;
}
} // anonymous namespace
AutoDJFeature::AutoDJFeature(Library* pLibrary,
UserSettingsPointer pConfig,
PlayerManagerInterface* pPlayerManager)
: LibraryFeature(pLibrary, pConfig, QStringLiteral("autodj")),
m_pTrackCollection(pLibrary->trackCollectionManager()->internalCollection()),
m_playlistDao(m_pTrackCollection->getPlaylistDAO()),
m_iAutoDJPlaylistId(findOrCreateAutoDjPlaylistId(m_playlistDao)),
m_pAutoDJProcessor(nullptr),
m_pSidebarModel(make_parented<TreeItemModel>(this)),
m_pAutoDJView(nullptr),
m_viewName(Library::kAutoDJViewName),
m_autoDjCratesDao(m_iAutoDJPlaylistId, pLibrary->trackCollectionManager(), m_pConfig) {
qRegisterMetaType<AutoDJProcessor::AutoDJState>("AutoDJState");
m_pAutoDJProcessor = new AutoDJProcessor(this,
m_pConfig,
pPlayerManager,
pLibrary->trackCollectionManager(),
m_iAutoDJPlaylistId);
// Connect loadTrackToPlayer signal as a queued connection to make sure all callbacks of a
// previous load attempt have been called #10504.
connect(m_pAutoDJProcessor,
&AutoDJProcessor::loadTrackToPlayer,
this,
&LibraryFeature::loadTrackToPlayer,
Qt::QueuedConnection);
// Update the title of the "Auto DJ" node when the
// list of queued tracks or their properties have changed.
connect(m_pAutoDJProcessor,
&AutoDJProcessor::queueDurationChanged,
this,
&AutoDJFeature::slotRemainingQueueDurationChanged);
m_playlistDao.setAutoDJProcessor(m_pAutoDJProcessor);
// Create the "Crates" tree-item under the root item.
std::unique_ptr<TreeItem> pRootItem = TreeItem::newRoot(this);
m_pCratesTreeItem = pRootItem->appendChild(tr("Crates"));
m_pCratesTreeItem->setIcon(QIcon(":/images/library/ic_library_crates.svg"));
// Create tree-items under "Crates".
constructCrateChildModel();
m_pSidebarModel->setRootItem(std::move(pRootItem));
// Be notified when the status of crates changes.
connect(m_pTrackCollection,
&TrackCollection::crateInserted,
this,
&AutoDJFeature::slotCrateChanged);
connect(m_pTrackCollection,
&TrackCollection::crateUpdated,
this,
&AutoDJFeature::slotCrateChanged);
connect(m_pTrackCollection,
&TrackCollection::crateDeleted,
this,
&AutoDJFeature::slotCrateChanged);
// Create context-menu items for enabling/disabling the auto-DJ
m_pEnableAutoDJAction = make_parented<QAction>(tr("Enable Auto DJ"), this);
connect(m_pEnableAutoDJAction.get(),
&QAction::triggered,
this,
&AutoDJFeature::slotEnableAutoDJ);
m_pDisableAutoDJAction = make_parented<QAction>(tr("Disable Auto DJ"), this);
connect(m_pDisableAutoDJAction.get(),
&QAction::triggered,
this,
&AutoDJFeature::slotDisableAutoDJ);
// Create context-menu item for clearing the auto-DJ queue
m_pClearQueueAction = make_parented<QAction>(tr("Clear Auto DJ Queue"), this);
const auto removeKeySequence =
// TODO(XXX): Qt6 replace enum | with QKeyCombination
QKeySequence(static_cast<int>(kHideRemoveShortcutModifier) |
kHideRemoveShortcutKey);
m_pClearQueueAction->setShortcut(removeKeySequence);
connect(m_pClearQueueAction.get(),
&QAction::triggered,
this,
&AutoDJFeature::slotClearQueue);
// Create context menu item to allow crates to be removed from AutoDJ sources.
// onRightClickChild() gets the clicked crate's id form the sidebar model and
// assigns it to this action's data.
// In slotRemoveCrateFromAutoDj() we retrieve the CrateId data and finally
// remove the crate from sources in removeCrateFromAutoDj().
m_pRemoveCrateFromAutoDjAction =
make_parented<QAction>(tr("Remove Crate as Track Source"), this);
m_pRemoveCrateFromAutoDjAction->setShortcut(removeKeySequence);
connect(m_pRemoveCrateFromAutoDjAction.get(),
&QAction::triggered,
this,
&AutoDJFeature::slotRemoveCrateFromAutoDj);
}
AutoDJFeature::~AutoDJFeature() {
delete m_pAutoDJProcessor;
}
QVariant AutoDJFeature::title() {
return createAutoDjTitle(tr("Auto DJ"),
m_pAutoDJProcessor->getQueueTrackCount(),
m_pAutoDJProcessor->getQueueDuration(),
true,
true);
}
void AutoDJFeature::slotRemainingQueueDurationChanged(int numTracks, mixxx::Duration duration) {
Q_UNUSED(numTracks);
Q_UNUSED(duration);
// As documented by the code docs for featureIsLoading,
// it is intended to indicate when the title() has changed.
emit featureIsLoading(this, false);
}
void AutoDJFeature::bindLibraryWidget(
WLibrary* libraryWidget,
KeyboardEventFilter* keyboard) {
m_pAutoDJView = new DlgAutoDJ(
libraryWidget,
m_pConfig,
m_pLibrary,
m_pAutoDJProcessor,
keyboard);
libraryWidget->registerView(m_viewName, m_pAutoDJView);
connect(m_pAutoDJView,
&DlgAutoDJ::loadTrack,
this,
&AutoDJFeature::loadTrack);
connect(m_pAutoDJView,
&DlgAutoDJ::loadTrackToPlayer,
this,
&LibraryFeature::loadTrackToPlayer);
connect(m_pAutoDJView,
&DlgAutoDJ::trackSelected,
this,
&AutoDJFeature::trackSelected);
// Be informed when the user wants to add another random track.
connect(m_pAutoDJProcessor,
&AutoDJProcessor::randomTrackRequested,
this,
&AutoDJFeature::slotRandomQueue);
connect(m_pAutoDJView,
&DlgAutoDJ::addRandomTrackButton,
this,
&AutoDJFeature::slotAddRandomTrack);
// Update shortcuts displayed in the context menu
QKeySequence toggleAutoDJShortcut = QKeySequence(
keyboard->getKeyboardConfig()->getValueString(ConfigKey("[AutoDJ]", "enabled")),
QKeySequence::PortableText);
m_pEnableAutoDJAction->setShortcut(toggleAutoDJShortcut);
m_pDisableAutoDJAction->setShortcut(toggleAutoDJShortcut);
}
void AutoDJFeature::bindSidebarWidget(WLibrarySidebar* pSidebarWidget) {
// store the sidebar widget pointer for later use in onRightClickChild
m_pSidebarWidget = pSidebarWidget;
}
TreeItemModel* AutoDJFeature::sidebarModel() const {
return m_pSidebarModel;
}
void AutoDJFeature::activate() {
//qDebug() << "AutoDJFeature::activate()";
emit switchToView(m_viewName);
emit disableSearch();
emit enableCoverArtDisplay(true);
}
void AutoDJFeature::clear() {
QMessageBox::StandardButton btn = QMessageBox::question(nullptr,
tr("Confirmation Clear"),
tr("Do you really want to remove all tracks from the Auto DJ queue?") +
tr("This can not be undone."),
QMessageBox::Yes | QMessageBox::No,
QMessageBox::No);
if (btn == QMessageBox::Yes) {
m_playlistDao.clearAutoDJQueue();
}
}
void AutoDJFeature::paste() {
emit pasteFromSidebar();
}
// Called by SidebarModel
void AutoDJFeature::deleteItem(const QModelIndex& index) {
TreeItem* pSelectedItem = static_cast<TreeItem*>(index.internalPointer());
if (!pSelectedItem || pSelectedItem == m_pCratesTreeItem) {
return;
}
CrateId crateId(pSelectedItem->getData());
removeCrateFromAutoDj(crateId);
}
// Called by deleteItem and slotRemoveCrateFromAutoDj()
void AutoDJFeature::removeCrateFromAutoDj(CrateId crateId) {
DEBUG_ASSERT(crateId.isValid());
// TODO Confirm dialog?
m_pTrackCollection->updateAutoDjCrate(crateId, false);
}
bool AutoDJFeature::dropAccept(const QList<QUrl>& urls, QObject* pSource) {
// If a track is dropped onto the Auto DJ tree node, but the track isn't in the
// library, then add the track to the library before adding it to the
// Auto DJ playlist.
// pSource != nullptr it is a drop from inside Mixxx and indicates all
// tracks already in the DB
const QList<mixxx::FileInfo> fileInfos =
// collect all tracks, accept playlist files
DragAndDropHelper::supportedTracksFromUrls(urls, false, true);
const QList<TrackId> trackIds =
m_pLibrary->trackCollectionManager()->resolveTrackIds(fileInfos, pSource);
if (trackIds.isEmpty()) {
return false;
}
// Return whether appendTracksToPlaylist succeeded.
return m_playlistDao.appendTracksToPlaylist(trackIds, m_iAutoDJPlaylistId);
}
bool AutoDJFeature::dragMoveAccept(const QList<QUrl>& urls) {
return DragAndDropHelper::urlsContainSupportedTrackFiles(urls, true);
}
void AutoDJFeature::slotEnableAutoDJ() {
m_pAutoDJProcessor->toggleAutoDJ(true);
}
void AutoDJFeature::slotDisableAutoDJ() {
m_pAutoDJProcessor->toggleAutoDJ(false);
}
void AutoDJFeature::slotClearQueue() {
clear();
}
// Add a crate to the AutoDJ sources
void AutoDJFeature::slotAddCrateToAutoDj(CrateId crateId) {
m_pTrackCollection->updateAutoDjCrate(crateId, true);
}
void AutoDJFeature::slotRemoveCrateFromAutoDj() {
CrateId crateId(m_pRemoveCrateFromAutoDjAction->data());
removeCrateFromAutoDj(crateId);
}
void AutoDJFeature::slotCrateChanged(CrateId crateId) {
Crate crate;
if (m_pTrackCollection->crates().readCrateById(crateId, &crate) && crate.isAutoDjSource()) {
// Crate exists and is already a source for AutoDJ
// -> Find and update the corresponding child item
for (int i = 0; i < m_crateList.length(); ++i) {
if (m_crateList[i].getId() == crateId) {
QModelIndex parentIndex = m_pSidebarModel->index(0, 0);
QModelIndex childIndex = m_pSidebarModel->index(i, 0, parentIndex);
m_pSidebarModel->setData(childIndex, crate.getName(), Qt::DisplayRole);
m_crateList[i] = crate;
return; // early exit
}
}
// No child item for crate found
// -> Create and append a new child item for this crate
// TODO() Use here std::span to get around the heap alloctaion of
// std::vector for a single element.
std::vector<std::unique_ptr<TreeItem>> rows;
rows.push_back(std::make_unique<TreeItem>(crate.getName(), crate.getId().toVariant()));
QModelIndex parentIndex = m_pSidebarModel->index(0, 0);
m_pSidebarModel->insertTreeItemRows(std::move(rows), m_crateList.length(), parentIndex);
m_crateList.append(crate);
} else {
// Crate does not exist or is not a source for AutoDJ
// -> Find and remove the corresponding child item
for (int i = 0; i < m_crateList.length(); ++i) {
if (m_crateList[i].getId() == crateId) {
QModelIndex parentIndex = m_pSidebarModel->index(0, 0);
m_pSidebarModel->removeRows(i, 1, parentIndex);
m_crateList.removeAt(i);
return; // early exit
}
}
}
}
void AutoDJFeature::slotAddRandomTrack() {
if (m_iAutoDJPlaylistId >= 0) {
TrackPointer pRandomTrack;
for (int failedRetrieveAttempts = 0;
!pRandomTrack && (failedRetrieveAttempts < 2 * kMaxRetrieveAttempts); // 2 rounds
++failedRetrieveAttempts) {
TrackId randomTrackId;
if (m_crateList.isEmpty()) {
// Fetch Track from Library since we have no assigned crates
randomTrackId = m_autoDjCratesDao.getRandomTrackIdFromLibrary(
m_iAutoDJPlaylistId);
} else {
// Fetch track from crates.
// We do not fall back to Library if this fails because this
// may add banned tracks
randomTrackId = m_autoDjCratesDao.getRandomTrackId();
}
if (randomTrackId.isValid()) {
pRandomTrack = m_pLibrary->trackCollectionManager()->getTrackById(randomTrackId);
VERIFY_OR_DEBUG_ASSERT(pRandomTrack) {
qWarning() << "Track does not exist:"
<< randomTrackId;
continue;
}
if (!pRandomTrack->getFileInfo().checkFileExists()) {
qWarning() << "Track does not exist:"
<< pRandomTrack->getInfo()
<< pRandomTrack->getLocation();
pRandomTrack.reset();
}
}
}
if (pRandomTrack) {
m_pTrackCollection->getPlaylistDAO().appendTrackToPlaylist(
pRandomTrack->getId(), m_iAutoDJPlaylistId);
m_pAutoDJView->onShow();
return; // success
}
}
qWarning() << "Could not load random track.";
}
void AutoDJFeature::constructCrateChildModel() {
m_crateList.clear();
CrateSelectResult autoDjCrates(m_pTrackCollection->crates().selectAutoDjCrates(true));
Crate crate;
while (autoDjCrates.populateNext(&crate)) {
// Create the TreeItem for this crate.
m_pCratesTreeItem->appendChild(crate.getName(), crate.getId().toVariant());
m_crateList.append(crate);
}
}
void AutoDJFeature::onRightClick(const QPoint& globalPos) {
QMenu menu(m_pSidebarWidget);
if (m_pAutoDJProcessor->getState() == AutoDJProcessor::ADJ_DISABLED) {
menu.addAction(m_pEnableAutoDJAction.get());
} else {
menu.addAction(m_pDisableAutoDJAction.get());
}
menu.addAction(m_pClearQueueAction.get());
menu.exec(globalPos);
}
void AutoDJFeature::onRightClickChild(const QPoint& globalPos,
const QModelIndex& index) {
TreeItem* pClickedItem = static_cast<TreeItem*>(index.internalPointer());
QMenu menu(m_pSidebarWidget);
if (m_pCratesTreeItem == pClickedItem) {
// The "Crates" parent item was right-clicked.
// Bring up the context menu.
QMenu crateMenu(m_pSidebarWidget);
crateMenu.setTitle(tr("Add Crate as Track Source"));
CrateSelectResult nonAutoDjCrates(m_pTrackCollection->crates().selectAutoDjCrates(false));
Crate crate;
while (nonAutoDjCrates.populateNext(&crate)) {
auto pAction = std::make_unique<QAction>(crate.getName(), &crateMenu);
auto crateId = crate.getId();
connect(pAction.get(), &QAction::triggered, this, [this, crateId] {
slotAddCrateToAutoDj(crateId);
});
crateMenu.addAction(pAction.get());
pAction.release();
}
menu.addMenu(&crateMenu);
menu.exec(globalPos);
} else {
// A crate child item was right-clicked.
// Bring up the context menu.
m_pRemoveCrateFromAutoDjAction->setData(pClickedItem->getData()); // the selected CrateId
menu.addAction(m_pRemoveCrateFromAutoDjAction);
menu.exec(globalPos);
}
}
void AutoDJFeature::slotRandomQueue(int numTracksToAdd) {
for (int addCount = 0; addCount < numTracksToAdd; ++addCount) {
slotAddRandomTrack();
}
}