xref: /OK3568_Linux_fs/app/forlinx/flapp/src/plugins/imxwayland/musicplayer/musicplayer.cpp (revision 4882a59341e53eb6f0b4789bf948001014eff981)
1 /****************************************************************************
2 **
3 ** Copyright (C) 2015 The Qt Company Ltd.
4 ** Contact: http://www.qt.io/licensing/
5 **
6 ** This file is part of the examples of the Qt Toolkit.
7 **
8 ** $QT_BEGIN_LICENSE:BSD$
9 ** You may use this file under the terms of the BSD license as follows:
10 **
11 ** "Redistribution and use in source and binary forms, with or without
12 ** modification, are permitted provided that the following conditions are
13 ** met:
14 **   * Redistributions of source code must retain the above copyright
15 **     notice, this list of conditions and the following disclaimer.
16 **   * Redistributions in binary form must reproduce the above copyright
17 **     notice, this list of conditions and the following disclaimer in
18 **     the documentation and/or other materials provided with the
19 **     distribution.
20 **   * Neither the name of The Qt Company Ltd nor the names of its
21 **     contributors may be used to endorse or promote products derived
22 **     from this software without specific prior written permission.
23 **
24 **
25 ** THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
26 ** "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
27 ** LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
28 ** A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
29 ** OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
30 ** SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
31 ** LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
32 ** DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
33 ** THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
34 ** (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
35 ** OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE."
36 **
37 ** $QT_END_LICENSE$
38 **
39 ****************************************************************************/
40 
41 #include "musicplayer.h"
42 #include "volumebutton.h"
43 #include <QDebug>
44 #include <QtWidgets>
45 #include <QApplication>
46 #include <QSlider>
47 #include <QPainter>
48 
49 
MusicPlayer(QWidget * parent)50 MusicPlayer::MusicPlayer(QWidget *parent) : IWidget(parent)
51 {
52     createWidgets();
53     createShortcuts();
54 
55     connect(&mediaPlayer, &QMediaPlayer::positionChanged, this, &MusicPlayer::updatePosition);
56     connect(&mediaPlayer, &QMediaPlayer::durationChanged, this, &MusicPlayer::updateDuration);
57     connect(&mediaPlayer, &QMediaObject::metaDataAvailableChanged, this, &MusicPlayer::updateInfo);
58 
59     typedef void(QMediaPlayer::*ErrorSignal)(QMediaPlayer::Error);
60     connect(&mediaPlayer, static_cast<ErrorSignal>(&QMediaPlayer::error),
61             this, &MusicPlayer::handleError);
62     connect(&mediaPlayer, &QMediaPlayer::stateChanged,
63             this, &MusicPlayer::updateState);
64 
65     setAcceptDrops(true);
66 }
67 
supportedMimeTypes()68 QStringList MusicPlayer::supportedMimeTypes()
69 {
70     QStringList result = QMediaPlayer::supportedMimeTypes();
71     if (result.isEmpty())
72         result.append(QStringLiteral("audio/mpeg"));
73     return result;
74 }
75 
id()76 QString MusicPlayer::id()
77 {
78     return "music";
79 }
80 
openFile()81 void MusicPlayer::openFile()
82 {
83     QFileDialog fileDialog(this);
84     fileDialog.setAcceptMode(QFileDialog::AcceptOpen);
85     fileDialog.setWindowTitle(tr("Open File"));
86     fileDialog.setMimeTypeFilters(MusicPlayer::supportedMimeTypes());
87     fileDialog.setDirectory(QStandardPaths::standardLocations(QStandardPaths::MusicLocation).value(0, QDir::homePath()));
88     if (fileDialog.exec() == QDialog::Accepted)
89     {
90          playUrl(fileDialog.selectedUrls().constFirst());
91     }
92 
93 }
94 
playUrl(const QUrl & url)95 void MusicPlayer::playUrl(const QUrl &url)
96 {
97     playButton->setEnabled(true);
98     if (url.isLocalFile()) {
99         const QString filePath = url.toLocalFile();
100         setWindowFilePath(filePath);
101         infoLabel->setText(QDir::toNativeSeparators(filePath));
102         fileName = QFileInfo(filePath).fileName();
103     } else {
104         setWindowFilePath(QString());
105         infoLabel->setText(url.toString());
106         fileName.clear();
107     }
108     mediaPlayer.setMedia(url);
109     mediaPlayer.play();
110 }
111 
togglePlayback()112 void MusicPlayer::togglePlayback()
113 {
114     if (mediaPlayer.mediaStatus() == QMediaPlayer::NoMedia)
115         openFile();
116     else if (mediaPlayer.state() == QMediaPlayer::PlayingState)
117         mediaPlayer.pause();
118     else
119         mediaPlayer.play();
120 }
121 
seekForward()122 void MusicPlayer::seekForward()
123 {
124     positionSlider->triggerAction(QSlider::SliderPageStepAdd);
125 }
126 
seekBackward()127 void MusicPlayer::seekBackward()
128 {
129     positionSlider->triggerAction(QSlider::SliderPageStepSub);
130 }
131 
132 //! [0]
event(QEvent * event)133 bool MusicPlayer::event(QEvent *event)
134 {
135     return QWidget::event(event);
136 }
137 //! [0]
138 
canHandleDrop(const QDropEvent * event)139 static bool canHandleDrop(const QDropEvent *event)
140 {
141     const QList<QUrl> urls = event->mimeData()->urls();
142     if (urls.size() != 1)
143         return false;
144     QMimeDatabase mimeDatabase;
145     return MusicPlayer::supportedMimeTypes().
146         contains(mimeDatabase.mimeTypeForUrl(urls.constFirst()).name());
147 }
148 
dragEnterEvent(QDragEnterEvent * event)149 void MusicPlayer::dragEnterEvent(QDragEnterEvent *event)
150 {
151     event->setAccepted(canHandleDrop(event));
152 }
153 
dropEvent(QDropEvent * event)154 void MusicPlayer::dropEvent(QDropEvent *event)
155 {
156     event->accept();
157    // playUrl(event->mimeData()->urls().constFirst());
158 }
159 
mousePressEvent(QMouseEvent * event)160 void MusicPlayer::mousePressEvent(QMouseEvent *event)
161 {
162     offset = event->globalPos() - pos();
163     event->accept();
164 }
165 
mouseMoveEvent(QMouseEvent * event)166 void MusicPlayer::mouseMoveEvent(QMouseEvent *event)
167 {
168     //move(event->globalPos() - offset);
169     event->accept();
170 }
171 
mouseReleaseEvent(QMouseEvent * event)172 void MusicPlayer::mouseReleaseEvent(QMouseEvent *event)
173 {
174     offset = QPoint();
175     event->accept();
176 }
177 
updateState(QMediaPlayer::State state)178 void MusicPlayer::updateState(QMediaPlayer::State state)
179 {
180     if (state == QMediaPlayer::PlayingState) {
181         playButton->setToolTip(tr("Pause"));
182         playButton->setIcon(style()->standardIcon(QStyle::SP_MediaPause));
183     } else {
184         playButton->setToolTip(tr("Play"));
185         playButton->setIcon(style()->standardIcon(QStyle::SP_MediaPlay));
186     }
187 }
188 
formatTime(qint64 timeMilliSeconds)189 static QString formatTime(qint64 timeMilliSeconds)
190 {
191     qint64 seconds = timeMilliSeconds / 1000;
192     const qint64 minutes = seconds / 60;
193     seconds -= minutes * 60;
194     return QStringLiteral("%1:%2")
195         .arg(minutes, 2, 10, QLatin1Char('0'))
196         .arg(seconds, 2, 10, QLatin1Char('0'));
197 }
198 
updatePosition(qint64 position)199 void MusicPlayer::updatePosition(qint64 position)
200 
201 {
202     positionSlider->setValue(position);
203     positionLabel->setText(formatTime(position));
204 }
205 
updateDuration(qint64 duration)206 void MusicPlayer::updateDuration(qint64 duration)
207 {
208     positionSlider->setRange(0, duration);
209     positionSlider->setEnabled(duration > 0);
210     positionSlider->setPageStep(duration / 10);
211     updateInfo();
212 }
213 
214 
setPosition(int position)215 void MusicPlayer::setPosition(int position)
216 {
217     // avoid seeking when the slider value change is triggered from updatePosition()
218     if (qAbs(mediaPlayer.position() - position) > 99)
219     {
220         mediaPlayer.setPosition(position);
221     }
222 }
223 
updateInfo()224 void MusicPlayer::updateInfo()
225 {
226     QStringList info;
227     if (!fileName.isEmpty())
228         info.append(fileName);
229     if (mediaPlayer.isMetaDataAvailable()) {
230         QString author = mediaPlayer.metaData(QStringLiteral("Author")).toString();
231         if (!author.isEmpty())
232             info.append(author);
233         QString title = mediaPlayer.metaData(QStringLiteral("Title")).toString();
234         if (!title.isEmpty())
235             info.append(title);
236     }
237     info.append(formatTime(mediaPlayer.duration()));
238     infoLabel->setText(info.join(tr(" - ")));
239 }
240 
handleError()241 void MusicPlayer::handleError()
242 {
243     playButton->setEnabled(false);
244     const QString errorString = mediaPlayer.errorString();
245     infoLabel->setText(errorString.isEmpty()
246                        ? tr("Unknown error #%1").arg(int(mediaPlayer.error()))
247                        : tr("Error: %1").arg(errorString));
248 }
249 
createWidgets()250 void MusicPlayer::createWidgets()
251 {
252     playButton = new QToolButton(this);
253     playButton->setEnabled(false);
254     playButton->setToolTip(tr("Play"));
255     playButton->setIcon(style()->standardIcon(QStyle::SP_MediaPlay));
256     playButton->setFixedSize(55,35);
257     connect(playButton, &QAbstractButton::clicked, this, &MusicPlayer::togglePlayback);
258 
259     QAbstractButton *openButton = new QToolButton(this);
260     openButton->setText(tr("..."));
261     openButton->setToolTip(tr("Open a file..."));
262     openButton->setFixedSize(55,35);
263     connect(openButton, &QAbstractButton::clicked, this, &MusicPlayer::openFile);
264 
265     volumeButton = new VolumeButton(this);
266     volumeButton->setToolTip(tr("Adjust volume"));
267     volumeButton->setVolume(mediaPlayer.volume());
268     volumeButton->setFixedSize(55,35);
269     connect(volumeButton, &VolumeButton::volumeChanged, &mediaPlayer, &QMediaPlayer::setVolume);
270 
271     positionSlider = new QSlider(Qt::Horizontal, this);
272     positionSlider->setEnabled(false);
273     positionSlider->setToolTip(tr("Seek"));
274     positionSlider->setMaximum(1000000);
275     positionSlider->setMinimum(0);
276     positionSlider->setValue(0);
277     positionSlider->setMinimumWidth(120);
278     connect(positionSlider, &QSlider::valueChanged, this, &MusicPlayer::setPosition);
279 
280     infoLabel = new QLabel(this);
281     QFont font;
282     font.setPointSize(14);
283     infoLabel->setFont(font);
284 
285     positionLabel = new QLabel(tr("00:00"), this);
286     positionLabel->setMinimumWidth(positionLabel->sizeHint().width());
287 
288     QGridLayout *controlLayout = new QGridLayout(this);
289     controlLayout->addWidget(openButton,1,0);
290     controlLayout->addWidget(playButton,1,1);
291     controlLayout->addWidget(positionSlider,1,2);
292     controlLayout->addWidget(positionLabel,1,3);
293     controlLayout->addWidget(volumeButton,1,4);
294     controlLayout->addWidget(infoLabel,0,2);
295     controlLayout->setSpacing(25);
296 
297 }
298 
createShortcuts()299 void MusicPlayer::createShortcuts()
300 {
301     QShortcut *quitShortcut = new QShortcut(QKeySequence::Quit, this);
302     connect(quitShortcut, &QShortcut::activated, QCoreApplication::quit);
303 
304     QShortcut *openShortcut = new QShortcut(QKeySequence::Open, this);
305     connect(openShortcut, &QShortcut::activated, this, &MusicPlayer::openFile);
306 
307     QShortcut *toggleShortcut = new QShortcut(Qt::Key_Space, this);
308     connect(toggleShortcut, &QShortcut::activated, this, &MusicPlayer::togglePlayback);
309 
310     QShortcut *forwardShortcut = new QShortcut(Qt::Key_Right, this);
311     connect(forwardShortcut, &QShortcut::activated, this, &MusicPlayer::seekForward);
312 
313     QShortcut *backwardShortcut = new QShortcut(Qt::Key_Left, this);
314     connect(backwardShortcut, &QShortcut::activated, this, &MusicPlayer::seekBackward);
315 
316     QShortcut *increaseShortcut = new QShortcut(Qt::Key_Up, this);
317     connect(increaseShortcut, &QShortcut::activated, volumeButton, &VolumeButton::increaseVolume);
318 
319     QShortcut *decreaseShortcut = new QShortcut(Qt::Key_Down, this);
320     connect(decreaseShortcut, &QShortcut::activated, volumeButton, &VolumeButton::descreaseVolume);
321 }
322 
323