-
-
Notifications
You must be signed in to change notification settings - Fork 3
/
playlist.cpp
2184 lines (1742 loc) · 60.9 KB
/
playlist.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
/**
* Copyright (C) 2002-2004 Scott Wheeler <wheeler@kde.org>
* Copyright (C) 2008-2018 Michael Pyne <mpyne@kde.org>
*
* This program 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 2 of the License, or (at your option) any later
* version.
*
* This program 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
* this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include "playlist.h"
#include "juk-exception.h"
#include <KLocalizedString>
#include <KSharedConfig>
#include <kconfig.h>
#include <kmessagebox.h>
#include <kiconloader.h>
#include <klineedit.h>
#include <kio/copyjob.h>
#include <kactioncollection.h>
#include <kconfiggroup.h>
#include <ktoolbarpopupaction.h>
#include <kactionmenu.h>
#include <ktoggleaction.h>
#include <QActionGroup>
#include <QClipboard>
#include <QCursor>
#include <QDesktopServices>
#include <QDir>
#include <QDragEnterEvent>
#include <QDropEvent>
#include <QFile>
#include <QFileDialog>
#include <QHeaderView>
#include <QKeyEvent>
#include <QList>
#include <QMenu>
#include <QMimeData>
#include <QMouseEvent>
#include <QPainter>
#include <QResizeEvent>
#include <QScrollBar>
#include <QSet>
#include <QStackedWidget>
#include <QTextStream>
#include <QTimer>
#include <QtConcurrent>
#include <QFutureWatcher>
#include <id3v1genres.h>
#include <time.h>
#include <cmath>
#include <algorithm>
#include <random>
#include <utility>
#include "actioncollection.h"
#include "cache.h"
#include "collectionlist.h"
#include "coverinfo.h"
#include "deletedialog.h"
#include "directoryloader.h"
#include "filerenamer.h"
#include "iconsupport.h"
#include "juk_debug.h"
#include "juktag.h"
#include "mediafiles.h"
#include "playlistcollection.h"
#include "playlistitem.h"
#include "playlistsearch.h"
#include "playlistsharedsettings.h"
#include "tagtransactionmanager.h"
#include "upcomingplaylist.h"
using namespace ActionCollection; // ""_act and others
using std::as_const;
/**
* Used to give every track added in the program a unique identifier. See
* PlaylistItem
*/
quint32 g_trackID = 0;
/**
* Just a shortcut of sorts.
*/
static bool manualResize()
{
return "resizeColumnsManually"_act->isChecked();
}
////////////////////////////////////////////////////////////////////////////////
// static members
////////////////////////////////////////////////////////////////////////////////
bool Playlist::m_visibleChanged = false;
bool Playlist::m_shuttingDown = false;
PlaylistItemList Playlist::m_history;
QVector<PlaylistItem *> Playlist::m_backMenuItems;
int Playlist::m_leftColumn = 0;
////////////////////////////////////////////////////////////////////////////////
// public members
////////////////////////////////////////////////////////////////////////////////
Playlist::Playlist(
bool delaySetup, const QString &name,
PlaylistCollection *collection, const QString &iconName,
int extraCols)
: QTreeWidget(collection->playlistStack())
, m_collection(collection)
, m_playlistName(name)
, m_refillDebounce(new QTimer(this))
{
setup(extraCols);
// The timer soaks up repeated events that may cause the random play list
// to be regenerated repeatedly.
m_refillDebounce->setInterval(100);
m_refillDebounce->setSingleShot(true);
connect(m_refillDebounce, &QTimer::timeout,
this, &Playlist::refillRandomList);
// Any of the random-related actions being triggered will cause the parent
// group to emit the triggered signal.
QActionGroup *randomGroup = action("disableRandomPlay")->actionGroup();
connect(randomGroup, &QActionGroup::triggered,
m_refillDebounce, qOverload<>(&QTimer::start));
// Some subclasses need to do even more handling but will remember to
// call setupPlaylist
if(!delaySetup) {
collection->setupPlaylist(this, iconName);
}
}
Playlist::Playlist(PlaylistCollection *collection, const QString &name,
const QString &iconName)
: Playlist(false, name, collection, iconName, 0)
{
}
Playlist::Playlist(PlaylistCollection *collection, const PlaylistItemList &items,
const QString &name, const QString &iconName)
: Playlist(false, name, collection, iconName, 0)
{
createItems(items);
}
Playlist::Playlist(PlaylistCollection *collection, const QFileInfo &playlistFile,
const QString &iconName)
: Playlist(true, QString(), collection, iconName, 0)
{
m_fileName = playlistFile.canonicalFilePath();
// Load the file after construction completes so that virtual methods in
// subclasses can take effect.
QTimer::singleShot(0, this, [=]() {
loadFile(m_fileName, playlistFile);
collection->setupPlaylist(this, iconName);
});
}
Playlist::Playlist(PlaylistCollection *collection, bool delaySetup, int extraColumns)
: Playlist(delaySetup, QString(), collection, QStringLiteral("audio-midi"), extraColumns)
{
}
Playlist::~Playlist()
{
// clearItem() will take care of removing the items from the history,
// so call clearItems() to make sure it happens.
//
// Some subclasses override clearItems and items so we manually dispatch to
// make clear that it's intentional that those subclassed versions don't
// get called (because we can't call them)
m_randomSequence.clear();
Playlist::clearItems(Playlist::items());
if(!m_shuttingDown)
m_collection->removePlaylist(this);
}
QString Playlist::name() const
{
if(m_playlistName.isEmpty())
return m_fileName.section(QDir::separator(), -1).section('.', 0, -2);
else
return m_playlistName;
}
FileHandle Playlist::currentFile() const
{
return playingItem() ? playingItem()->file() : FileHandle();
}
void Playlist::playFirst()
{
QTreeWidgetItemIterator listIt(const_cast<Playlist *>(this), QTreeWidgetItemIterator::NotHidden);
beginPlayingItem(static_cast<PlaylistItem *>(*listIt));
refillRandomList();
}
void Playlist::playNextAlbum()
{
const auto &item = playingItem();
if(!item || !action("albumRandomPlay")->isChecked()) {
playNext();
return;
}
const auto currentAlbum = item->file().tag()->album();
const auto nextAlbumTrack = std::find_if(m_randomSequence.begin(), m_randomSequence.end(),
[currentAlbum](const PlaylistItem *item) {
return item->file().tag()->album() != currentAlbum;
});
if(nextAlbumTrack == m_randomSequence.end()) {
// We were on the last album, playNext will handle looping if we should loop
m_randomSequence.clear();
playNext();
}
else {
m_randomSequence.erase(m_randomSequence.begin(), nextAlbumTrack);
beginPlayingItem(*nextAlbumTrack);
}
}
void Playlist::playNext()
{
PlaylistItem *next = nullptr;
auto nowPlaying = playingItem();
bool doLoop = action("loopPlaylist")->isChecked();
// Treat an item from a different playlist as if we were being asked to
// play from a stop
if(nowPlaying && nowPlaying->playlist() != this) {
nowPlaying = nullptr;
}
if(action("disableRandomPlay")->isChecked()) {
QTreeWidgetItemIterator listIt = nowPlaying
? QTreeWidgetItemIterator(nowPlaying, QTreeWidgetItemIterator::NotHidden)
: QTreeWidgetItemIterator(this, QTreeWidgetItemIterator::NotHidden);
if(*listIt && nowPlaying) {
++listIt;
}
next = static_cast<PlaylistItem *>(*listIt);
if(!next && doLoop) {
playFirst();
return;
}
}
else {
// The two random play modes are identical here, the difference is in how the
// randomized sequence is generated by refillRandomList
if(m_randomSequence.isEmpty() && (doLoop || !nowPlaying)) {
refillRandomList();
// Don't play the same track twice in a row even if it can
// "randomly" happen
if(m_randomSequence.front() == nowPlaying) {
std::swap(m_randomSequence.front(), m_randomSequence.back());
}
}
if(!m_randomSequence.isEmpty()) {
next = m_randomSequence.takeFirst();
}
}
// Will stop playback if next is still null
beginPlayingItem(next);
}
void Playlist::stop()
{
m_history.clear();
setPlaying(nullptr);
}
void Playlist::playPrevious()
{
if(!playingItem())
return;
bool random = action("randomPlay") && action<KToggleAction>("randomPlay")->isChecked();
PlaylistItem *previous = nullptr;
if(random && !m_history.isEmpty()) {
previous = m_history.last();
m_history.removeLast();
}
else {
m_history.clear();
QTreeWidgetItemIterator listIt(playingItem(), QTreeWidgetItemIterator::NotHidden);
previous = static_cast<PlaylistItem *>(*--listIt);
}
beginPlayingItem(previous);
}
void Playlist::setName(const QString &n)
{
m_collection->addNameToDict(n);
m_collection->removeNameFromDict(m_playlistName);
m_playlistName = n;
emit signalNameChanged(m_playlistName);
}
void Playlist::save()
{
if(m_fileName.isEmpty())
return saveAs();
QFile file(m_fileName);
if(!file.open(QIODevice::WriteOnly))
return KMessageBox::error(this, i18n("Could not save to file %1.", m_fileName));
QTextStream stream(&file);
const QStringList fileList = files();
for(const auto &file : fileList) {
stream << file << '\n';
}
file.close();
}
void Playlist::saveAs()
{
m_collection->removeFileFromDict(m_fileName);
m_fileName = MediaFiles::savePlaylistDialog(name(), this);
if(!m_fileName.isEmpty()) {
m_collection->addFileToDict(m_fileName);
// If there's no playlist name set, use the file name.
if(m_playlistName.isEmpty())
emit signalNameChanged(name());
save();
}
}
void Playlist::updateDeletedItem(PlaylistItem *item)
{
m_members.remove(item->file().absFilePath());
m_randomSequence.removeAll(item);
m_history.removeAll(item);
}
void Playlist::clearItem(PlaylistItem *item)
{
// Automatically updates internal structs via updateDeletedItem
delete item;
playlistItemsChanged();
}
void Playlist::clearItems(const PlaylistItemList &items)
{
for(auto &item : items) {
delete item;
}
playlistItemsChanged();
}
PlaylistItem *Playlist::playingItem() // static
{
return PlaylistItem::playingItems().isEmpty()
? nullptr
: PlaylistItem::playingItems().front();
}
QStringList Playlist::files() const
{
QStringList list;
for(QTreeWidgetItemIterator it(const_cast<Playlist *>(this)); *it; ++it)
list.append(static_cast<PlaylistItem *>(*it)->file().absFilePath());
return list;
}
PlaylistItemList Playlist::items()
{
return items(QTreeWidgetItemIterator::All);
}
PlaylistItemList Playlist::visibleItems()
{
return items(QTreeWidgetItemIterator::NotHidden);
}
PlaylistItemList Playlist::selectedItems()
{
return items(QTreeWidgetItemIterator::Selected | QTreeWidgetItemIterator::NotHidden);
}
PlaylistItem *Playlist::firstChild() const
{
return static_cast<PlaylistItem *>(topLevelItem(0));
}
void Playlist::updateLeftColumn()
{
int newLeftColumn = leftMostVisibleColumn();
if(m_leftColumn != newLeftColumn) {
updatePlaying();
m_leftColumn = newLeftColumn;
}
}
void Playlist::setItemsVisible(const QModelIndexList &indexes, bool visible) // static
{
m_visibleChanged = true;
for(QModelIndex index : indexes)
itemFromIndex(index)->setHidden(!visible);
}
void Playlist::setSearch(PlaylistSearch* s)
{
m_search = s;
if(!m_searchEnabled)
return;
for(int row = 0; row < topLevelItemCount(); ++row)
topLevelItem(row)->setHidden(true);
setItemsVisible(s->matchedItems(), true);
refillRandomList();
}
void Playlist::setSearchEnabled(bool enabled)
{
if(m_searchEnabled == enabled)
return;
m_searchEnabled = enabled;
if(enabled) {
for(int row = 0; row < topLevelItemCount(); ++row)
topLevelItem(row)->setHidden(true);
setItemsVisible(m_search->matchedItems(), true);
}
else {
const auto &playlistItems = items();
for(PlaylistItem* item : playlistItems)
item->setHidden(false);
}
refillRandomList();
}
// Mostly seems to be for DynamicPlaylist
// TODO: See if this can't all be eliminated by making 'is-playing' a predicate
// of the playlist item itself
void Playlist::synchronizePlayingItems(Playlist *playlist, bool setMaster)
{
if(!playlist || !playlist->playing())
return;
CollectionListItem *base = playingItem()->collectionItem();
for(QTreeWidgetItemIterator itemIt(playlist); *itemIt; ++itemIt) {
PlaylistItem *item = static_cast<PlaylistItem *>(*itemIt);
if(base == item->collectionItem()) {
item->setPlaying(true, setMaster);
return;
}
}
}
void Playlist::synchronizePlayingItems(const PlaylistList &sources, bool setMaster)
{
for(auto p : sources) {
synchronizePlayingItems(p, setMaster);
}
}
////////////////////////////////////////////////////////////////////////////////
// public slots
////////////////////////////////////////////////////////////////////////////////
void Playlist::copy()
{
const PlaylistItemList items = selectedItems();
QList<QUrl> urls;
for(const auto &item : items) {
urls << QUrl::fromLocalFile(item->file().absFilePath());
}
QMimeData *mimeData = new QMimeData;
mimeData->setUrls(urls);
QApplication::clipboard()->setMimeData(mimeData, QClipboard::Clipboard);
}
void Playlist::paste()
{
addFilesFromMimeData(
QApplication::clipboard()->mimeData(),
static_cast<PlaylistItem *>(currentItem()));
}
void Playlist::clear()
{
PlaylistItemList l = selectedItems();
if(l.isEmpty())
l = items();
clearItems(l);
}
void Playlist::slotRefresh()
{
PlaylistItemList itemList = selectedItems();
if(itemList.isEmpty())
itemList = visibleItems();
QApplication::setOverrideCursor(Qt::WaitCursor);
for(auto &item : itemList) {
item->refreshFromDisk();
if(!item->file().tag() || !item->file().fileInfo().exists()) {
qCDebug(JUK_LOG) << "Error while trying to refresh the tag. "
<< "This file has probably been removed.";
delete item->collectionItem();
}
processEvents();
}
QApplication::restoreOverrideCursor();
}
void Playlist::slotOpenItemDir()
{
PlaylistItemList itemList = selectedItems();
QList<QUrl> pathList;
for(auto &item : itemList) {
QUrl path = QUrl::fromLocalFile(item->file().fileInfo().absoluteDir().absolutePath());
if(!pathList.contains(path))
pathList.append(path);
}
if (pathList.length() > 4) {
if(KMessageBox::warningContinueCancel(
this,
i18np("You are about to open directory. Are you sure you want to continue?",
"You are about to open %1 directories. Are you sure you want to continue?",
pathList.length()),
i18n("Open Containing Folder")
) == KMessageBox::Cancel)
{
return;
}
}
QApplication::setOverrideCursor(Qt::WaitCursor);
for(auto &path : pathList) {
QDesktopServices::openUrl(path);
processEvents();
}
QApplication::restoreOverrideCursor();
}
void Playlist::slotRenameFile()
{
FileRenamer renamer;
PlaylistItemList items = selectedItems();
if(items.isEmpty())
return;
emit signalEnableDirWatch(false);
m_blockDataChanged = true;
renamer.rename(items);
m_blockDataChanged = false;
playlistItemsChanged();
emit signalEnableDirWatch(true);
}
void Playlist::slotBeginPlayback()
{
QTreeWidgetItemIterator visible(this, QTreeWidgetItemIterator::NotHidden);
PlaylistItem *item = static_cast<PlaylistItem *>(*visible);
if(item) {
refillRandomList();
playNext();
}
else {
action("stop")->trigger();
}
}
void Playlist::slotGuessTagInfo(TagGuesser::Type type)
{
QApplication::setOverrideCursor(Qt::WaitCursor);
const PlaylistItemList items = selectedItems();
setDynamicListsFrozen(true);
m_blockDataChanged = true;
for(auto &item : items) {
item->guessTagInfo(type);
processEvents();
}
// MusicBrainz queries automatically commit at this point. What would
// be nice is having a signal emitted when the last query is completed.
if(type == TagGuesser::FileName)
TagTransactionManager::instance()->commit();
m_blockDataChanged = false;
playlistItemsChanged();
setDynamicListsFrozen(false);
QApplication::restoreOverrideCursor();
}
void Playlist::slotReload()
{
QFileInfo fileInfo(m_fileName);
if(!fileInfo.exists() || !fileInfo.isFile() || !fileInfo.isReadable())
return;
clearItems(items());
loadFile(m_fileName, fileInfo);
}
void Playlist::refillRandomList()
{
if(action("disableRandomPlay")->isChecked()) {
m_randomSequence.clear();
return;
}
PlaylistItemList randomItems = visibleItems();
qCDebug(JUK_LOG) << "Refilling random items among" << randomItems.count() << "viable tracks";
// See https://www.pcg-random.org/posts/cpp-seeding-surprises.html
std::random_device rdev;
uint64_t rseed = (uint64_t(rdev()) << 32) | rdev();
std::linear_congruential_engine<
uint64_t, 6364136223846793005U, 1442695040888963407U, 0U
> knuth_lcg(rseed);
std::shuffle(randomItems.begin(), randomItems.end(), knuth_lcg);
if(action("albumRandomPlay")->isChecked()) {
std::sort(randomItems.begin(), randomItems.end(),
[](PlaylistItem *a, PlaylistItem *b) {
return a->file().tag()->album() < b->file().tag()->album();
});
// If there is an item playing from our playlist already, move its
// album to the front
const auto wasPlaying = playingItem();
if(wasPlaying && wasPlaying->playlist() == this) {
const auto playingAlbum = wasPlaying->file().tag()->album();
std::stable_partition(randomItems.begin(), randomItems.end(),
[playingAlbum](const PlaylistItem *item) {
return item->file().tag()->album() == playingAlbum;
});
}
}
std::swap(m_randomSequence, randomItems);
}
void Playlist::slotWeightDirty(int column)
{
if(column < 0) {
m_weightDirty.clear();
for(int i = 0; i < columnCount(); i++) {
if(!isColumnHidden(i))
m_weightDirty.append(i);
}
return;
}
if(!m_weightDirty.contains(column))
m_weightDirty.append(column);
}
void Playlist::slotShowPlaying()
{
if(!playingItem())
return;
Playlist *l = playingItem()->playlist();
l->clearSelection();
// Raise the playlist before selecting the items otherwise the tag editor
// will not update when it gets the selectionChanged() notification
// because it will think the user is choosing a different playlist but not
// selecting a different item.
m_collection->raise(l);
l->setCurrentItem(playingItem());
l->scrollToItem(playingItem(), QAbstractItemView::PositionAtCenter);
}
void Playlist::slotColumnResizeModeChanged()
{
if(manualResize()) {
header()->setSectionResizeMode(QHeaderView::Interactive);
setHorizontalScrollBarPolicy(Qt::ScrollBarAsNeeded);
} else {
header()->setSectionResizeMode(QHeaderView::Fixed);
setHorizontalScrollBarPolicy(Qt::ScrollBarAlwaysOff);
}
if(!manualResize())
slotUpdateColumnWidths();
SharedSettings::instance()->sync();
}
void Playlist::playlistItemsChanged()
{
if(m_blockDataChanged)
return;
PlaylistInterface::playlistItemsChanged();
}
////////////////////////////////////////////////////////////////////////////////
// protected members
////////////////////////////////////////////////////////////////////////////////
void Playlist::removeFromDisk(const PlaylistItemList &items)
{
if(!isVisible() || items.isEmpty()) {
return;
}
QStringList files;
for(const auto &item : items) {
files.append(item->file().absFilePath());
}
DeleteDialog dialog(this);
m_blockDataChanged = true;
if(dialog.confirmDeleteList(files)) {
bool shouldDelete = dialog.shouldDelete();
QStringList errorFiles;
for(const auto &item : items) {
if(playingItem() == item)
action("forward")->trigger();
QString removePath = item->file().absFilePath();
QUrl removeUrl = QUrl::fromLocalFile(removePath);
if((!shouldDelete && KIO::trash(removeUrl)->exec()) ||
(shouldDelete && QFile::remove(removePath)))
{
delete item->collectionItem();
}
else
errorFiles.append(item->file().absFilePath());
}
if(!errorFiles.isEmpty()) {
QString errorMsg = shouldDelete ?
i18n("Could not delete these files") :
i18n("Could not move these files to the Trash");
KMessageBox::errorList(this, errorMsg, errorFiles);
}
}
m_blockDataChanged = false;
playlistItemsChanged();
}
void Playlist::synchronizeItemsTo(const PlaylistItemList &itemList)
{
// direct call to ::items to avoid infinite loop, bug 402355
m_randomSequence.clear();
clearItems(Playlist::items());
createItems(itemList);
}
void Playlist::beginPlayingItem(PlaylistItem *itemToPlay)
{
if(itemToPlay) {
setPlaying(itemToPlay, true);
m_collection->requestPlaybackFor(itemToPlay->file());
}
else {
setPlaying(nullptr);
action("stop")->trigger();
}
}
void Playlist::dragEnterEvent(QDragEnterEvent *e)
{
if(e->mimeData()->hasUrls() && !e->mimeData()->urls().isEmpty()) {
setDropIndicatorShown(true);
e->acceptProposedAction();
}
else
e->ignore();
}
void Playlist::addFilesFromMimeData(const QMimeData *urls, PlaylistItem *after)
{
if(!urls->hasUrls()) {
return;
}
addFiles(QUrl::toStringList(urls->urls(), QUrl::PreferLocalFile), after);
}
bool Playlist::eventFilter(QObject *watched, QEvent *e)
{
if(watched == header()) {
switch(e->type()) {
case QEvent::MouseMove:
{
if((static_cast<QMouseEvent *>(e)->modifiers() & Qt::LeftButton) == Qt::LeftButton &&
!action<KToggleAction>("resizeColumnsManually")->isChecked())
{
m_columnWidthModeChanged = true;
action<KToggleAction>("resizeColumnsManually")->setChecked(true);
slotColumnResizeModeChanged();
}
break;
}
case QEvent::MouseButtonPress:
{
if(static_cast<QMouseEvent *>(e)->button() == Qt::RightButton)
m_headerMenu->popup(QCursor::pos());
break;
}
case QEvent::MouseButtonRelease:
{
if(m_columnWidthModeChanged) {
m_columnWidthModeChanged = false;
notifyUserColumnWidthModeChanged();
}
if(!manualResize() && m_widthsDirty)
QTimer::singleShot(0, this, &Playlist::slotUpdateColumnWidths);
break;
}
default:
break;
}
}
return QTreeWidget::eventFilter(watched, e);
}
void Playlist::keyPressEvent(QKeyEvent *event)
{
if(event->key() == Qt::Key_Up) {
if(const auto activeItem = currentItem()) {
QTreeWidgetItemIterator visible(this, QTreeWidgetItemIterator::NotHidden);
if(activeItem == *visible) {
emit signalMoveFocusAway();
event->accept();
}
}
}
else if(event->key() == Qt::Key_Return && !event->isAutoRepeat()) {
event->accept();
slotPlayCurrent();
return; // event completely handled already
}
QTreeWidget::keyPressEvent(event);
}
QStringList Playlist::mimeTypes() const
{
return QStringList("text/uri-list");
}
#if QT_VERSION < QT_VERSION_CHECK(6, 0, 0)
QMimeData* Playlist::mimeData(const QList<QTreeWidgetItem *> items) const
#else
QMimeData* Playlist::mimeData(const QList<QTreeWidgetItem *> &items) const
#endif
{
QList<QUrl> urls;
for(const auto &item : items) {
urls << QUrl::fromLocalFile(static_cast<const PlaylistItem*>(item)->file().absFilePath());
}
QMimeData *urlDrag = new QMimeData();
urlDrag->setUrls(urls);
return urlDrag;
}
bool Playlist::dropMimeData(QTreeWidgetItem *parent, int index, const QMimeData *data, Qt::DropAction action)
{
// TODO: Re-add DND
Q_UNUSED(parent);
Q_UNUSED(index);
Q_UNUSED(data);
Q_UNUSED(action);
return false;
}
void Playlist::dropEvent(QDropEvent *e)
{
QPoint vp = e->position().toPoint();
PlaylistItem *item = static_cast<PlaylistItem *>(itemAt(vp));
// When dropping on the toUpper half of an item, insert before this item.
// This is what the user expects, and also allows the insertion at
// top of the list
QRect rect = visualItemRect(item);
if(!item)
item = static_cast<PlaylistItem *>(topLevelItem(topLevelItemCount() - 1));
else if(vp.y() < rect.y() + rect.height() / 2)
item = static_cast<PlaylistItem *>(item->itemAbove());
m_blockDataChanged = true;
if(e->source() == this) {
// Since we're trying to arrange things manually, turn off sorting.
sortItems(columnCount() + 1, Qt::AscendingOrder);
const QList<QTreeWidgetItem *> items = QTreeWidget::selectedItems();
int insertIndex = item ? indexOfTopLevelItem(item) : 0;
// Move items from elsewhere in the playlist
for(auto &listViewItem : items) {
auto oldItem = takeTopLevelItem(indexOfTopLevelItem(listViewItem));
insertTopLevelItem(++insertIndex, oldItem);
}
}
else
addFilesFromMimeData(e->mimeData(), item);
m_blockDataChanged = false;
playlistItemsChanged();
emit signalPlaylistItemsDropped(this);
QTreeWidget::dropEvent(e);
}
void Playlist::showEvent(QShowEvent *e)
{
if(m_applySharedSettings) {
SharedSettings::instance()->apply(this);
m_applySharedSettings = false;
}
QTreeWidget::showEvent(e);
}