-
Notifications
You must be signed in to change notification settings - Fork 717
Expand file tree
/
Copy pathplaylist.cpp
More file actions
2352 lines (1974 loc) · 72.1 KB
/
playlist.cpp
File metadata and controls
2352 lines (1974 loc) · 72.1 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
/* This file is part of Clementine.
Copyright 2010, David Sansome <me@davidsansome.com>
Clementine is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
Clementine is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with Clementine. If not, see <http://www.gnu.org/licenses/>.
*/
#include "playlist.h"
#include <QApplication>
#include <QBuffer>
#include <QCoreApplication>
#include <QDirIterator>
#include <QFileInfo>
#include <QLinkedList>
#include <QMimeData>
#include <QMutableListIterator>
#include <QSortFilterProxyModel>
#include <QUndoStack>
#include <QtConcurrentRun>
#include <QtDebug>
#include <algorithm>
#include <functional>
#include <memory>
#include <unordered_map>
#if (QT_VERSION >= QT_VERSION_CHECK(5, 10, 0))
#include <QRandomGenerator>
#endif
#include "core/application.h"
#include "core/closure.h"
#include "core/logging.h"
#include "core/player.h"
#include "core/tagreaderclient.h"
#include "core/timeconstants.h"
#include "internet/core/internetmimedata.h"
#include "internet/core/internetmodel.h"
#include "internet/core/internetplaylistitem.h"
#include "internet/core/internetsongmimedata.h"
#include "internet/internetradio/savedradio.h"
#include "internet/jamendo/jamendoplaylistitem.h"
#include "internet/jamendo/jamendoservice.h"
#include "internet/magnatune/magnatuneplaylistitem.h"
#include "internet/magnatune/magnatuneservice.h"
#include "library/library.h"
#include "library/librarybackend.h"
#include "library/librarymodel.h"
#include "library/libraryplaylistitem.h"
#include "playlistbackend.h"
#include "playlistfilter.h"
#include "playlistitemmimedata.h"
#include "playlistundocommands.h"
#include "playlistview.h"
#include "queue.h"
#include "smartplaylists/generator.h"
#include "smartplaylists/generatorinserter.h"
#include "smartplaylists/generatormimedata.h"
#include "songloaderinserter.h"
#include "songmimedata.h"
#include "songplaylistitem.h"
using std::shared_ptr;
using std::unordered_map;
using std::placeholders::_1;
using std::placeholders::_2;
using smart_playlists::Generator;
using smart_playlists::GeneratorInserter;
using smart_playlists::GeneratorPtr;
const char* Playlist::kCddaMimeType = "x-content/audio-cdda";
const char* Playlist::kRowsMimetype = "application/x-clementine-playlist-rows";
const char* Playlist::kPlayNowMimetype = "application/x-clementine-play-now";
const int Playlist::kInvalidSongPriority = 200;
const QRgb Playlist::kInvalidSongColor = qRgb(0xC0, 0xC0, 0xC0);
const int Playlist::kDynamicHistoryPriority = 100;
const QRgb Playlist::kDynamicHistoryColor = qRgb(0x80, 0x80, 0x80);
const char* Playlist::kSettingsGroup = "Playlist";
const char* Playlist::kPathType = "path_type";
const char* Playlist::kWriteMetadata = "write_metadata";
const char* Playlist::kSortIgnorePrefix = "sort_ignore_prefix";
const char* Playlist::kSortIgnorePrefixList = "sort_ignore_prefix_list";
const int Playlist::kUndoStackSize = 20;
const int Playlist::kUndoItemLimit = 500;
const qint64 Playlist::kMinScrobblePointNsecs = 31ll * kNsecPerSec;
const qint64 Playlist::kMaxScrobblePointNsecs = 240ll * kNsecPerSec;
namespace {
QString removePrefix(const QString& a, const QStringList& prefixes) {
for (const QString& prefix : prefixes) {
if (a.startsWith(prefix)) {
return a.mid(prefix.size());
}
}
return a;
}
} // namespace
Playlist::Playlist(PlaylistBackend* backend, TaskManager* task_manager,
LibraryBackend* library, int id, const QString& special_type,
bool favorite, QObject* parent)
: QAbstractListModel(parent),
is_loading_(false),
proxy_(new PlaylistFilter(this)),
queue_(new Queue(this)),
backend_(backend),
task_manager_(task_manager),
library_(library),
id_(id),
favorite_(favorite),
current_is_paused_(false),
current_virtual_index_(-1),
is_shuffled_(false),
scrobble_point_(-1),
lastfm_status_(LastFM_New),
have_incremented_playcount_(false),
playlist_sequence_(nullptr),
ignore_sorting_(false),
undo_stack_(new QUndoStack(this)),
special_type_(special_type),
cancel_restore_(false) {
undo_stack_->setUndoLimit(kUndoStackSize);
connect(this, SIGNAL(rowsInserted(const QModelIndex&, int, int)),
SIGNAL(PlaylistChanged()));
connect(this, SIGNAL(rowsRemoved(const QModelIndex&, int, int)),
SIGNAL(PlaylistChanged()));
Restore();
proxy_->setSourceModel(this);
queue_->setSourceModel(this);
connect(queue_, SIGNAL(rowsAboutToBeRemoved(QModelIndex, int, int)),
SLOT(TracksAboutToBeDequeued(QModelIndex, int, int)));
connect(queue_, SIGNAL(rowsRemoved(QModelIndex, int, int)),
SLOT(TracksDequeued()));
connect(queue_, SIGNAL(rowsInserted(const QModelIndex&, int, int)),
SLOT(TracksEnqueued(const QModelIndex&, int, int)));
connect(queue_, SIGNAL(layoutChanged()), SLOT(QueueLayoutChanged()));
column_alignments_ = PlaylistView::DefaultColumnAlignment();
min_play_count_point_nsecs_ = (31ll * kNsecPerSec); // 30 seconds
QSettings settings;
settings.beginGroup(Player::kSettingsGroup);
if (settings.value("play_count_short_duration").toBool()) {
max_play_count_point_nsecs_ = (60ll * kNsecPerSec); // 1 minute
} else {
max_play_count_point_nsecs_ = (240ll * kNsecPerSec); // 4 minutes
}
settings.endGroup();
qLog(Debug) << "k_max_scrobble_point"
<< (max_play_count_point_nsecs_ / kNsecPerSec);
}
Playlist::~Playlist() {
items_.clear();
library_items_by_id_.clear();
}
template <typename T>
void Playlist::InsertSongItems(const SongList& songs, int pos, bool play_now,
bool enqueue, bool enqueue_next) {
PlaylistItemList items;
for (const Song& song : songs) {
items << PlaylistItemPtr(new T(song));
}
InsertItems(items, pos, play_now, enqueue, enqueue_next);
}
QVariant Playlist::headerData(int section, Qt::Orientation, int role) const {
if (role != Qt::DisplayRole && role != Qt::ToolTipRole) return QVariant();
const QString name = column_name((Playlist::Column)section);
if (!name.isEmpty()) return name;
return QVariant();
}
bool Playlist::column_is_editable(Playlist::Column column) {
switch (column) {
case Column_Title:
case Column_Artist:
case Column_Album:
case Column_AlbumArtist:
case Column_Composer:
case Column_Performer:
case Column_Grouping:
case Column_Track:
case Column_Disc:
case Column_Year:
case Column_Genre:
case Column_Score:
case Column_Comment:
return true;
default:
break;
}
return false;
}
bool Playlist::set_column_value(Song& song, Playlist::Column column,
const QVariant& value) {
if (!song.IsEditable()) return false;
switch (column) {
case Column_Title:
song.set_title(value.toString());
break;
case Column_Artist:
song.set_artist(value.toString());
break;
case Column_Album:
song.set_album(value.toString());
break;
case Column_AlbumArtist:
song.set_albumartist(value.toString());
break;
case Column_Composer:
song.set_composer(value.toString());
break;
case Column_Performer:
song.set_performer(value.toString());
break;
case Column_Grouping:
song.set_grouping(value.toString());
break;
case Column_Track:
song.set_track(value.toInt());
break;
case Column_Disc:
song.set_disc(value.toInt());
break;
case Column_Year:
song.set_year(value.toInt());
break;
case Column_Genre:
song.set_genre(value.toString());
break;
case Column_Score:
song.set_score(value.toInt());
break;
case Column_Comment:
song.set_comment(value.toString());
break;
default:
break;
}
return true;
}
QVariant Playlist::data(const QModelIndex& index, int role) const {
switch (role) {
case Role_IsCurrent:
return current_item_index_.isValid() &&
index.row() == current_item_index_.row();
case Role_IsPaused:
return current_is_paused_;
case Role_StopAfter:
return stop_after_.isValid() && stop_after_.row() == index.row();
case Role_QueuePosition:
return queue_->PositionOf(index);
case Role_CanSetRating:
return index.column() == Column_Rating &&
items_[index.row()]->IsLocalLibraryItem() &&
items_[index.row()]->Metadata().id() != -1;
case Qt::EditRole:
case Qt::ToolTipRole:
case Qt::DisplayRole: {
PlaylistItemPtr item = items_[index.row()];
Song song = item->Metadata();
// Don't forget to change Playlist::CompareItems when adding new columns
switch (index.column()) {
case Column_Title:
return song.PrettyTitle();
case Column_Artist:
return song.artist();
case Column_Album:
return song.album();
case Column_Length:
return song.length_nanosec();
case Column_Track:
return song.track();
case Column_Disc:
return song.disc();
case Column_Year:
return song.year();
case Column_OriginalYear:
return song.effective_originalyear();
case Column_Genre:
return song.genre();
case Column_AlbumArtist:
return song.playlist_albumartist();
case Column_Composer:
return song.composer();
case Column_Performer:
return song.performer();
case Column_Grouping:
return song.grouping();
case Column_Rating:
return song.rating();
case Column_PlayCount:
return song.playcount();
case Column_SkipCount:
return song.skipcount();
case Column_LastPlayed:
return song.lastplayed();
case Column_Score:
return song.score();
case Column_BPM:
return song.bpm();
case Column_Bitrate:
return song.bitrate();
case Column_Samplerate:
return song.samplerate();
case Column_Filename:
return song.url();
case Column_BaseFilename:
return song.basefilename();
case Column_Filesize:
return song.filesize();
case Column_Filetype:
return song.filetype();
case Column_DateModified:
return song.mtime();
case Column_DateCreated:
return song.ctime();
case Column_Comment:
if (role == Qt::DisplayRole) return song.comment().simplified();
return song.comment();
case Column_Source:
return item->Url();
}
return QVariant();
}
case Qt::TextAlignmentRole:
return QVariant(column_alignments_.value(
index.column(), (Qt::AlignLeft | Qt::AlignVCenter)));
case Qt::ForegroundRole:
if (data(index, Role_IsCurrent).toBool()) {
// Ignore any custom colours for the currently playing item - they might
// clash with the glowing current track indicator.
return QVariant();
}
if (items_[index.row()]->HasCurrentForegroundColor()) {
return QBrush(items_[index.row()]->GetCurrentForegroundColor());
}
if (index.row() < dynamic_history_length()) {
return QBrush(kDynamicHistoryColor);
}
return QVariant();
case Qt::BackgroundRole:
if (data(index, Role_IsCurrent).toBool()) {
// Ignore any custom colours for the currently playing item - they might
// clash with the glowing current track indicator.
return QVariant();
}
if (items_[index.row()]->HasCurrentBackgroundColor()) {
return QBrush(items_[index.row()]->GetCurrentBackgroundColor());
}
return QVariant();
case Qt::FontRole:
if (items_[index.row()]->GetShouldSkip()) {
QFont track_font;
track_font.setStrikeOut(true);
return track_font;
}
return QVariant();
default:
return QVariant();
}
}
void Playlist::MoodbarUpdated(const QModelIndex& index) {
emit dataChanged(index.sibling(index.row(), Column_Mood),
index.sibling(index.row(), Column_Mood));
}
bool Playlist::setData(const QModelIndex& index, const QVariant& value,
int role) {
int row = index.row();
PlaylistItemPtr item = item_at(row);
Song song = item->Metadata();
if (index.data() == value) return false;
if (!set_column_value(song, (Column)index.column(), value)) return false;
if ((Column)index.column() == Column_Score) {
// The score is only saved in the database, not the file
library_->AddOrUpdateSongs(SongList() << song);
emit EditingFinished(index);
} else {
TagReaderReply* reply =
TagReaderClient::Instance()->SaveFile(song.url().toLocalFile(), song);
NewClosure(reply, SIGNAL(Finished(bool)), this,
SLOT(SongSaveComplete(TagReaderReply*, QPersistentModelIndex)),
reply, QPersistentModelIndex(index));
}
return true;
}
void Playlist::SongSaveComplete(TagReaderReply* reply,
const QPersistentModelIndex& index) {
if (reply->is_successful() && index.isValid()) {
if (reply->message().save_file_response().success()) {
QFuture<void> future = item_at(index.row())->BackgroundReload();
NewClosure(future, this, SLOT(ItemReloadComplete(QPersistentModelIndex)),
index);
} else {
emit Error(
tr("An error occurred writing metadata to '%1'")
.arg(QString::fromStdString(
reply->request_message().save_file_request().filename())));
}
}
reply->deleteLater();
}
void Playlist::ItemReloadComplete(const QPersistentModelIndex& index) {
if (index.isValid()) {
emit dataChanged(index, index);
emit EditingFinished(index);
}
}
int Playlist::current_row() const {
return current_item_index_.isValid() ? current_item_index_.row() : -1;
}
const QModelIndex Playlist::current_index() const {
return current_item_index_;
}
int Playlist::last_played_row() const {
return last_played_item_index_.isValid() ? last_played_item_index_.row() : -1;
}
void Playlist::ShuffleModeChanged(PlaylistSequence::ShuffleMode mode) {
is_shuffled_ = (mode != PlaylistSequence::Shuffle_Off);
ReshuffleIndices();
}
bool Playlist::FilterContainsVirtualIndex(int i) const {
if (i < 0 || i >= virtual_items_.count()) return false;
return proxy_->filterAcceptsRow(virtual_items_[i], QModelIndex());
}
int Playlist::NextVirtualIndex(int i, bool ignore_repeat_track) const {
PlaylistSequence::RepeatMode repeat_mode = playlist_sequence_->repeat_mode();
PlaylistSequence::ShuffleMode shuffle_mode =
playlist_sequence_->shuffle_mode();
bool album_only = repeat_mode == PlaylistSequence::Repeat_Album ||
shuffle_mode == PlaylistSequence::Shuffle_InsideAlbum;
// This one's easy - if we have to repeat the current track then just return i
if (repeat_mode == PlaylistSequence::Repeat_Track && !ignore_repeat_track) {
if (!FilterContainsVirtualIndex(i))
return virtual_items_.count(); // It's not in the filter any more
return i;
}
// If we're not bothered about whether a song is on the same album then
// return the next virtual index, whatever it is.
if (!album_only) {
++i;
// Advance i until we find any track that is in the filter, skipping
// the selected to be skipped
while (i < virtual_items_.count() &&
(!FilterContainsVirtualIndex(i) ||
item_at(virtual_items_[i])->GetShouldSkip())) {
++i;
}
return i;
}
// We need to advance i until we get something else on the same album
Song last_song = current_item_metadata();
for (int j = i + 1; j < virtual_items_.count(); ++j) {
if (item_at(virtual_items_[j])->GetShouldSkip()) {
continue;
}
Song this_song = item_at(virtual_items_[j])->Metadata();
if (((last_song.is_compilation() && this_song.is_compilation()) ||
last_song.effective_albumartist() ==
this_song.effective_albumartist()) &&
last_song.album() == this_song.album() &&
FilterContainsVirtualIndex(j)) {
return j; // Found one
}
}
// Couldn't find one - return past the end of the list
return virtual_items_.count();
}
int Playlist::PreviousVirtualIndex(int i, bool ignore_repeat_track) const {
PlaylistSequence::RepeatMode repeat_mode = playlist_sequence_->repeat_mode();
PlaylistSequence::ShuffleMode shuffle_mode =
playlist_sequence_->shuffle_mode();
bool album_only = repeat_mode == PlaylistSequence::Repeat_Album ||
shuffle_mode == PlaylistSequence::Shuffle_InsideAlbum;
// This one's easy - if we have to repeat the current track then just return i
if (repeat_mode == PlaylistSequence::Repeat_Track && !ignore_repeat_track) {
if (!FilterContainsVirtualIndex(i)) return -1;
return i;
}
// If we're not bothered about whether a song is on the same album then
// return the previous virtual index, whatever it is.
if (!album_only) {
--i;
// Decrement i until we find any track that is in the filter
while (i >= 0 && (!FilterContainsVirtualIndex(i) ||
item_at(virtual_items_[i])->GetShouldSkip()))
--i;
return i;
}
// We need to decrement i until we get something else on the same album
Song last_song = current_item_metadata();
for (int j = i - 1; j >= 0; --j) {
if (item_at(virtual_items_[j])->GetShouldSkip()) {
continue;
}
Song this_song = item_at(virtual_items_[j])->Metadata();
if (((last_song.is_compilation() && this_song.is_compilation()) ||
last_song.artist() == this_song.artist()) &&
last_song.album() == this_song.album() &&
FilterContainsVirtualIndex(j)) {
return j; // Found one
}
}
// Couldn't find one - return before the start of the list
return -1;
}
int Playlist::next_row(bool ignore_repeat_track) const {
// Any queued items take priority
if (!queue_->is_empty()) {
return queue_->PeekNext();
}
int next_virtual_index =
NextVirtualIndex(current_virtual_index_, ignore_repeat_track);
if (next_virtual_index >= virtual_items_.count()) {
// We've gone off the end of the playlist.
switch (playlist_sequence_->repeat_mode()) {
case PlaylistSequence::Repeat_Off:
case PlaylistSequence::Repeat_Intro:
return -1;
case PlaylistSequence::Repeat_Track:
next_virtual_index = current_virtual_index_;
break;
default:
next_virtual_index = NextVirtualIndex(-1, ignore_repeat_track);
break;
}
}
// Still off the end? Then just give up
if (next_virtual_index < 0 || next_virtual_index >= virtual_items_.count())
return -1;
return virtual_items_[next_virtual_index];
}
int Playlist::previous_row(bool ignore_repeat_track) const {
int prev_virtual_index =
PreviousVirtualIndex(current_virtual_index_, ignore_repeat_track);
if (prev_virtual_index < 0) {
// We've gone off the beginning of the playlist.
switch (playlist_sequence_->repeat_mode()) {
case PlaylistSequence::Repeat_Off:
return -1;
case PlaylistSequence::Repeat_Track:
prev_virtual_index = current_virtual_index_;
break;
default:
prev_virtual_index =
PreviousVirtualIndex(virtual_items_.count(), ignore_repeat_track);
break;
}
}
// Still off the beginning? Then just give up
if (prev_virtual_index < 0) return -1;
return virtual_items_[prev_virtual_index];
}
int Playlist::dynamic_history_length() const {
return dynamic_playlist_ && last_played_item_index_.isValid()
? last_played_item_index_.row() + 1
: 0;
}
void Playlist::set_current_row(int i, bool is_stopping) {
QModelIndex old_current_item_index = current_item_index_;
ClearStreamMetadata();
current_item_index_ = QPersistentModelIndex(index(i, 0, QModelIndex()));
// if the given item is the first in the queue, remove it from the queue
if (current_item_index_.row() == queue_->PeekNext()) {
queue_->TakeNext();
}
if (current_item_index_ == old_current_item_index) return;
if (old_current_item_index.isValid()) {
emit dataChanged(old_current_item_index,
old_current_item_index.sibling(
old_current_item_index.row(), ColumnCount - 1));
}
// Update the virtual index
if (i == -1) {
current_virtual_index_ = -1;
} else if (is_shuffled_ && current_virtual_index_ == -1) {
// This is the first thing we're playing so we want to make sure the array
// is shuffled
ReshuffleIndices();
// Bring the one we've been asked to play to the start of the list
virtual_items_.takeAt(virtual_items_.indexOf(i));
virtual_items_.prepend(i);
current_virtual_index_ = 0;
} else if (is_shuffled_) {
current_virtual_index_ = virtual_items_.indexOf(i);
} else {
current_virtual_index_ = i;
}
if (current_item_index_.isValid() && !is_stopping) {
InformOfCurrentSongChange();
}
// The structure of a dynamic playlist is as follows:
// history - active song - future
// We have to ensure that this invariant is maintained.
if (dynamic_playlist_ && current_item_index_.isValid()) {
using smart_playlists::Generator;
// When advancing to the next track
if (i > old_current_item_index.row()) {
// Move the new item one position ahead of the last item in the history.
MoveItemWithoutUndo(current_item_index_.row(), dynamic_history_length());
// Compute the number of new items that have to be inserted. This is not
// necessarily 1 because the user might have added or removed items
// manually. Note that the future excludes the current item.
const int count = dynamic_history_length() + 1 +
dynamic_playlist_->GetDynamicFuture() - items_.count();
if (count > 0) {
InsertDynamicItems(count);
}
// Shrink the history, again this is not necessarily by 1, because the
// user might have moved items by hand.
const int remove_count =
dynamic_history_length() - dynamic_playlist_->GetDynamicHistory();
if (0 < remove_count) RemoveItemsWithoutUndo(0, remove_count);
}
// the above actions make all commands on the undo stack invalid, so we
// better clear it.
undo_stack_->clear();
}
if (current_item_index_.isValid()) {
last_played_item_index_ = current_item_index_;
Save();
}
UpdateScrobblePoint();
}
void Playlist::InsertDynamicItems(int count) {
GeneratorInserter* inserter =
new GeneratorInserter(task_manager_, library_, this);
connect(inserter, SIGNAL(Error(QString)), SIGNAL(Error(QString)));
connect(inserter, SIGNAL(PlayRequested(QModelIndex)),
SIGNAL(PlayRequested(QModelIndex)));
inserter->Load(this, -1, false, false, false, dynamic_playlist_, count);
}
Qt::ItemFlags Playlist::flags(const QModelIndex& index) const {
Qt::ItemFlags flags = Qt::ItemIsEnabled | Qt::ItemIsSelectable;
if (column_is_editable((Column)index.column())) flags |= Qt::ItemIsEditable;
if (index.isValid()) return flags | Qt::ItemIsDragEnabled;
return Qt::ItemIsDropEnabled;
}
QStringList Playlist::mimeTypes() const {
return QStringList() << "text/uri-list" << kRowsMimetype
<< LibraryModel::kSmartPlaylistsMimeType;
}
Qt::DropActions Playlist::supportedDropActions() const {
return Qt::MoveAction | Qt::CopyAction | Qt::LinkAction;
}
bool Playlist::dropMimeData(const QMimeData* data, Qt::DropAction action,
int row, int, const QModelIndex&) {
if (action == Qt::IgnoreAction) return false;
using smart_playlists::GeneratorMimeData;
bool play_now = false;
bool enqueue_now = false;
bool enqueue_next_now = false;
if (const MimeData* mime_data = qobject_cast<const MimeData*>(data)) {
if (mime_data->clear_first_) {
Clear();
}
play_now = mime_data->play_now_;
enqueue_now = mime_data->enqueue_now_;
enqueue_next_now = mime_data->enqueue_next_now_;
}
if (const SongMimeData* song_data = qobject_cast<const SongMimeData*>(data)) {
// Dragged from a library
// We want to check if these songs are from the actual local file backend,
// if they are we treat them differently.
if (song_data->backend &&
song_data->backend->songs_table() == Library::kSongsTable)
InsertSongItems<LibraryPlaylistItem>(song_data->songs, row, play_now,
enqueue_now, enqueue_next_now);
else if (song_data->backend &&
song_data->backend->songs_table() == MagnatuneService::kSongsTable)
InsertSongItems<MagnatunePlaylistItem>(song_data->songs, row, play_now,
enqueue_now, enqueue_next_now);
else if (song_data->backend &&
song_data->backend->songs_table() == JamendoService::kSongsTable)
InsertSongItems<JamendoPlaylistItem>(song_data->songs, row, play_now,
enqueue_now, enqueue_next_now);
else
InsertSongItems<SongPlaylistItem>(song_data->songs, row, play_now,
enqueue_now, enqueue_next_now);
} else if (const InternetMimeData* internet_data =
qobject_cast<const InternetMimeData*>(data)) {
// Dragged from the Internet pane
InsertInternetItems(internet_data->model, internet_data->indexes, row,
play_now, enqueue_now, enqueue_next_now);
} else if (const InternetSongMimeData* internet_song_data =
qobject_cast<const InternetSongMimeData*>(data)) {
InsertInternetItems(internet_song_data->service, internet_song_data->songs,
row, play_now, enqueue_now, enqueue_next_now);
} else if (const GeneratorMimeData* generator_data =
qobject_cast<const GeneratorMimeData*>(data)) {
InsertSmartPlaylist(generator_data->generator_, row, play_now, enqueue_now,
enqueue_next_now);
} else if (const PlaylistItemMimeData* item_data =
qobject_cast<const PlaylistItemMimeData*>(data)) {
InsertItems(item_data->items_, row, play_now, enqueue_now,
enqueue_next_now);
} else if (data->hasFormat(kRowsMimetype)) {
// Dragged from the playlist
// Rearranging it is tricky...
// Get the list of rows that were moved
QList<int> source_rows;
Playlist* source_playlist = nullptr;
qint64 pid = 0;
qint64 own_pid = QCoreApplication::applicationPid();
QDataStream stream(data->data(kRowsMimetype));
stream.readRawData(reinterpret_cast<char*>(&source_playlist),
sizeof(source_playlist));
stream >> source_rows;
if (!stream.atEnd()) {
stream.readRawData((char*)&pid, sizeof(pid));
} else {
pid = !own_pid;
}
std::stable_sort(source_rows.begin(),
source_rows.end()); // Make sure we take them in order
if (source_playlist == this) {
// Dragged from this playlist - rearrange the items
undo_stack_->push(
new PlaylistUndoCommands::MoveItems(this, source_rows, row));
} else if (pid == own_pid) {
// Drag from a different playlist
PlaylistItemList items;
for (int row : source_rows) items << source_playlist->item_at(row);
if (items.count() > kUndoItemLimit) {
// Too big to keep in the undo stack. Also clear the stack because it
// might have been invalidated.
InsertItemsWithoutUndo(items, row, false, false);
undo_stack_->clear();
} else {
undo_stack_->push(
new PlaylistUndoCommands::InsertItems(this, items, row));
}
// Remove the items from the source playlist if it was a move event
if (action == Qt::MoveAction) {
for (int row : source_rows) {
source_playlist->undo_stack()->push(
new PlaylistUndoCommands::RemoveItems(source_playlist, row, 1));
}
}
}
} else if (data->hasFormat(kCddaMimeType)) {
SongLoaderInserter* inserter = new SongLoaderInserter(
task_manager_, library_, backend_->app()->player());
connect(inserter, SIGNAL(Error(QString)), SIGNAL(Error(QString)));
inserter->LoadAudioCD(this, row, play_now, enqueue_now, enqueue_next_now);
} else if (data->hasUrls()) {
// URL list dragged from the file list or some other app
InsertUrls(data->urls(), row, play_now, enqueue_now, enqueue_next_now);
}
return true;
}
void Playlist::InsertUrls(const QList<QUrl>& urls, int pos, bool play_now,
bool enqueue, bool enqueue_next) {
SongLoaderInserter* inserter = new SongLoaderInserter(
task_manager_, library_, backend_->app()->player());
connect(inserter, SIGNAL(Error(QString)), SIGNAL(Error(QString)));
inserter->Load(this, pos, play_now, enqueue, enqueue_next, urls);
}
void Playlist::InsertSmartPlaylist(GeneratorPtr generator, int pos,
bool play_now, bool enqueue,
bool enqueue_next) {
// Hack: If the generator hasn't got a library set then use the main one
if (!generator->library()) {
generator->set_library(library_);
}
GeneratorInserter* inserter =
new GeneratorInserter(task_manager_, library_, this);
connect(inserter, SIGNAL(Error(QString)), SIGNAL(Error(QString)));
inserter->Load(this, pos, play_now, enqueue, enqueue_next, generator);
if (generator->is_dynamic()) {
TurnOnDynamicPlaylist(generator);
}
}
void Playlist::TurnOnDynamicPlaylist(GeneratorPtr gen) {
dynamic_playlist_ = gen;
playlist_sequence_->SetUsingDynamicPlaylist(true);
ShuffleModeChanged(PlaylistSequence::Shuffle_Off);
emit DynamicModeChanged(true);
Save();
}
void Playlist::MoveItemWithoutUndo(int source, int dest) {
MoveItemsWithoutUndo(QList<int>() << source, dest);
}
void Playlist::MoveItemsWithoutUndo(const QList<int>& source_rows, int pos) {
layoutAboutToBeChanged();
PlaylistItemList moved_items;
if (pos < 0) {
pos = items_.count();
}
// Take the items out of the list first, keeping track of whether the
// insertion point changes
int offset = 0;
int start = pos;
for (int source_row : source_rows) {
moved_items << items_.takeAt(source_row - offset);
if (pos > source_row) {
start--;
}
offset++;
}
// Put the items back in
for (int i = start; i < start + moved_items.count(); ++i) {
moved_items[i - start]->RemoveForegroundColor(kDynamicHistoryPriority);
items_.insert(i, moved_items[i - start]);
}
// Update persistent indexes
for (const QModelIndex& pidx : persistentIndexList()) {
const int dest_offset = source_rows.indexOf(pidx.row());
if (dest_offset != -1) {
// This index was moved
changePersistentIndex(
pidx, index(start + dest_offset, pidx.column(), QModelIndex()));
} else {
int d = 0;
for (int source_row : source_rows) {
if (pidx.row() > source_row) d--;
}
if (pidx.row() + d >= start) d += source_rows.count();
changePersistentIndex(
pidx, index(pidx.row() + d, pidx.column(), QModelIndex()));
}
}
current_virtual_index_ = virtual_items_.indexOf(current_row());
layoutChanged();
Save();
}
void Playlist::MoveItemsWithoutUndo(int start, const QList<int>& dest_rows) {
layoutAboutToBeChanged();
PlaylistItemList moved_items;
int pos = start;
for (int dest_row : dest_rows) {
if (dest_row < pos) start--;
}
if (start < 0) {
start = items_.count() - dest_rows.count();
}
// Take the items out of the list first
for (int i = 0; i < dest_rows.count(); i++)
moved_items << items_.takeAt(start);
// Put the items back in
int offset = 0;
for (int dest_row : dest_rows) {
items_.insert(dest_row, moved_items[offset]);
offset++;
}
// Update persistent indexes
for (const QModelIndex& pidx : persistentIndexList()) {
if (pidx.row() >= start && pidx.row() < start + dest_rows.count()) {
// This index was moved
const int i = pidx.row() - start;
changePersistentIndex(pidx,
index(dest_rows[i], pidx.column(), QModelIndex()));
} else {