shuffle, repeat work, save last playlist
[tomamp] / mainwindow.cpp
1 /****************************************************************************
2 **
3 ** Copyright (C) 2010 Nokia Corporation and/or its subsidiary(-ies).
4 ** All rights reserved.
5 ** Contact: Nokia Corporation (qt-info@nokia.com)
6 **
7 ** This file is part of the examples of the Qt Toolkit.
8 **
9 ** $QT_BEGIN_LICENSE:LGPL$
10 ** Commercial Usage
11 ** Licensees holding valid Qt Commercial licenses may use this file in
12 ** accordance with the Qt Commercial License Agreement provided with the
13 ** Software or, alternatively, in accordance with the terms contained in
14 ** a written agreement between you and Nokia.
15 **
16 ** GNU Lesser General Public License Usage
17 ** Alternatively, this file may be used under the terms of the GNU Lesser
18 ** General Public License version 2.1 as published by the Free Software
19 ** Foundation and appearing in the file LICENSE.LGPL included in the
20 ** packaging of this file.  Please review the following information to
21 ** ensure the GNU Lesser General Public License version 2.1 requirements
22 ** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
23 **
24 ** In addition, as a special exception, Nokia gives you certain additional
25 ** rights.  These rights are described in the Nokia Qt LGPL Exception
26 ** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
27 **
28 ** GNU General Public License Usage
29 ** Alternatively, this file may be used under the terms of the GNU
30 ** General Public License version 3.0 as published by the Free Software
31 ** Foundation and appearing in the file LICENSE.GPL included in the
32 ** packaging of this file.  Please review the following information to
33 ** ensure the GNU General Public License version 3.0 requirements will be
34 ** met: http://www.gnu.org/copyleft/gpl.html.
35 **
36 ** If you have questions regarding the use of this file, please contact
37 ** Nokia at qt-info@nokia.com.
38 ** $QT_END_LICENSE$
39 **
40 ***************************************************************************/
41
42 #include <QtGui>
43 #include <QtDebug>
44 #include <QInputDialog>
45
46 #include "mainwindow.h"
47
48 #define AVOID_INPUT_DIALOG 1
49
50 MainWindow::MainWindow()
51     : settings (tr ("TomAmp"), "TomAmp")
52 {
53     audioOutput = new Phonon::AudioOutput(Phonon::MusicCategory, this);
54     mediaObject = new Phonon::MediaObject(this);
55     metaInformationResolver = new Phonon::MediaObject(this);
56
57     mediaObject->setTickInterval(500);
58     connect(mediaObject, SIGNAL(tick(qint64)), this, SLOT(tick(qint64)));
59     connect(mediaObject, SIGNAL(stateChanged(Phonon::State,Phonon::State)),
60     this, SLOT(stateChanged(Phonon::State,Phonon::State)));
61     connect(metaInformationResolver, SIGNAL(stateChanged(Phonon::State,Phonon::State)),
62     this, SLOT(metaStateChanged(Phonon::State,Phonon::State)));
63     connect(mediaObject, SIGNAL(currentSourceChanged(Phonon::MediaSource)),
64     this, SLOT(sourceChanged(Phonon::MediaSource)));
65     connect(mediaObject, SIGNAL(aboutToFinish()), this, SLOT(aboutToFinish()));
66
67     Phonon::createPath(mediaObject, audioOutput);
68
69     repeat = settings.value("repeat", false).toBool();
70     shuffle = settings.value("shuffle", false).toBool();
71     qsrand (time (NULL));
72     setupShuffleList();
73     setupActions();
74     setupMenus();
75     setupUi();
76     timeLcd->display("00:00");
77     addStringList(settings.value("lastPlaylist").toStringList());
78 }
79
80 MainWindow::~MainWindow()
81 {
82     settings.setValue("shuffle", shuffle);
83     QStringList curList;
84     foreach (Phonon::MediaSource src, sources)
85     {
86         curList.append(src.fileName());
87     }
88     settings.setValue("lastPlaylist", curList);
89 }
90
91 void MainWindow::addFiles()
92 {
93     QString folder = settings.value("LastFolder").toString();
94     if (folder.isEmpty())
95         folder = QDesktopServices::storageLocation(QDesktopServices::MusicLocation);
96     QStringList files = QFileDialog::getOpenFileNames(this, tr("Select Files To Add"),
97                     folder);
98
99     if (files.isEmpty())
100         return;
101
102     QString dir = QFileInfo (files[0]).absoluteDir().absolutePath();
103     settings.setValue("LastFolder", dir);
104     int index = sources.size();
105     foreach (QString string, files)
106     {
107         Phonon::MediaSource source (string);
108         sources.append(source);
109     }
110     if (!sources.isEmpty())
111         metaInformationResolver->setCurrentSource(sources.at(index));
112     setupShuffleList();
113
114 }
115
116 void MainWindow::addFolders()
117 {
118     QString folder = settings.value("LastFolder").toString();
119     if (folder.isEmpty())
120         folder = QDesktopServices::storageLocation(QDesktopServices::MusicLocation);
121     QString dir = QFileDialog::getExistingDirectory(this,
122             tr("Select Directory To Add"),
123             folder);
124
125     QStringList filters;
126     filters << "*.mp3";
127
128     QStringList files = QDir (dir).entryList(filters);
129
130     if (files.isEmpty())
131         return;
132
133     settings.setValue("LastFolder", dir);
134     int index = sources.size();
135     foreach (QString string, files)
136     {
137         QString fname = dir + "/" + string;
138         qDebug () << fname;
139         Phonon::MediaSource source(fname);
140         sources.append(source);
141     }
142     if (!sources.isEmpty())
143         metaInformationResolver->setCurrentSource(sources.at(index));
144     setupShuffleList();
145
146 }
147
148 void MainWindow::addUrl()
149 {
150 #ifdef AVOID_INPUT_DIALOG
151     QString url = "http://war.str3am.com:7970";
152 #else
153     QString url = QInputDialog::getText(this, "Get URL", "Please type in the stream URL");
154 #endif
155     int index = sources.size();
156     if (!url.isEmpty())
157     {
158         Phonon::MediaSource source(url);
159         sources.append(source);
160     }
161     if (!sources.isEmpty())
162         metaInformationResolver->setCurrentSource(sources.at(index));
163     setupShuffleList();
164 }
165
166 void MainWindow::addStringList(const QStringList& list)
167 {
168     int index = sources.size();
169     foreach (QString string, list)
170     {
171         Phonon::MediaSource source(string);
172         sources.append(source);
173     }
174     if (!sources.isEmpty())
175         metaInformationResolver->setCurrentSource(sources.at(index));
176     setupShuffleList();
177 }
178
179 void MainWindow::about()
180 {
181     QMessageBox::information(this, tr("About Music Player"),
182         tr("The Music Player example shows how to use Phonon - the multimedia"
183         " framework that comes with Qt - to create a simple music player."));
184 }
185
186 void MainWindow::stateChanged(Phonon::State newState, Phonon::State /* oldState */)
187 {
188     qDebug () << "State: " << newState;
189     switch (newState)
190     {
191         case Phonon::ErrorState:
192             if (mediaObject->errorType() == Phonon::FatalError)
193             {
194                 QMessageBox::warning(this, tr("Fatal Error"),
195                 mediaObject->errorString());
196             }
197             else
198             {
199                 QMessageBox::warning(this, tr("Error"),
200                 mediaObject->errorString());
201             }
202             break;
203         case Phonon::PlayingState:
204             setWindowTitle(metaInformationResolver->metaData().value("TITLE") + " - TomAmp");
205             playAction->setEnabled(false);
206             pauseAction->setEnabled(true);
207             stopAction->setEnabled(true);
208             break;
209         case Phonon::StoppedState:
210             stopAction->setEnabled(false);
211             playAction->setEnabled(true);
212             pauseAction->setEnabled(false);
213             timeLcd->display("00:00");
214             break;
215         case Phonon::PausedState:
216             pauseAction->setEnabled(false);
217             stopAction->setEnabled(true);
218             playAction->setEnabled(true);
219             qDebug () << "Queue size: " << mediaObject->queue().size ();
220             if (mediaObject->queue().size ())
221             {
222                 mediaObject->setCurrentSource(mediaObject->queue()[0]);
223                 musicTable->selectRow(sources.indexOf(mediaObject->currentSource()));
224                 mediaObject->play();
225             }
226             mediaObject->clearQueue();
227             break;
228         case Phonon::BufferingState:
229             qDebug () << "Buffering";
230             break;
231         default:
232         ;
233     }
234 }
235
236 void MainWindow::tick(qint64 time)
237 {
238     QTime displayTime(0, (time / 60000) % 60, (time / 1000) % 60);
239
240     timeLcd->display(displayTime.toString("mm:ss"));
241 }
242
243 void MainWindow::tableClicked(int row, int /* column */)
244 {
245 //    bool wasPlaying = mediaObject->state() == Phonon::PlayingState;
246
247     mediaObject->stop();
248     mediaObject->clearQueue();
249
250     if (row >= sources.size())
251         return;
252
253     mediaObject->setCurrentSource(sources[row]);
254
255     mediaObject->play();
256     int ind = shuffleList.indexOf(row);
257     shuffleList.removeAt(ind);
258     shuffleList.insert(0, row);
259     qDebug () << "Modified shuffle list: " << shuffleList;
260 }
261
262 void MainWindow::sourceChanged(const Phonon::MediaSource &source)
263 {
264     musicTable->selectRow(sources.indexOf(source));
265     timeLcd->display("00:00");
266 }
267
268 void MainWindow::metaStateChanged(Phonon::State newState, Phonon::State /* oldState */)
269 {
270     if (newState == Phonon::ErrorState)
271     {
272         QMessageBox::warning(this, tr("Error opening files"),
273         metaInformationResolver->errorString());
274         while (!sources.isEmpty() &&
275             !(sources.takeLast() == metaInformationResolver->currentSource())) {}  /* loop */;
276         return;
277     }
278
279     if (newState != Phonon::StoppedState && newState != Phonon::PausedState)
280     {
281         return;
282     }
283
284     if (metaInformationResolver->currentSource().type() == Phonon::MediaSource::Invalid)
285         return;
286
287     QMap<QString, QString> metaData = metaInformationResolver->metaData();
288
289     QString title = metaData.value("TITLE");
290     if (title == "")
291         title = metaInformationResolver->currentSource().fileName();
292
293     if (title == "")
294         title = metaInformationResolver->currentSource().url().toString();
295
296     QTableWidgetItem *titleItem = new QTableWidgetItem(title);
297     titleItem->setFlags(titleItem->flags() ^ Qt::ItemIsEditable);
298     QTableWidgetItem *artistItem = new QTableWidgetItem(metaData.value("ARTIST"));
299     artistItem->setFlags(artistItem->flags() ^ Qt::ItemIsEditable);
300     QTableWidgetItem *albumItem = new QTableWidgetItem(metaData.value("ALBUM"));
301     albumItem->setFlags(albumItem->flags() ^ Qt::ItemIsEditable);
302     QTableWidgetItem *yearItem = new QTableWidgetItem(metaData.value("DATE"));
303     yearItem->setFlags(yearItem->flags() ^ Qt::ItemIsEditable);
304
305     int currentRow = musicTable->rowCount();
306     musicTable->insertRow(currentRow);
307     musicTable->setItem(currentRow, 0, artistItem);
308     musicTable->setItem(currentRow, 1, titleItem);
309     musicTable->setItem(currentRow, 2, albumItem);
310     musicTable->setItem(currentRow, 3, yearItem);
311
312
313     if (musicTable->selectedItems().isEmpty())
314     {
315         musicTable->selectRow(0);
316         mediaObject->setCurrentSource(metaInformationResolver->currentSource());
317     }
318
319     Phonon::MediaSource source = metaInformationResolver->currentSource();
320     int index = sources.indexOf(metaInformationResolver->currentSource()) + 1;
321     if (sources.size() > index)
322     {
323         metaInformationResolver->setCurrentSource(sources.at(index));
324     }
325     else
326     {
327         musicTable->resizeColumnsToContents();
328         if (musicTable->columnWidth(0) > 300)
329             musicTable->setColumnWidth(0, 300);
330     }
331 }
332
333 void MainWindow::aboutToFinish()
334 {
335     qDebug () << "Abouttotfinish";
336     int index = sources.indexOf(mediaObject->currentSource()) + 1;
337     if (shuffle)
338     {
339         index = shuffleList.indexOf(sources.indexOf(mediaObject->currentSource())) + 1;
340         if (index < shuffleList.size ())
341         {
342             mediaObject->enqueue(sources.at (shuffleList[index]));
343         }
344         else if (repeat)
345         {
346             mediaObject->enqueue(sources.at (shuffleList[0]));
347         }
348
349     }
350     else
351     {
352         if (sources.size() > index)
353         {
354             mediaObject->enqueue(sources.at(index));
355             qDebug () << "Enqueue " << index << " pfm " << mediaObject->prefinishMark();
356         }
357         else if (repeat)
358         {
359             mediaObject->enqueue(sources.at(0));
360             qDebug () << "Enqueue " << 0 << " pfm " << mediaObject->prefinishMark();
361         }
362     }
363 }
364
365 void MainWindow::finished()
366 {
367     qDebug () << "Finished";
368 }
369
370 void MainWindow::setupActions()
371 {
372     playAction = new QAction(style()->standardIcon(QStyle::SP_MediaPlay), tr("Play"), this);
373     playAction->setShortcut(tr("Crl+P"));
374     playAction->setDisabled(true);
375     pauseAction = new QAction(style()->standardIcon(QStyle::SP_MediaPause), tr("Pause"), this);
376     pauseAction->setShortcut(tr("Ctrl+A"));
377     pauseAction->setDisabled(true);
378     stopAction = new QAction(style()->standardIcon(QStyle::SP_MediaStop), tr("Stop"), this);
379     stopAction->setShortcut(tr("Ctrl+S"));
380     stopAction->setDisabled(true);
381     nextAction = new QAction(style()->standardIcon(QStyle::SP_MediaSkipForward), tr("Next"), this);
382     nextAction->setShortcut(tr("Ctrl+N"));
383     previousAction = new QAction(style()->standardIcon(QStyle::SP_MediaSkipBackward), tr("Previous"), this);
384     previousAction->setShortcut(tr("Ctrl+R"));
385     repeatAction = new QAction(style()->standardIcon(QStyle::SP_BrowserReload), tr("Repeat"), this);
386     repeatAction->setCheckable(true);
387     repeatAction->setChecked(repeat);
388     repeatAction->setShortcut(tr("Ctrl+I"));
389     shuffleAction = new QAction(style()->standardIcon(QStyle::SP_TrashIcon), tr("S&huffle"), this);
390     shuffleAction->setCheckable(true);
391     shuffleAction->setChecked(shuffle);
392     shuffleAction->setShortcut(tr("Ctrl+H"));
393     addFilesAction = new QAction(tr("Add &File"), this);
394     addFilesAction->setShortcut(tr("Ctrl+F"));
395     addFoldersAction = new QAction(tr("Add F&older"), this);
396     addFoldersAction->setShortcut(tr("Ctrl+O"));
397     addUrlAction = new QAction(tr("Add &Url"), this);
398     addUrlAction->setShortcut(tr("Ctrl+U"));
399     exitAction = new QAction(tr("E&xit"), this);
400     exitAction->setShortcuts(QKeySequence::Quit);
401     aboutAction = new QAction(tr("A&bout"), this);
402     aboutAction->setShortcut(tr("Ctrl+B"));
403     aboutQtAction = new QAction(tr("About &Qt"), this);
404     aboutQtAction->setShortcut(tr("Ctrl+Q"));
405
406     connect(playAction, SIGNAL(triggered()), mediaObject, SLOT(play()));
407     connect(pauseAction, SIGNAL(triggered()), mediaObject, SLOT(pause()) );
408     connect(stopAction, SIGNAL(triggered()), mediaObject, SLOT(stop()));
409     connect(repeatAction, SIGNAL(triggered()), this, SLOT(repeatToggle()));
410     connect(shuffleAction, SIGNAL(triggered()), this, SLOT(shuffleToggle()));
411     connect(addFilesAction, SIGNAL(triggered()), this, SLOT(addFiles()));
412     connect(addFoldersAction, SIGNAL(triggered()), this, SLOT(addFolders()));
413     connect(addUrlAction, SIGNAL(triggered()), this, SLOT(addUrl()));
414     connect(exitAction, SIGNAL(triggered()), this, SLOT(close()));
415     connect(aboutAction, SIGNAL(triggered()), this, SLOT(about()));
416     connect(aboutQtAction, SIGNAL(triggered()), qApp, SLOT(aboutQt()));
417 }
418
419 void MainWindow::repeatToggle ()
420 {
421     repeat = !repeat;
422     qDebug() << "Repeat toggled to " << repeat;
423     settings.setValue("repeat", QVariant (repeat));
424 }
425
426 void MainWindow::shuffleToggle ()
427 {
428     shuffle = !shuffle;
429     settings.setValue("shuffle", QVariant (shuffle));
430 }
431
432
433 void MainWindow::setupMenus()
434 {
435     QMenu *fileMenu = menuBar()->addMenu(tr("&File"));
436     fileMenu->addAction(addFilesAction);
437     fileMenu->addAction(addFoldersAction);
438     fileMenu->addAction(addUrlAction);
439     fileMenu->addSeparator();
440     fileMenu->addAction(exitAction);
441
442     QMenu *aboutMenu = menuBar()->addMenu(tr("&Help"));
443     aboutMenu->addAction(aboutAction);
444     aboutMenu->addAction(aboutQtAction);
445 }
446
447 void MainWindow::setupUi()
448 {
449     QToolBar *bar = new QToolBar;
450
451     bar->setOrientation(Qt::Vertical);
452     bar->addAction(playAction);
453     bar->addAction(pauseAction);
454     bar->addAction(stopAction);
455     bar->addAction(repeatAction);
456     bar->addAction(shuffleAction);
457
458     seekSlider = new Phonon::SeekSlider(this);
459     seekSlider->setMediaObject(mediaObject);
460
461 /*    volumeSlider = new Phonon::VolumeSlider(this);
462     volumeSlider->setAudioOutput(audioOutput);
463     volumeSlider->setSizePolicy(QSizePolicy::Maximum, QSizePolicy::Maximum);
464     volumeSlider->setOrientation(Qt::Vertical);*/
465
466     QLabel *volumeLabel = new QLabel;
467     volumeLabel->setPixmap(QPixmap("images/volume.png"));
468
469 /*    QPalette palette;
470     palette.setBrush(QPalette::Light, Qt::darkGray);*/
471
472     timeLcd = new QLCDNumber;
473 //    timeLcd->setPalette(palette);
474
475     QStringList headers;
476     headers << tr("Artist") << tr("Title") << tr("Album") << tr("Year");
477
478     musicTable = new QTableWidget(0, 4);
479     musicTable->setHorizontalHeaderLabels(headers);
480     musicTable->setSelectionMode(QAbstractItemView::SingleSelection);
481     musicTable->setSelectionBehavior(QAbstractItemView::SelectRows);
482     connect(musicTable, SIGNAL(cellDoubleClicked(int,int)),
483         this, SLOT(tableClicked(int,int)));
484
485     QHBoxLayout *seekerLayout = new QHBoxLayout;
486     seekerLayout->addWidget(seekSlider);
487     seekerLayout->addWidget(timeLcd);
488
489     QVBoxLayout *playbackLayout = new QVBoxLayout;
490     playbackLayout->addWidget(bar);
491 //    playbackLayout->addStretch();
492 //    playbackLayout->addWidget(volumeSlider);
493 //    playbackLayout->addWidget(volumeLabel);
494
495     QVBoxLayout *seekAndTableLayout = new QVBoxLayout;
496
497     seekAndTableLayout->addWidget(musicTable);
498     seekAndTableLayout->addLayout(seekerLayout);
499
500     QHBoxLayout *mainLayout = new QHBoxLayout;
501     mainLayout->addLayout(seekAndTableLayout);
502     mainLayout->addLayout(playbackLayout);
503
504     QWidget *widget = new QWidget;
505     widget->setLayout(mainLayout);
506
507     setCentralWidget(widget);
508     setWindowTitle("TomAmp");
509 //    ui.setupUi(this);
510 }
511
512
513 void MainWindow::setupShuffleList()
514 {
515     QList<int> tmp;
516     for (int i = 0; i < sources.size(); ++i)
517         tmp.append(i);
518     shuffleList.clear();
519     while (tmp.size ())
520     {
521         int ind = qrand () % tmp.size();
522         shuffleList.append(tmp[ind]);
523         tmp.removeAt(ind);
524     }
525     qDebug () << shuffleList;
526 }