Debian Codegraph @

src/playlist.cpp

raw symbols SCIP
1 /*
2 Copyright (C) 2005-2019 Mario Stephan <[email protected]>
3
4 This library is free software; you can redistribute it and/or modify
5 it under the terms of the GNU Lesser General Public License as published
6 by the Free Software Foundation; either version 2.1 of the License, or
7 (at your option) any later version.
8
9 This program is distributed in the hope that it will be useful,
10 but WITHOUT ANY WARRANTY; without even the implied warranty of
11 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 GNU General Public License for more details.
13
14 You should have received a copy of the GNU Lesser General Public License
15 along with this program. If not, see <http://www.gnu.org/licenses/>.
16 */
17
18 #include "playlist.h"
19 #include "playlistitem.h"
20
21 #include <QMenu>
22 #include <Qt>
23 #include <qdebug.h>
24
25 #include <QtGui>
26 #include <QtXml>
27 #include <qprogressdialog.h>
28 #include <qscrollbar.h>
29
30 #include <QApplication>
31 #include <QHeaderView>
32 #include <QMessageBox>
33 #include <QPainter>
34 #include <qfile.h>
35
36 Playlist::Playlist(QWidget* parent)
37 : QTreeWidget(parent)
38 , m_alternateMax(0)
39 , m_marker(nullptr)
40 , m_NextTrackColor(QColor(200, 200, 255))
41 , m_CurrentTrackColor(QColor(255, 100, 100))
42 , nextPlaylistItem(nullptr)
43 , previousPlaylistItem(nullptr)
44 , newPlaylistItem(nullptr)
45 , currentPlaylistItem(nullptr)
46 , m_PlaylistMode(Playlist::Playlist_Single)
47 , showDropHighlighter(false)
48 , autoClearOn(false)
49 , m_isPlaying(false)
50 , m_isInternDrop(false)
51 , m_dragLocked(false)
52 , isChangeSignalEnabled(true)
53 {
54
55 setSortingEnabled(false);
56 setAcceptDrops(true);
57 setDragEnabled(true);
58 setAllColumnsShowFocus(false);
59 setDropIndicatorShown(true);
60 setAcceptDrops(true);
61 setDragEnabled(true);
62 setSelectionBehavior(QAbstractItemView::SelectRows);
63 setSelectionMode(QAbstractItemView::ExtendedSelection);
64 setDragDropMode(QAbstractItemView::InternalMove);
65 setAttribute(Qt::WA_MacShowFocusRect, false);
66 setUniformRowHeights(true);
67
68 QStringList headers;
69 headers << tr("Url") << tr("No") << tr("Played") << tr("Artist")
70 << tr("Title");
71 headers << tr("Album") << tr("Year") << tr("Genre") << tr("Track");
72 headers << tr("Length") << tr("Rate");
73
74 QTreeWidgetItem* headeritem = new QTreeWidgetItem(headers);
75 setHeaderItem(headeritem);
76 setHeaderLabels(headers);
77
78 // header()->setResizeMode(QHeaderView::Interactive);
79 header()->hideSection(PlaylistItem::Column_Url);
80
81 // prevent click event if doubleclicked
82 ignoreNextRelease = false;
83 timer = new QTimer(this);
84 connect(timer, SIGNAL(timeout()), this, SLOT(emitClicked()));
85
86 timerDragLock = new QTimer(this);
87 timerDragLock->setInterval(300);
88 connect(timerDragLock, SIGNAL(timeout()), this, SLOT(timeoutDragLock()));
89
90 connect(this, SIGNAL(itemClicked(QTreeWidgetItem*, int)), this,
91 SLOT(slotItemClicked(QTreeWidgetItem*, int)));
92 connect(this, SIGNAL(itemDoubleClicked(QTreeWidgetItem*, int)), this,
93 SLOT(slotItemDoubleClicked(QTreeWidgetItem*, int)));
94 connect(this,
95 SIGNAL(currentItemChanged(QTreeWidgetItem*, QTreeWidgetItem*)),
96 this, SLOT(slotItemChanged(QTreeWidgetItem*, QTreeWidgetItem*)));
97 }
98
99 Playlist::~Playlist()
100 {
101 // save width and sort settings
102 QSettings settings;
103 settings.setValue("playlist_" + objectName(), header()->saveState());
104 }
105
106 /** Add a song to the playlist */
107 void Playlist::addTrack(QUrl file, PlaylistItem* after)
108 {
109 Track* track = new Track(file);
110 addTrack(track, after);
111 }
112
113 void Playlist::addTrack(Track* track, PlaylistItem* after)
114 {
115 if (!track || !track->isValid())
116 return;
117 // qDebug() << Q_FUNC_INFO <<":"<<objectName()<<" url="<<track->url();
118 PlaylistItem* item = new PlaylistItem(this, after);
119 item->setTexts(track);
120 newPlaylistItem = item;
121 RatingWidget* rating = new RatingWidget(this);
122 rating->setRating(track->rate() * 0.1);
123 QObject::connect(rating, SIGNAL(RatingChanged(float)),
124 SLOT(onRatingChanged(float)));
125 setItemWidget(item, PlaylistItem::Column_Rate, rating);
126 }
127
128 /** Add a track and set it as current item */
129 void Playlist::addCurrentTrack(Track* track)
130 {
131 // Add if it comes from outsite only
132 bool fromOutsite = true;
133 PlaylistItem* currItem = (PlaylistItem*)currentItem();
134 if (currItem)
135 if (track->url() == currItem->track()->url())
136 fromOutsite = false;
137
138 if (fromOutsite)
139 addTrack(track, nullptr);
140 else
141 newPlaylistItem = currItem;
142
143 if (!m_isPlaying) {
144 // is not playing, direct into player and roll others
145 setCurrentPlaylistItem(newPlaylistItem);
146 } else {
147 // is playing, wait and add as next
148 setNextPlaylistItem(newPlaylistItem);
149 }
150
151 handleChanges();
152 }
153
154 void Playlist::addNextTrack(Track* track) { Q_UNUSED(track); }
155
156 void Playlist::appendSong(QString songFileName)
157 {
158 return addTrack(songFileName, (PlaylistItem*)this->lastChild());
159 }
160
161 void Playlist::appendSong(Track* track)
162 {
163 addTrack(track, lastChild());
164 checkCurrentItem();
165 }
166
167 void Playlist::appendList(QList<QUrl> list)
168 {
169 appendList(list, (PlaylistItem*)lastChild());
170 }
171
172 void Playlist::appendList(const QList<QUrl> urls, PlaylistItem* after)
173 {
174 qDebug() << Q_FUNC_INFO;
175
176 int droppedUrlCnt = urls.size();
177 for (int i = droppedUrlCnt - 1; i > -1; i--) {
178 QString localPath = urls[i].toLocalFile();
179 QFileInfo fileInfo(localPath);
180 if (fileInfo.isFile()) {
181 // file
182 addTrack(urls[i], after);
183 } else if (fileInfo.isDir()) {
184 // directory
185 if (fileInfo.isDir()) {
186 // directory
187 QStringList filters;
188 filters << "*.mp3"
189 << "*.ogg"
190 << "*.wav";
191
192 QDirIterator it(localPath, filters,
193 QDir::Files | QDir::NoSymLinks | QDir::NoDotAndDotDot,
194 QDirIterator::Subdirectories);
195 while (it.hasNext()) {
196 it.next();
197 addTrack("file:///" + it.filePath(), after);
198 }
199 }
200 } else {
201 // none
202 }
203 }
204 checkCurrentItem();
205 }
206
207 void Playlist::changeTracks(const QList<Track*> tracks)
208 {
209 clear();
210 appendTracks(tracks);
211 }
212
213 void Playlist::appendTracks(const QList<Track*> tracks)
214 {
215 // a week attempt to speed up the setItemWidget time issue
216 setUpdatesEnabled(false);
217 bool doSort = isSortingEnabled();
218 setSortingEnabled(false);
219 hide();
220
221 appendTracks(tracks, (PlaylistItem*)lastChild());
222
223 setSortingEnabled(doSort);
224 setUpdatesEnabled(true);
225 show();
226 }
227
228 void Playlist::appendTracks(QList<Track*> tracks, PlaylistItem* after)
229 {
230 foreach (Track* track, tracks) {
231 if (track != nullptr) {
232 addTrack(new Track(*track), after);
233 after = this->newTrack();
234 }
235 }
236 checkCurrentItem();
237 }
238
239 void Playlist::setPlaylistMode(Mode newMode)
240 {
241 m_PlaylistMode = newMode;
242
243 double percent = this->size().width() / 100.0;
244
245 switch (m_PlaylistMode) {
246 case Playlist::Tracklist:
247 header()->hideSection(PlaylistItem::Column_No);
248 header()->showSection(PlaylistItem::Column_Played);
249 header()->showSection(PlaylistItem::Column_Year);
250 header()->showSection(PlaylistItem::Column_Genre);
251 header()->showSection(PlaylistItem::Column_Tracknumber);
252 header()->showSection(PlaylistItem::Column_Album);
253 header()->showSection(PlaylistItem::Column_Rate);
254 header()->resizeSection(PlaylistItem::Column_Artist, 22 * percent);
255 header()->resizeSection(PlaylistItem::Column_Title, 22 * percent);
256 header()->resizeSection(PlaylistItem::Column_Album, 20 * percent);
257 header()->resizeSection(PlaylistItem::Column_Length, 7 * percent);
258 header()->resizeSection(PlaylistItem::Column_Genre, 10 * percent);
259 header()->resizeSection(PlaylistItem::Column_Year, 8 * percent);
260 header()->resizeSection(PlaylistItem::Column_Tracknumber, 5 * percent);
261 header()->resizeSection(PlaylistItem::Column_Played, 5 * percent);
262 header()->resizeSection(PlaylistItem::Column_Rate, 75);
263 setSortingEnabled(true);
264 sortByColumn(PlaylistItem::Column_Played, Qt::DescendingOrder);
265 m_CurrentTrackColor = Qt::white;
266 m_NextTrackColor = Qt::white;
267 break;
268 default:
269 header()->showSection(PlaylistItem::Column_No);
270 header()->hideSection(PlaylistItem::Column_Played);
271 header()->hideSection(PlaylistItem::Column_Year);
272 header()->hideSection(PlaylistItem::Column_Genre);
273 header()->hideSection(PlaylistItem::Column_Tracknumber);
274 header()->hideSection(PlaylistItem::Column_Album);
275 header()->hideSection(PlaylistItem::Column_Rate);
276 header()->resizeSection(PlaylistItem::Column_No, 6 * percent);
277 header()->resizeSection(PlaylistItem::Column_Artist, 40 * percent);
278 header()->resizeSection(PlaylistItem::Column_Title, 40 * percent);
279 header()->resizeSection(PlaylistItem::Column_Length, 10 * percent);
280 header()->resizeSection(PlaylistItem::Column_Rate, 0);
281 setSortingEnabled(false);
282 m_CurrentTrackColor = QColor(255, 100, 100);
283 m_NextTrackColor = QColor(200, 200, 255);
284 }
285
286 QSettings settings;
287 if (settings.contains("playlist_" + objectName()))
288 header()->restoreState(
289 settings.value("playlist_" + objectName()).toByteArray());
290
291 handleChanges();
292 }
293
294 void Playlist::checkCurrentItem()
295 {
296 if (autoClearOn && newPlaylistItem == firstChild())
297 setCurrentPlaylistItem(newPlaylistItem);
298 if (!currentPlaylistItem)
299 setCurrentPlaylistItem(firstChild());
300
301 handleChanges();
302 }
303
304 /** handle changes after remove or adding tracks to play list */
305 void Playlist::handleChanges()
306 {
307 if (m_PlaylistMode == Playlist::Tracklist)
308 return;
309
310 if (itemBelow(currentPlaylistItem)) {
311 nextPlaylistItem = (PlaylistItem*)itemBelow(currentPlaylistItem);
312 } else {
313 nextPlaylistItem = nullptr;
314 }
315
316 updatePlaylistItems();
317
318 Q_EMIT countChanged(countTrack());
319 Q_EMIT countChanged(allTracks());
320
321 fillNoColumn();
322
323 isChangeSignalEnabled = true;
324 }
325
326 void Playlist::setCurrentPlaylistItem(PlaylistItem* item)
327 {
328 currentPlaylistItem = item;
329
330 if (autoClearOn) {
331 // Only for the mode, where current item is always on top of the list
332 if (currentPlaylistItem != firstChild()) {
333 // Move nextPlaylistItem at first row
334 QTreeWidgetItem* child = takeTopLevelItem(indexOfTopLevelItem(item));
335 this->insertTopLevelItem(0, child);
336 currentPlaylistItem = (PlaylistItem*)child;
337 }
338 }
339
340 if (currentPlaylistItem)
341 Q_EMIT currentTrackChanged(currentPlaylistItem->track());
342 else
343 Q_EMIT currentTrackChanged(nullptr);
344 }
345
346 void Playlist::setNextPlaylistItem(PlaylistItem* item)
347 {
348 if (autoClearOn) {
349 // Move nextPlaylistItem to second row
350 // Only for the mode, where current item is always on top of the list
351 QTreeWidgetItem* child = takeTopLevelItem(indexOfTopLevelItem(item));
352 this->insertTopLevelItem(1, child);
353 handleChanges();
354 }
355 }
356
357 void Playlist::updatePlaylistItems()
358 {
359 // Set all items to normal
360 for (PlaylistItem* item = firstChild(); item; item = item->nextSibling()) {
361 if (item) {
362 item->setFlags(Qt::ItemIsSelectable | Qt::ItemIsDragEnabled | Qt::ItemIsEnabled);
363 item->setForeColor(Qt::white);
364 }
365 }
366
367 if (currentPlaylistItem) {
368
369 if (m_isPlaying)
370 currentPlaylistItem->setFlags(Qt::ItemIsEnabled);
371 else
372 currentPlaylistItem->setFlags(Qt::ItemIsSelectable | Qt::ItemIsDragEnabled | Qt::ItemIsEnabled);
373
374 if (!m_isCurrentList)
375 currentPlaylistItem->setForeColor(m_CurrentTrackColor.darker(130));
376 else
377 currentPlaylistItem->setForeColor(m_CurrentTrackColor);
378 }
379
380 if (nextPlaylistItem) {
381
382 nextPlaylistItem->setFlags(Qt::ItemIsSelectable | Qt::ItemIsDragEnabled | Qt::ItemIsEnabled);
383
384 if (!m_isCurrentList)
385 nextPlaylistItem->setForeColor(m_NextTrackColor.darker(130));
386 else
387 nextPlaylistItem->setForeColor(m_NextTrackColor);
388 }
389 }
390
391 QList<Track*> Playlist::allTracks()
392 {
393 QList<Track*> trackList;
394 for (int i = 0; i < this->topLevelItemCount(); i++) {
395 if (PlaylistItem* item = dynamic_cast<PlaylistItem*>(this->topLevelItem(i))) {
396 if (item->track()->isValid())
397 trackList.append(item->track());
398 }
399 }
400 return trackList;
401 }
402
403 void Playlist::removePlaylistItem(PlaylistItem* item)
404 {
405 if (item) {
406 qDebug() << Q_FUNC_INFO << ":" << item->track()->url();
407
408 // unset if not available any more
409 if (item == currentPlaylistItem)
410 setCurrentPlaylistItem(nullptr);
411 if (item == nextPlaylistItem)
412 setNextPlaylistItem(nullptr);
413
414 newPlaylistItem = nullptr;
415
416 takeTopLevelItem(indexOfTopLevelItem(item));
417 delete item;
418 }
419 }
420
421 void Playlist::skipForward()
422 {
423 qDebug() << Q_FUNC_INFO << ":" << objectName();
424
425 // remove previous item at last due to keep playing
426 if (autoClearOn) {
427 previousPlaylistItem = currentPlaylistItem;
428 setCurrentPlaylistItem((PlaylistItem*)itemBelow(currentPlaylistItem));
429 removePlaylistItem(previousPlaylistItem);
430 } else {
431 if (itemBelow(currentPlaylistItem)) {
432 setCurrentPlaylistItem((PlaylistItem*)itemBelow(currentPlaylistItem));
433 }
434 }
435 handleChanges();
436 }
437
438 void Playlist::skipRewind()
439 {
440 if (itemAbove(currentPlaylistItem)) {
441 setCurrentPlaylistItem((PlaylistItem*)itemAbove(currentPlaylistItem));
442 }
443 handleChanges();
444 }
445
446 QString Playlist::defaultPlaylistPath()
447 {
448 #if QT_VERSION >= 0x050000
449 QString pathName = QStandardPaths::standardLocations(QStandardPaths::DataLocation).at(0);
450 #else
451 QString pathName = QDesktopServices::storageLocation(QDesktopServices::DataLocation);
452 #endif
453 QDir path(pathName);
454
455 if (!path.exists())
456 path.mkpath(pathName);
457
458 return path.absolutePath() + "/" + this->objectName() + ".xspf";
459 }
460
461 // Export content as a xspf playlist
462 void Playlist::saveXML(const QString& path) const
463 {
464 qDebug() << Q_FUNC_INFO << "BEGIN ";
465 QFile file(path);
466
467 if (!file.open(QFile::WriteOnly))
468 return;
469
470 QDomDocument newdoc;
471 QDomElement playlistElem = newdoc.createElement("playlist");
472 playlistElem.setAttribute("version", "1");
473 playlistElem.setAttribute("xmlns", "http://xspf.org/ns/0/");
474 newdoc.appendChild(playlistElem);
475
476 QDomElement elem = newdoc.createElement("creator");
477 QDomText t = newdoc.createTextNode("Knowthelist");
478 elem.appendChild(t);
479 playlistElem.appendChild(elem);
480
481 QDomElement listElem = newdoc.createElement("trackList");
482
483 for (PlaylistItem* item = firstChild(); item; item = item->nextSibling()) {
484 if (item) {
485 QDomElement trackElem = newdoc.createElement("track");
486
487 QDomElement extElem = newdoc.createElement("extension");
488
489 if (currentPlaylistItem && item == currentPlaylistItem) {
490 extElem.setAttribute("current", "1");
491 }
492 if (item == nextTrack()) {
493 extElem.setAttribute("next", "1");
494 }
495 if (item->track()->flags().testFlag(Track::isAutoDjSelection)) {
496 extElem.setAttribute("isAutoDjSelection", "1");
497 }
498
499 QStringList tag = item->track()->tagList();
500
501 for (int x = 0; x < tag.count(); ++x) {
502 if (x == 4 || x == 5) {
503 extElem.setAttribute(Track::tagNameList.at(x), tag.at(x));
504 } else {
505 QDomElement elem = newdoc.createElement(Track::tagNameList.at(x));
506 QDomText t = newdoc.createTextNode(tag.at(x));
507 elem.appendChild(t);
508 trackElem.appendChild(elem);
509 }
510 }
511
512 trackElem.appendChild(extElem);
513 listElem.appendChild(trackElem);
514 }
515 }
516
517 playlistElem.appendChild(listElem);
518
519 QTextStream stream(&file);
520 stream.setCodec("UTF-8");
521 stream << "<?xml version=\"1.0\" encoding=\"utf8\"?>\n";
522 stream << newdoc.toString();
523 file.close();
524 qDebug() << Q_FUNC_INFO << "END ";
525 }
526
527 void Playlist::loadXML(const QString& path)
528 {
529 QFile file(path);
530
531 if (file.open(QFile::ReadOnly)) {
532 QTextStream stream(&file);
533
534 stream.setCodec(QTextCodec::codecForName("utf8"));
535 QDomDocument d;
536 if (!d.setContent(stream.readAll())) {
537 qDebug() << "Could not load XML\n";
538 return;
539 }
540
541 QDomNode n = d.namedItem("playlist").namedItem("trackList").firstChild();
542
543 const QString TRACK(
544 "track"); // so we don't construct the QStrings all the time
545 const QString URL("url");
546 const QString CURRENT("current");
547 const QString NEXT("next");
548
549 while (!n.isNull()) {
550 if (n.nodeName() == TRACK) {
551 const QDomElement e = n.toElement();
552 if (e.isNull()) {
553 qDebug() << "Element '" << n.nodeName() << "' is null, skipping.";
554 continue;
555 }
556
557 // qDebug() << "Add from xml url='" << e.attribute( URL );
558 Track* track = new Track();
559 track->setUrl(QUrl::fromLocalFile(
560 e.namedItem("location").firstChild().nodeValue()));
561 track->setArtist(e.namedItem("creator").firstChild().nodeValue());
562 track->setTitle(e.namedItem("title").firstChild().nodeValue());
563 track->setAlbum(e.namedItem("album").firstChild().nodeValue());
564 track->setGenre(
565 e.namedItem("extension").toElement().attribute("genre"));
566 track->setYear(e.namedItem("extension").toElement().attribute("year"));
567 track->setLength(e.namedItem("duration").firstChild().nodeValue());
568 track->setCounter("0");
569 if (e.namedItem("extension")
570 .toElement()
571 .attribute("isAutoDjSelection")
572 == "1")
573 track->setFlags(track->flags() | Track::isAutoDjSelection);
574
575 appendSong(track);
576
577 if (e.namedItem("extension").toElement().attribute(CURRENT) == "1")
578 this->setCurrentPlaylistItem(newPlaylistItem);
579 if (e.namedItem("extension").toElement().attribute(NEXT) == "1")
580 this->setNextPlaylistItem(newPlaylistItem);
581 }
582 n = n.nextSibling();
583 }
584 }
585 file.close();
586
587 qDebug() << "End " << Q_FUNC_INFO;
588 }
589
590 void Playlist::removeSelectedItems()
591 {
592 if (m_PlaylistMode == Playlist::Tracklist)
593 return;
594
595 QListIterator<QTreeWidgetItem*> it(selectedItems());
596
597 while (it.hasNext()) {
598 PlaylistItem* item = dynamic_cast<PlaylistItem*>(it.next());
599 if (item != currentPlaylistItem || (!m_isPlaying))
600 removePlaylistItem(item);
601 }
602
603 if (this->topLevelItemCount() > 1 || !this->isPlaying())
604 checkCurrentItem();
605 }
606
607 void Playlist::fillNoColumn()
608 {
609
610 int no = 0;
611 int i = 0;
612
613 for (int ii = 0; ii < this->topLevelItemCount(); ii++) {
614 QTreeWidgetItem* item = this->topLevelItem(ii);
615
616 // if this item number is less then then alternateMax increment 2
617 // (alternate) else 1 alternateMax is equal to the count of then other
618 // player+1
619 i++;
620
621 // qDebug() << this->name() << ": markNextTrack(): " << markNextTrack();
622
623 if (m_PlaylistMode != Playlist::Playlist_Multi)
624 no = i;
625 else if (i > m_alternateMax)
626 no = i + m_alternateMax;
627 else {
628 if (m_isCurrentList)
629 no = i * 2 - 1;
630 else
631 no = i * 2;
632 }
633
634 // qDebug() << this->name() << ": m_alternateMax: " << m_alternateMax << "
635 // i: " << i << " no: " << no;
636 item->setText(PlaylistItem::Column_No, QString::number(no));
637 }
638 }
639
640 void Playlist::onRatingChanged(float rate)
641 {
642 if (RatingWidget* rateWidget = dynamic_cast<RatingWidget*>(QObject::sender())) {
643
644 QModelIndex modidx = indexAt(QPoint(0, rateWidget->pos().y()));
645 (PlaylistItem*)this->itemFromIndex(modidx);
646 if (PlaylistItem* item = (PlaylistItem*)this->itemFromIndex(modidx)) {
647 Track* track = item->track();
648 if (track) {
649 track->setRate(rate * 10);
650 qDebug() << Q_FUNC_INFO << item->track()->url();
651 emit trackPropertyChanged(track);
652 }
653 }
654 }
655 }
656
657 void Playlist::slotItemChanged(QTreeWidgetItem* current,
658 QTreeWidgetItem* previous)
659 {
660 Q_UNUSED(previous);
661 if ((selectedItems().count() > 1) || (selectedItems().count() == 0))
662 return;
663
664 PlaylistItem* item = static_cast<PlaylistItem*>(current);
665
666 if (item && isChangeSignalEnabled)
667 emit trackSelected(item->track());
668 }
669
670 void Playlist::slotItemDoubleClicked(QTreeWidgetItem* sender, int column)
671 {
672 Q_UNUSED(column);
673 PlaylistItem* item = static_cast<PlaylistItem*>(sender);
674
675 if (item)
676 emit trackDoubleClicked(item->track());
677 }
678
679 void Playlist::slotItemClicked(QTreeWidgetItem* after, int col)
680 {
681 isChangeSignalEnabled = true;
682
683 PlaylistItem* item = static_cast<PlaylistItem*>(after);
684
685 if (item)
686 emit trackSelected(item->track());
687 }
688
689 // avoid multiple drops on quick drags
690 void Playlist::timeoutDragLock()
691 {
692 m_dragLocked = false;
693 timerDragLock->stop();
694 }
695
696 // prevent click event if doubleclicked
697 void Playlist::emitClicked()
698 {
699 emit itemClicked(currentItem(), currentColumn());
700 timer->stop();
701 }
702
703 void Playlist::mouseReleaseEvent(QMouseEvent* event)
704 {
705 if (!ignoreNextRelease) {
706 timer->start(QApplication::doubleClickInterval());
707 blockSignals(true);
708 QTreeWidget::mouseReleaseEvent(event);
709 blockSignals(false);
710 }
711 ignoreNextRelease = false;
712 }
713
714 void Playlist::mouseDoubleClickEvent(QMouseEvent* event)
715 {
716 ignoreNextRelease = true;
717 timer->stop();
718 QTreeWidget::mouseDoubleClickEvent(event);
719 }
720
721 void Playlist::mousePressEvent(QMouseEvent* e)
722 {
723 if (e->button() == Qt::LeftButton) {
724 startPos = e->pos();
725 }
726 QTreeWidget::mousePressEvent(e);
727
728 if (e->button() == Qt::RightButton)
729 showContextMenu(dynamic_cast<PlaylistItem*>(currentItem()),
730 currentColumn());
731 }
732
733 void Playlist::mouseMoveEvent(QMouseEvent* event)
734 {
735 if (event->buttons() & Qt::LeftButton) {
736 int distance = (event->pos() - startPos).manhattanLength();
737 if (distance >= QApplication::startDragDistance() && !m_dragLocked) {
738 performDrag();
739 }
740 }
741 }
742
743 void Playlist::performDrag()
744 {
745 m_dragLocked = true;
746 QByteArray itemData;
747 QDataStream dataStream(&itemData, QIODevice::WriteOnly);
748 QVector<QStringList> tags;
749 QPixmap cover;
750 int i = 0;
751
752 // iterate selected items
753 QListIterator<QTreeWidgetItem*> it(selectedItems());
754 while (it.hasNext()) {
755 PlaylistItem* item = dynamic_cast<PlaylistItem*>(it.next());
756 if ((item != currentPlaylistItem || (!m_isPlaying)) && item->track()->isValid()) {
757 qDebug() << Q_FUNC_INFO << ": send Data:" << item->track()->url();
758 QStringList tag = item->track()->tagList();
759 tags << tag;
760 if (i == 0) {
761 cover = QPixmap::fromImage(item->track()->coverImage());
762 emit trackSelected(item->track());
763 }
764 i++;
765 }
766 }
767
768 dataStream << tags;
769
770 QMimeData* mimeData = new QMimeData;
771 mimeData->setData("text/playlistitem", itemData);
772
773 QDrag* drag = new QDrag(this);
774 drag->setMimeData(mimeData);
775
776 if (!cover.isNull())
777 drag->setPixmap(cover.scaled(50, 50));
778
779 timerDragLock->start();
780
781 Qt::DropAction dropAction = (m_PlaylistMode != Playlist::Tracklist) ? Qt::MoveAction : Qt::CopyAction;
782
783 if (drag->exec(dropAction) == Qt::MoveAction) {
784 // ToDo: before remove, give over current or next Track to newTrack, if
785 // within the same playlist
786 isChangeSignalEnabled = false;
787 removeSelectedItems();
788 }
789 }
790
791 void Playlist::dragEnterEvent(QDragEnterEvent* event)
792 {
793 if (m_PlaylistMode == Playlist::Tracklist) {
794 event->ignore();
795 return;
796 }
797 if (event->mimeData()->hasFormat("text/uri-list") || event->mimeData()->hasFormat("text/playlistitem")) {
798 event->acceptProposedAction();
799 }
800 }
801
802 void Playlist::dropEvent(QDropEvent* event)
803 {
804 m_isInternDrop = false;
805
806 if (event->mimeData()->hasUrls()) {
807 QList<QUrl> urlList = event->mimeData()->urls(); // returns list of QUrls
808 event->accept();
809 appendList(urlList, m_marker);
810 } else if (event->mimeData()->hasFormat("text/playlistitem")) {
811
812 // decode playlistitem
813 QByteArray itemData = event->mimeData()->data("text/playlistitem");
814 QDataStream stream(&itemData, QIODevice::ReadOnly);
815 QVector<QStringList> tags;
816
817 stream >> tags;
818
819 // add Tracks to this playlist
820 foreach (QStringList tag, tags) {
821 qDebug() << Q_FUNC_INFO << ": is playlistitem; tags:" << tags;
822 addTrack(new Track(tag), m_marker);
823 m_marker = this->newTrack();
824 }
825 checkCurrentItem();
826
827 event->acceptProposedAction();
828
829 if (event->source()->objectName() == this->objectName())
830 m_isInternDrop = true;
831 } else
832 event->ignore();
833
834 showDropHighlighter = false;
835 viewport()->repaint();
836 }
837
838 void Playlist::dragMoveEvent(QDragMoveEvent* event)
839 {
840 dropSite = event->answerRect();
841 showDropHighlighter = true;
842 event->acceptProposedAction();
843 viewport()->repaint();
844 }
845
846 void Playlist::dragLeaveEvent(QDragLeaveEvent* event)
847 {
848 Q_UNUSED(event);
849 showDropHighlighter = false;
850 viewport()->repaint();
851 }
852
853 void Playlist::paintEvent(QPaintEvent* event)
854 {
855 QTreeView::paintEvent(event);
856 if (showDropHighlighter) {
857 QPainter painter(viewport());
858 int x, y, w, h;
859 dropSite.getRect(&x, &y, &w, &h);
860 QPoint point(x, y);
861 QModelIndex modidx = indexAt(point);
862 int addHeight = 0;
863
864 // if is playing mark as next only
865 if (isPlaying() && modidx.row() == 0) {
866 modidx = model()->index(1, 1);
867 }
868
869 // Draw drop line after last item
870 if (!modidx.isValid()) {
871 modidx = model()->index(model()->rowCount() - 1, 1, modidx);
872 addHeight = 1;
873 }
874
875 // bookmark item in case of a drop
876 m_marker = (PlaylistItem*)this->itemFromIndex(modidx);
877 if (addHeight == 0) {
878 if (itemAbove(m_marker)) {
879 // one item above
880 m_marker = (PlaylistItem*)itemAbove(m_marker);
881 } else {
882 // add new item at first row
883 m_marker = nullptr;
884 }
885 }
886
887 // qDebug() << Q_FUNC_INFO <<": modidx:"<<modidx;
888
889 // draw the drop point hightlighter
890 QRect arect = visualRect(modidx);
891 int b = arect.y() + arect.height() * addHeight;
892 QBrush brush(Qt::red, Qt::SolidPattern);
893 QPen pen;
894 pen.setWidth(2);
895 pen.setBrush(brush);
896 painter.setPen(pen);
897 painter.drawLine(10, b, width() - 10, b);
898 painter.drawEllipse(5, b - 2, 5, 5);
899 painter.drawEllipse(width() - 15, b - 2, 5, 5);
900 }
901 event->accept();
902 }
903
904 void Playlist::keyPressEvent(QKeyEvent* e)
905 {
906 qDebug() << Q_FUNC_INFO << " " << e->key() << "del=" << Qt::Key_Delete;
907
908 PlaylistItem* item = static_cast<PlaylistItem*>(currentItem());
909
910 if ((e->key() == Qt::Key_Delete) || (e->key() == 0x1000003)) // also for Mac
911 {
912 this->removeSelectedItems();
913 } else if (e->key() == Qt::Key_L) {
914 setCurrentPlaylistItem(item);
915 handleChanges();
916 } else if (e->key() == Qt::Key_N) {
917 setNextPlaylistItem(item);
918 } else if (e->key() == Qt::Key_1)
919 Q_EMIT wantLoad(item->track(), "Left");
920 else if (e->key() == Qt::Key_2)
921 Q_EMIT wantLoad(item->track(), "Right");
922 else if (e->key() == Qt::Key_P)
923 Q_EMIT trackDoubleClicked(item->track());
924 else if (e->key() == Qt::CTRL + Qt::Key_S)
925 Q_EMIT wantSearch(QString::null);
926 else
927 QTreeWidget::keyPressEvent(e);
928 }
929
930 // needed for showContextMenu actions
931 void Playlist::dummySlot() {}
932
933 void Playlist::showContextMenu(PlaylistItem* item, int col)
934 {
935 enum Id { LOAD,
936 LOAD_NEXT,
937 VIEW,
938 EDIT,
939 REMOVE,
940 LISTEN,
941 FILTER,
942 LOAD1,
943 LOAD2 };
944
945 if (item == nullptr)
946 return;
947
948 const bool isCurrentPlaylistItem = (item == currentPlaylistItem);
949
950 QMenu popup(this);
951
952 popup.setTitle(item->track()->prettyTitle(50));
953 if (m_PlaylistMode == Playlist::Tracklist) {
954 popup.addAction(style()->standardPixmap(QStyle::SP_MediaPlay),
955 tr("Add to PlayList&1"), this, SLOT(dummySlot()),
956 Qt::Key_1); //, LOAD1
957 popup.addAction(style()->standardPixmap(QStyle::SP_MediaPlay),
958 tr("Add to PlayList&2"), this, SLOT(dummySlot()),
959 Qt::Key_2); //, LOAD2
960 }
961 if (!m_isPlaying && !isCurrentPlaylistItem && m_PlaylistMode != Playlist::Tracklist)
962 popup.addAction(style()->standardPixmap(QStyle::SP_MediaPlay), tr("&Load"),
963 this, SLOT(dummySlot()), Qt::Key_L);
964 if (!isCurrentPlaylistItem && m_PlaylistMode != Playlist::Tracklist)
965 popup.addAction(style()->standardPixmap(QStyle::SP_ArrowRight),
966 tr("Load as &Next"), this, SLOT(dummySlot()), Qt::Key_N);
967 popup.addSeparator();
968 popup.addAction(style()->standardPixmap(QStyle::SP_DriveCDIcon),
969 tr("&Prelisten Track"), this, SLOT(dummySlot()), Qt::Key_P);
970 popup.addSeparator();
971 popup.addAction(style()->standardPixmap(QStyle::SP_ArrowRight),
972 tr("&Search for: '%1'").arg(item->text(col)), this,
973 SLOT(dummySlot()), Qt::Key_S);
974 popup.addSeparator();
975 if (!isCurrentPlaylistItem && m_PlaylistMode != Playlist::Tracklist)
976 popup.addAction(style()->standardPixmap(QStyle::SP_TrashIcon),
977 tr("&Remove Selected"), this, SLOT(removeSelectedItems()),
978 Qt::Key_Delete);
979 popup.addSeparator();
980 popup.addAction(style()->standardPixmap(QStyle::SP_DirOpenIcon),
981 tr("&Open File Location"), this, SLOT(dummySlot()),
982 Qt::Key_O);
983 popup.addAction(style()->standardPixmap(QStyle::SP_MessageBoxInformation),
984 tr("&View Tag Information"), this, SLOT(dummySlot()),
985 Qt::Key_V);
986
987 QAction* a = popup.exec(QCursor::pos());
988 if (!a)
989 return;
990 QKeySequence shortcut = a->shortcut();
991
992 if (shortcut == QKeySequence(Qt::Key_L)) {
993 setCurrentPlaylistItem(item);
994 handleChanges();
995 } else if (shortcut == QKeySequence(Qt::Key_N)) {
996 setNextPlaylistItem(item);
997 } else if (shortcut == QKeySequence(Qt::Key_1)) {
998 Q_EMIT wantLoad(item->track(), "Left");
999 } else if (shortcut == QKeySequence(Qt::Key_2)) {
1000 Q_EMIT wantLoad(item->track(), "Right");
1001 } else if (shortcut == QKeySequence(Qt::Key_P)) {
1002 Q_EMIT itemDoubleClicked(item, col);
1003 } else if (shortcut == QKeySequence(Qt::Key_S)) {
1004 Q_EMIT wantSearch(item->text(col));
1005 } else if (shortcut == QKeySequence(Qt::Key_V)) {
1006 showTrackInfo(item->track());
1007 } else if (shortcut == QKeySequence(Qt::Key_O)) {
1008 if (item->track())
1009 QDesktopServices::openUrl(
1010 QUrl(QString("file://%1").arg(item->track()->dirPath())));
1011 } else if (shortcut == QKeySequence(Qt::Key_Delete)) {
1012 item = nullptr;
1013 }
1014 }
1015
1016 void Playlist::showTrackInfo(Track* mb)
1017 {
1018 const QString body = "<tr><td>%1</td><td>%2</td></tr>";
1019
1020 QString str = "<html><body><table STYLE=\"border-collapse: collapse\"> "
1021 "width=\"100%\" border=\"1\">";
1022 str += body.arg(tr("Title"), mb->title());
1023 str += body.arg(tr("Artist"), mb->artist());
1024 str += body.arg(tr("Album"), mb->album());
1025 str += body.arg(tr("Genre"), mb->genre());
1026 str += body.arg(tr("Year"), mb->year());
1027 str += body.arg(tr("Location"), mb->url().toString());
1028 str += "</table></body></html>";
1029
1030 QMessageBox::information(nullptr, tr("Meta Information"), str);
1031 }