kind of works, but has problems with non-playables and maybe next too...
[tomamp] / mainwindow.cpp
1 #include <QtGui>
2 #include <QtDebug>
3 #include <QInputDialog>
4
5 #include "mainwindow.h"
6 #include "time.h"
7
8 //#define AVOID_INPUT_DIALOG 0
9
10 MainWindow::MainWindow()
11     : plman (this), settings (tr ("TomAmp"), "TomAmp")
12 {
13     audioOutput = new Phonon::AudioOutput(Phonon::MusicCategory, this);
14     mediaObject = new Phonon::MediaObject(this);
15
16     mediaObject->setTickInterval(1000);
17     connect(mediaObject, SIGNAL(tick(qint64)), this, SLOT(tick(qint64)));
18     connect(mediaObject, SIGNAL(stateChanged(Phonon::State,Phonon::State)),
19         this, SLOT(stateChanged(Phonon::State,Phonon::State)));
20     connect(mediaObject, SIGNAL(currentSourceChanged(Phonon::MediaSource)),
21         this, SLOT(sourceChanged(Phonon::MediaSource)));
22     connect(mediaObject, SIGNAL(aboutToFinish()), this, SLOT(aboutToFinish()));
23     connect (&plman, SIGNAL (playlistChanged (int)), this, SLOT (playlistChanged(int)));
24     connect (&plman, SIGNAL (itemUpdated(int)), this, SLOT (itemUpdated (int)));
25
26     Phonon::createPath(mediaObject, audioOutput);
27
28     qsrand (time (NULL));
29     repeat = settings.value("repeat", false).toBool();
30     shuffle = settings.value("shuffle", false).toBool();
31     setupShuffleList();
32     setupActions();
33     setupMenus();
34     setupUi();
35     timeLcd->display("00:00");
36     plman.addStringList(settings.value("lastPlaylist").toStringList());
37     setupShuffleList();
38     audioOutput->setVolume(settings.value("volume", .5).toReal());
39 }
40
41 MainWindow::~MainWindow()
42 {
43     settings.setValue("shuffle", shuffle);
44     settings.setValue("repeat", repeat);
45     settings.setValue("lastPlaylist", plman.playlistStrings());
46     settings.setValue("volume", audioOutput->volume());
47 }
48
49 void MainWindow::addFiles()
50 {
51     QString folder = settings.value("LastFolder").toString();
52     if (folder.isEmpty())
53         folder = QDesktopServices::storageLocation(QDesktopServices::MusicLocation);
54     QStringList files = QFileDialog::getOpenFileNames(this, tr("Select Files To Add"),
55                     folder);
56
57     if (files.isEmpty())
58         return;
59
60     QString dir = QFileInfo (files[0]).absoluteDir().absolutePath();
61     settings.setValue("LastFolder", dir);
62     QStringList toadd;
63     foreach (QString string, files)
64     {
65         toadd.append (string);
66     }
67     plman.addStringList(toadd);
68 }
69
70 void MainWindow::addFolder()
71 {
72     QString folder = settings.value("LastFolder").toString();
73     if (folder.isEmpty())
74         folder = QDesktopServices::storageLocation(QDesktopServices::MusicLocation);
75     QString dir = QFileDialog::getExistingDirectory(this,
76             tr("Select Directory To Add"),
77             folder);
78
79     QStringList filters;
80     QStringList files = QDir (dir).entryList(filters, QDir::AllDirs);
81     files.removeAll(".");
82     files.removeAll("..");
83     qDebug () << files;
84     bool recursive = false;
85     if (files.size())
86         recursive = QMessageBox::question(this, "Add all folders", "Subfolders have been detected, add everything?", QMessageBox::Yes | QMessageBox::No) == QMessageBox::Yes;
87     plman.parseAndAddFolder(dir, recursive);
88 }
89
90
91 void MainWindow::addUrl()
92 {
93 #ifdef AVOID_INPUT_DIALOG
94     QString url = "http://war.str3am.com:7970";
95 #else
96     QString url = QInputDialog::getText(this, "Get URL", "Please type in the stream URL");
97 #endif
98     QStringList toadd;
99     toadd << url;
100     plman.addStringList(toadd);
101 }
102
103
104 void MainWindow::about()
105 {
106     QMessageBox::information(this, tr("About TomAmp v0.1"),
107         tr("TomAmp is a simple playlist-based music player.\n\n"
108         "(c) 2010 Tamas Marki <tmarki@gmail.com>\n\n"
109         "Please send comments and bug reports to the above e-mail address.\n\n"
110         "Icons by deleket (http://www.deleket.com)"));
111 }
112
113 void MainWindow::stateChanged(Phonon::State newState, Phonon::State /* oldState */)
114 {
115     qDebug () << "State: " << newState;
116     switch (newState)
117     {
118         case Phonon::ErrorState:
119             if (mediaObject->errorType() == Phonon::FatalError)
120             {
121 //                QMessageBox::warning(this, tr("Fatal Error"),
122 //                mediaObject->errorString() + mediaObject->currentSource().fileName() + ", " + mediaObject->currentSource().url().toString());
123             }
124             else
125             {
126 //                QMessageBox::warning(this, tr("Error"),
127 //                mediaObject->errorString());
128             }
129             next ();
130             break;
131         case Phonon::PlayingState:
132             setWindowTitle(mediaObject->metaData().value("TITLE") + " - TomAmp");
133             pauseAction->setVisible(true);
134             playAction->setVisible (false);
135             playAction->setEnabled(false);
136             pauseAction->setEnabled(true);
137             stopAction->setEnabled(true);
138             break;
139         case Phonon::StoppedState:
140             stopAction->setEnabled(false);
141             playAction->setEnabled(true);
142             pauseAction->setVisible(false);
143             playAction->setVisible(true);
144             pauseAction->setEnabled(false);
145             timeLcd->display("00:00");
146             break;
147         case Phonon::PausedState:
148             pauseAction->setEnabled(false);
149             stopAction->setEnabled(true);
150             pauseAction->setVisible(false);
151             playAction->setVisible(true);
152             playAction->setEnabled(true);
153             qDebug () << "Queue size: " << mediaObject->queue().size ();
154             if (mediaObject->queue().size ())
155             {
156                 mediaObject->setCurrentSource(mediaObject->queue()[0]);
157                 musicTable->selectRow(plman.indexOf(mediaObject->currentSource()));
158                 mediaObject->play();
159             }
160             mediaObject->clearQueue();
161             break;
162         case Phonon::BufferingState:
163             qDebug () << "Buffering";
164             break;
165         default:
166         ;
167     }
168 }
169
170 void MainWindow::next()
171 {
172     bool wasPlaying = (mediaObject->state () == Phonon::PlayingState);
173     if (mediaObject->state () == Phonon::ErrorState)
174         wasPlaying = true;
175     int index = plman.indexOf(mediaObject->currentSource()) + 1;
176     if (shuffle)
177     {
178         index = shuffleList.indexOf(plman.indexOf(mediaObject->currentSource()));
179         do
180         {
181             index += 1;
182         }
183         while (index < shuffleList.size () && !plman.getItem(index).playable);
184         if (index < shuffleList.size ())
185         {
186             mediaObject->setCurrentSource(plman.at (shuffleList[index]));
187         }
188         else if (repeat)
189         {
190             index = 0;
191             do
192             {
193                 index += 1;
194             }
195             while (index < shuffleList.size () && !plman.getItem(index).playable);
196             if (index < shuffleList.size ())
197                 mediaObject->setCurrentSource(plman.at (shuffleList[index]));
198         }
199
200     }
201     else
202     {
203         while (index < plman.size () && !plman.getItem(index).playable);
204         {
205             index += 1;
206         }
207         if (plman.size() > index)
208         {
209             mediaObject->setCurrentSource(plman.at(index));
210         }
211         else if (repeat)
212         {
213             index = 0;
214             do
215             {
216                 index += 1;
217             }
218             while (index < shuffleList.size () && !plman.getItem(index).playable);
219             mediaObject->setCurrentSource(plman.at(index));
220         }
221     }
222     if (wasPlaying)
223         mediaObject->play();
224 }
225
226 void MainWindow::previous()
227 {
228     bool wasPlaying = (mediaObject->state () == Phonon::PlayingState);
229     int index = plman.indexOf(mediaObject->currentSource()) - 1;
230     if (shuffle)
231     {
232         index = shuffleList.indexOf(plman.indexOf(mediaObject->currentSource())) - 1;
233         if (index >= 0)
234         {
235             mediaObject->setCurrentSource(plman.at (shuffleList[index]));
236         }
237         else if (repeat)
238         {
239             mediaObject->setCurrentSource(plman.at (shuffleList[shuffleList.size() - 1]));
240         }
241
242     }
243     else
244     {
245         if (index >= 0)
246         {
247             mediaObject->setCurrentSource(plman.at(index));
248         }
249         else if (repeat)
250         {
251             mediaObject->setCurrentSource(plman.at(plman.size() - 1));
252         }
253     }
254     if (wasPlaying)
255         mediaObject->play();
256
257 }
258
259 void MainWindow::tick(qint64 time)
260 {
261     QTime displayTime(0, (time / 60000) % 60, (time / 1000) % 60);
262
263     timeLcd->display(displayTime.toString("mm:ss"));
264 }
265
266 void MainWindow::tableClicked(int row, int /* column */)
267 {
268 //    bool wasPlaying = mediaObject->state() == Phonon::PlayingState;
269
270     mediaObject->stop();
271     mediaObject->clearQueue();
272
273     if (row >= plman.size())
274         return;
275
276     int index = row;
277     while (index < plman.size () && !plman.getItem(index).playable);
278     {
279         index += 1;
280     }
281     if (plman.size() > index)
282     {
283         mediaObject->setCurrentSource(plman.at(index));
284         int ind = shuffleList.indexOf(index);
285         shuffleList.removeAt(ind);
286         shuffleList.insert(0, index);
287         qDebug () << "Modified shuffle list: " << shuffleList;
288         mediaObject->play();
289     }
290     else
291     {
292         next ();
293     }
294
295 }
296
297 void MainWindow::sourceChanged(const Phonon::MediaSource &source)
298 {
299     musicTable->selectRow(plman.indexOf(source));
300     timeLcd->display("00:00");
301 }
302
303
304 void MainWindow::aboutToFinish()
305 {
306     qDebug () << "Abouttotfinish";
307     int index = plman.indexOf(mediaObject->currentSource()) + 1;
308     if (shuffle)
309     {
310         index = shuffleList.indexOf(plman.indexOf(mediaObject->currentSource())) + 1;
311         if (index < shuffleList.size ())
312         {
313             mediaObject->enqueue(plman.at (shuffleList[index]));
314         }
315         else if (repeat)
316         {
317             mediaObject->enqueue(plman.at (shuffleList[0]));
318         }
319
320     }
321     else
322     {
323         if (plman.size() > index)
324         {
325             mediaObject->enqueue(plman.at(index));
326             qDebug () << "Enqueue " << index << " pfm " << mediaObject->prefinishMark();
327         }
328         else if (repeat)
329         {
330             mediaObject->enqueue(plman.at(0));
331             qDebug () << "Enqueue " << 0 << " pfm " << mediaObject->prefinishMark();
332         }
333     }
334 }
335
336 void MainWindow::finished()
337 {
338     qDebug () << "Finished";
339 }
340
341 void MainWindow::setupActions()
342 {
343     playAction = new QAction(QIcon (QPixmap (":images/play")), tr("Play"), this);
344     playAction->setShortcut(tr("Crl+P"));
345     playAction->setDisabled(true);
346     pauseAction = new QAction(QIcon (QPixmap (":images/pause")), tr("Pause"), this);
347     pauseAction->setShortcut(tr("Ctrl+A"));
348     pauseAction->setDisabled(true);
349     pauseAction->setVisible(false);
350     stopAction = new QAction(QIcon (QPixmap (":images/stop")), tr("Stop"), this);
351     stopAction->setShortcut(tr("Ctrl+S"));
352     stopAction->setDisabled(true);
353     nextAction = new QAction(QIcon (QPixmap (":images/next")), tr("Next"), this);
354     nextAction->setShortcut(tr("Ctrl+N"));
355     previousAction = new QAction(QIcon (QPixmap (":images/previous")), tr("Previous"), this);
356     previousAction->setShortcut(tr("Ctrl+R"));
357     repeatAction = new QAction(QIcon (QPixmap (":images/repeat")), tr("Repeat"), this);
358     repeatAction->setCheckable(true);
359     repeatAction->setChecked(repeat);
360     repeatAction->setShortcut(tr("Ctrl+I"));
361     shuffleAction = new QAction(QIcon (QPixmap (":images/shuffle")), tr("Shuffle"), this);
362     shuffleAction->setCheckable(true);
363     shuffleAction->setChecked(shuffle);
364     shuffleAction->setShortcut(tr("Ctrl+H"));
365     volumeAction = new QAction(QIcon (QPixmap (":images/volume")), tr("Volume"), this);
366     volumeAction->setCheckable(true);
367     volumeAction->setShortcut(tr("Ctrl+V"));
368     addFilesAction = new QAction(tr("Add &File"), this);
369     addFilesAction->setShortcut(tr("Ctrl+F"));
370     addFoldersAction = new QAction(tr("Add F&older"), this);
371     addFoldersAction->setShortcut(tr("Ctrl+O"));
372     addUrlAction = new QAction(tr("Add &Url"), this);
373     addUrlAction->setShortcut(tr("Ctrl+U"));
374     savePlaylistAction = new QAction (tr("Sa&ve Playlist"), this);
375     savePlaylistAction->setShortcut(tr ("Ctrl+V"));
376     loadPlaylistAction = new QAction (tr("&Load Playlist"), this);
377     loadPlaylistAction->setShortcut(tr("Ctrl+L"));
378     clearPlaylistAction = new QAction (tr("&Clear Playlist"), this);
379     clearPlaylistAction->setShortcut(tr("Ctrl+C"));
380     exitAction = new QAction(tr("E&xit"), this);
381     exitAction->setShortcut(tr("Ctrl+X"));
382     aboutAction = new QAction(tr("A&bout"), this);
383     aboutAction->setShortcut(tr("Ctrl+B"));
384     aboutQtAction = new QAction(tr("About &Qt"), this);
385     aboutQtAction->setShortcut(tr("Ctrl+Q"));
386
387     connect(playAction, SIGNAL(triggered()), mediaObject, SLOT(play()));
388     connect(pauseAction, SIGNAL(triggered()), mediaObject, SLOT(pause()) );
389     connect(stopAction, SIGNAL(triggered()), mediaObject, SLOT(stop()));
390     connect(repeatAction, SIGNAL(triggered()), this, SLOT(repeatToggle()));
391     connect(shuffleAction, SIGNAL(triggered()), this, SLOT(shuffleToggle()));
392     connect(volumeAction, SIGNAL(triggered()), this, SLOT(volumeToggle()));
393     connect(addFilesAction, SIGNAL(triggered()), this, SLOT(addFiles()));
394     connect(addFoldersAction, SIGNAL(triggered()), this, SLOT(addFolder()));
395     connect(addUrlAction, SIGNAL(triggered()), this, SLOT(addUrl()));
396     connect (savePlaylistAction, SIGNAL (triggered()), this, SLOT (savePlaylist()));
397     connect (loadPlaylistAction, SIGNAL (triggered()), this, SLOT (loadPlaylist()));
398     connect (clearPlaylistAction, SIGNAL (triggered()), &plman, SLOT (clearPlaylist()));
399     connect (nextAction, SIGNAL(triggered()), this, SLOT(next()));
400     connect (previousAction, SIGNAL(triggered()), this, SLOT(previous()));
401     connect(exitAction, SIGNAL(triggered()), this, SLOT(close()));
402     connect(aboutAction, SIGNAL(triggered()), this, SLOT(about()));
403     connect(aboutQtAction, SIGNAL(triggered()), qApp, SLOT(aboutQt()));
404 }
405
406
407 void MainWindow::repeatToggle ()
408 {
409     repeat = !repeat;
410     qDebug() << "Repeat toggled to " << repeat;
411     settings.setValue("repeat", QVariant (repeat));
412 }
413
414 void MainWindow::shuffleToggle ()
415 {
416     shuffle = !shuffle;
417     settings.setValue("shuffle", QVariant (shuffle));
418 }
419
420 void MainWindow::volumeToggle ()
421 {
422     qDebug () << "Volumetoggle: " << volumeAction->isChecked();
423     volumeSlider->setVisible(volumeAction->isChecked());
424 }
425
426 void MainWindow::play()
427 {
428
429 }
430
431
432 void MainWindow::setupMenus()
433 {
434     QMenu *fileMenu = menuBar()->addMenu(tr("&File"));
435     fileMenu->addAction(addFilesAction);
436     fileMenu->addAction(addFoldersAction);
437     fileMenu->addAction(addUrlAction);
438     fileMenu->addSeparator();
439     fileMenu->addAction(savePlaylistAction);
440     fileMenu->addAction(loadPlaylistAction);
441     fileMenu->addAction(clearPlaylistAction);
442 //    fileMenu->addAction(exitAction);
443
444     QMenu *aboutMenu = menuBar()->addMenu(tr("&Help"));
445     aboutMenu->addAction(aboutAction);
446     aboutMenu->addAction(aboutQtAction);
447 }
448
449 void MainWindow::setupUi()
450 {
451     QToolBar *bar = new QToolBar;
452
453     bar->setOrientation(Qt::Vertical);
454     bar->setStyleSheet("padding:7px");
455     //bar->addAction(volumeAction);
456
457     seekSlider = new Phonon::SeekSlider(this);
458     seekSlider->setMediaObject(mediaObject);
459
460     volumeSlider = new Phonon::VolumeSlider(this);
461     volumeSlider->setAudioOutput(audioOutput);
462     volumeSlider->setSizePolicy(QSizePolicy::Maximum, QSizePolicy::Maximum);
463     volumeSlider->setOrientation(Qt::Horizontal);
464     volumeSlider->setMuteVisible(false);
465 //    volumeAddedAction = bar->addWidget(volumeSlider);
466 //    volumeAddedAction->setVisible(false);
467     bar->addAction(playAction);
468     bar->addAction(pauseAction);
469     bar->addAction(stopAction);
470     bar->addAction(repeatAction);
471     bar->addAction(shuffleAction);
472     bar->addAction(nextAction);
473     bar->addAction(previousAction);
474
475 /*    QLabel *volumeLabel = new QLabel;
476     volumeLabel->setPixmap(QPixmap("images/volume.png"));*/
477
478 /*    QPalette palette;
479     palette.setBrush(QPalette::Light, Qt::darkGray);*/
480
481     timeLcd = new QLCDNumber;
482 //    timeLcd->setPalette(palette);
483
484     QStringList headers;
485     headers << tr("Artist") << tr("Title") << tr("Album");
486
487     musicTable = new QTableWidget(0, 3);
488     musicTable->setHorizontalHeaderLabels(headers);
489     musicTable->setSelectionMode(QAbstractItemView::SingleSelection);
490     musicTable->setSelectionBehavior(QAbstractItemView::SelectRows);
491     connect(musicTable, SIGNAL(cellDoubleClicked(int,int)),
492         this, SLOT(tableClicked(int,int)));
493     connect(musicTable, SIGNAL(cellClicked(int,int)),
494         this, SLOT(cellClicked(int,int)));
495     musicTable->setSelectionBehavior(QAbstractItemView::SelectRows);
496
497     QHBoxLayout *seekerLayout = new QHBoxLayout;
498     QToolBar* bar2 = new QToolBar;
499     bar2->addAction(volumeAction);
500     seekerLayout->addWidget(bar2);
501     seekerLayout->addWidget(volumeSlider);
502     seekerLayout->addWidget(seekSlider);
503     seekerLayout->addWidget(timeLcd);
504
505     QVBoxLayout *playbackLayout = new QVBoxLayout;
506     volumeSlider->hide ();
507     playbackLayout->addWidget(bar);
508 //    playbackLayout->addStretch();
509 //    playbackLayout->addWidget(volumeSlider);
510 //    playbackLayout->addWidget(volumeLabel);
511
512     QVBoxLayout *seekAndTableLayout = new QVBoxLayout;
513
514     seekAndTableLayout->addWidget(musicTable);
515     seekAndTableLayout->addLayout(seekerLayout);
516
517     QHBoxLayout *mainLayout = new QHBoxLayout;
518     mainLayout->addLayout(seekAndTableLayout);
519     mainLayout->addLayout(playbackLayout);
520
521     QWidget *widget = new QWidget;
522     widget->setLayout(mainLayout);
523
524     setCentralWidget(widget);
525     setWindowTitle("TomAmp");
526     qDebug () << "cucc: " << musicTable->columnWidth(1);
527 }
528
529 void MainWindow::cellClicked(int row, int)
530 {
531     if (mediaObject->state() == Phonon::PlayingState)
532     {
533         int index = plman.indexOf(mediaObject->currentSource());
534         if (index >= 0)
535         {
536             musicTable->selectRow(index);
537         }
538     }
539     else if (row < plman.size())
540     {
541         mediaObject->setCurrentSource(plman.at(row));
542         shuffleList.removeAll(row);
543         shuffleList.insert(0, row);
544         qDebug () << shuffleList;
545     }
546 }
547
548 void MainWindow::setupShuffleList()
549 {
550     QList<int> tmp;
551     int index = plman.indexOf(mediaObject->currentSource());
552     if (index < 0)
553         index = 0;
554     for (int i = 0; i < plman.size(); ++i)
555     {
556         if (i != index)
557             tmp.append(i);
558     }
559     shuffleList.clear();
560     shuffleList.append (index);
561     while (tmp.size ())
562     {
563         int ind = qrand () % tmp.size();
564         shuffleList.append(tmp[ind]);
565         tmp.removeAt(ind);
566     }
567     qDebug () << shuffleList;
568     qDebug () << shuffleList;
569 }
570
571 void MainWindow::savePlaylist ()
572 {
573     QString filename = QFileDialog::getSaveFileName(this, tr("Please select file name"), "", "Playlist Files (*.m3u)");
574     plman.loadPlaylist(filename);
575 }
576
577 void MainWindow::loadPlaylist ()
578 {
579     QString filename = QFileDialog::getOpenFileName(this, tr("Select playlist file to load"), "", "*.m3u");
580     plman.loadPlaylist (filename);
581 }
582
583 void MainWindow::playlistChanged(int from)
584 {
585     while (musicTable->rowCount() > from)
586     {
587         musicTable->removeRow(musicTable->rowCount () - 1);
588     }
589     for (int i = from; i < plman.size (); ++i)
590     {
591         int currentRow = musicTable->rowCount();
592         musicTable->insertRow(currentRow);
593         setRowFromItem (currentRow, plman.getItem(i));
594     }
595     setupShuffleList();
596 }
597
598 void MainWindow::setRowFromItem (int row, const PlaylistItem& item)
599 {
600     if (row >= musicTable->rowCount())
601         return;
602     if (item.artist.isEmpty() && item.title.isEmpty())
603     {
604         QTableWidgetItem *item1 = new QTableWidgetItem(item.uri);
605         item1->setFlags(item1->flags() ^ Qt::ItemIsEditable);
606         musicTable->setItem(row, 1, item1);
607     }
608     else
609     {
610         QTableWidgetItem *item1 = new QTableWidgetItem(item.artist);
611         item1->setFlags(item1->flags() ^ Qt::ItemIsEditable);
612         musicTable->setItem(row, 0, item1);
613         QTableWidgetItem *item2 = new QTableWidgetItem(item.title);
614         item2->setFlags(item2->flags() ^ Qt::ItemIsEditable);
615         musicTable->setItem(row, 1, item2);
616         QTableWidgetItem *item3 = new QTableWidgetItem(item.album);
617         item3->setFlags(item3->flags() ^ Qt::ItemIsEditable);
618         musicTable->setItem(row, 2, item3);
619     }
620 }
621
622 void MainWindow::itemUpdated(int index)
623 {
624     setRowFromItem (index, plman.getItem(index));
625 }