6024d17dbc936159f74c5805cfc8aa1a4e15de58
[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"), isPlaying (false)
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:00");
36     plman.addStringList(settings.value("lastPlaylist").toStringList());
37     setupShuffleList();
38     int curind = settings.value("currentIndex", -1).toInt ();
39     if (curind >= 0)
40         setItem (curind, false);
41     audioOutput->setVolume(settings.value("volume", .5).toReal());
42     QApplication::setWindowIcon(QIcon (QPixmap (":images/tomamp")));
43 }
44
45 MainWindow::~MainWindow()
46 {
47     settings.setValue("shuffle", shuffle);
48     settings.setValue("repeat", repeat);
49     settings.setValue("lastPlaylist", plman.playlistStrings());
50     settings.setValue("volume", audioOutput->volume());
51     settings.setValue("currentIndex", plman.indexOf(mediaObject->currentSource()));
52     for (int i = 0; i < musicTable->columnCount(); ++i)
53     {
54         QString lab = QString ("colWidth_%1").arg (i);
55         settings.setValue(lab, musicTable->columnWidth(i));
56     }
57 }
58
59 void MainWindow::addFiles()
60 {
61     QString folder = settings.value("LastFolder").toString();
62     if (folder.isEmpty())
63         folder = QDesktopServices::storageLocation(QDesktopServices::MusicLocation);
64     QStringList files = QFileDialog::getOpenFileNames(this, tr("Select Files To Add"),
65                     folder, "Music files (*.mp3 *.ogg *.wav *.flac);;Playlists (*.m3u *.pls)");
66
67     if (files.isEmpty())
68         return;
69
70     QString dir = QFileInfo (files[0]).absoluteDir().absolutePath();
71     settings.setValue("LastFolder", dir);
72     QStringList toadd;
73     foreach (QString string, files)
74     {
75         if (string.toLower().endsWith(".pls") || string.toLower().endsWith(".m3u"))
76             plman.addPlaylist(string);
77         else
78             toadd.append (string);
79     }
80     plman.addStringList(toadd);
81 }
82
83 void MainWindow::addFolder()
84 {
85     QString folder = settings.value("LastFolder").toString();
86     if (folder.isEmpty())
87         folder = QDesktopServices::storageLocation(QDesktopServices::MusicLocation);
88     QString dir = QFileDialog::getExistingDirectory(this,
89             tr("Select Directory To Add"),
90             folder);
91
92     if (dir.isEmpty())
93         return;
94
95     settings.setValue("LastFolder", dir);
96
97     QStringList filters;
98     QStringList files = QDir (dir).entryList(filters, QDir::AllDirs);
99     files.removeAll(".");
100     files.removeAll("..");
101     bool recursive = false;
102     if (files.size())
103         recursive = QMessageBox::question(this, "Add all folders", "Subfolders have been detected, add everything?", QMessageBox::Yes | QMessageBox::No) == QMessageBox::Yes;
104     plman.parseAndAddFolder(dir, recursive);
105 }
106
107
108 void MainWindow::addUrl()
109 {
110 #ifdef AVOID_INPUT_DIALOG
111     QString url = "http://war.str3am.com:7970";
112 #else
113     QString url = QInputDialog::getText(this, "Get URL", "Please type in the stream URL");
114 #endif
115     if (url.isEmpty() || !url.toLower().startsWith("http"))
116         return;
117     QStringList toadd;
118     toadd << url;
119     plman.addStringList(toadd);
120 }
121
122
123 void MainWindow::about()
124 {
125     QMessageBox::information(this, tr("About TomAmp v0.1"),
126         tr("TomAmp is a simple playlist-based music player.\n\n"
127         "(c) 2010 Tamas Marki <tmarki@gmail.com>\n\n"
128         "Please send comments and bug reports to the above e-mail address.\n\n"
129         "Icons by http://itweek.deviantart.com/"));
130 }
131
132 void MainWindow::stateChanged(Phonon::State newState, Phonon::State /* oldState */)
133 {
134     switch (newState)
135     {
136         case Phonon::ErrorState:
137             if (mediaObject->errorType() == Phonon::FatalError)
138             {
139 //                QMessageBox::warning(this, tr("Fatal Error"),
140 //                mediaObject->errorString() + mediaObject->currentSource().fileName() + ", " + mediaObject->currentSource().url().toString());
141             }
142             else
143             {
144 //                QMessageBox::warning(this, tr("Error"),
145 //                mediaObject->errorString());
146             }
147             next ();
148             break;
149         case Phonon::PlayingState:
150             setWindowTitle(mediaObject->metaData().value("TITLE") + " - TomAmp");
151             pauseAction->setVisible(true);
152             playAction->setVisible (false);
153             playAction->setEnabled(false);
154             pauseAction->setEnabled(true);
155             stopAction->setEnabled(true);
156             //lastPlayed = plman.indexOf(mediaObject->currentSource());
157             break;
158         case Phonon::StoppedState:
159             setWindowTitle("TomAmp");
160             stopAction->setEnabled(false);
161             playAction->setEnabled(true);
162             pauseAction->setVisible(false);
163             playAction->setVisible(true);
164             pauseAction->setEnabled(false);
165             timeLcd->display("00:00:00");
166             unhighlightRow(plman.indexOf(mediaObject->currentSource()));
167             break;
168         case Phonon::PausedState:
169             pauseAction->setEnabled(false);
170             stopAction->setEnabled(true);
171             pauseAction->setVisible(false);
172             playAction->setVisible(true);
173             playAction->setEnabled(true);
174             break;
175         case Phonon::BufferingState:
176             break;
177         default:
178         ;
179     }
180 }
181
182 void MainWindow::next()
183 {
184     bool wasPlaying = isPlaying;
185     if (mediaObject->state () == Phonon::ErrorState)
186         wasPlaying = true;
187     int index = plman.indexOf(mediaObject->currentSource());
188     if (shuffle)
189     {
190         index = shuffleList.indexOf(plman.indexOf(mediaObject->currentSource())) + 1;
191         while (index < shuffleList.size () && !plman.getItem(shuffleList[index]).playable)
192         {
193             index += 1;
194         }
195         if (index < shuffleList.size ())
196         {
197             setItem (index, wasPlaying);
198         }
199         else if (repeat)
200         {
201             index = 0;
202             while ((index) < shuffleList.size () && !plman.getItem(shuffleList[index]).playable)
203             {
204                 index += 1;
205             }
206             setItem (index, wasPlaying);
207         }
208     }
209     else
210     {
211         index++;
212         while ((index) < plman.size () && !plman.getItem(index).playable)
213         {
214             index += 1;
215         }
216         if (index < plman.size())
217         {
218             setItem (index, wasPlaying);
219         }
220         else if (repeat)
221         {
222             index = 0;
223             while ((index) < plman.size () && !plman.getItem(index).playable)
224             {
225                 index += 1;
226             }
227             setItem (index, wasPlaying);
228         }
229     }
230 }
231
232 void MainWindow::setItem(int i, bool doplay)
233 {
234     if (i < plman.size() && i >= 0)
235     {
236         if (lastPlayed >= 0)
237             unhighlightRow(lastPlayed);
238         if (shuffle)
239         {
240             mediaObject->setCurrentSource(plman.at (shuffleList[i]));
241         }
242         else
243         {
244             mediaObject->setCurrentSource(plman.at(i));
245         }
246     }
247     if (doplay && mediaObject->currentSource().type() != Phonon::MediaSource::Invalid)
248     {
249         play();
250     }
251     else
252         stop ();
253 }
254
255 void MainWindow::previous()
256 {
257     bool wasPlaying = isPlaying;//(mediaObject->state () == Phonon::PlayingState);
258     if (mediaObject->state () == Phonon::ErrorState)
259         wasPlaying = true;
260     int index = plman.indexOf(mediaObject->currentSource());
261     if (shuffle)
262     {
263         index = shuffleList.indexOf(plman.indexOf(mediaObject->currentSource())) - 1;
264         while (index >= 0 && !plman.getItem(shuffleList[index]).playable)
265         {
266             index--;
267         }
268         if (index >= 0)
269         {
270             setItem (index, wasPlaying);
271         }
272         else if (repeat)
273         {
274             index = plman.size () - 1;
275             while (index >= 0 && !plman.getItem(shuffleList[index]).playable)
276             {
277                 index--;
278             }
279             setItem (index, wasPlaying);
280         }
281 /*        if (index < 0)
282             wasPlaying = false;*/
283
284     }
285     else
286     {
287         index--;
288         while ((index) >= 0 && !plman.getItem(index).playable)
289         {
290             index--;
291         }
292         if (index >= 0)
293         {
294             setItem (index, wasPlaying);
295         }
296         else if (repeat)
297         {
298             index = plman.size() - 1;
299             while ((index) >= 0 && !plman.getItem(index).playable)
300             {
301                 index--;
302             }
303             setItem (index, wasPlaying);
304         }
305     }
306 }
307
308 void MainWindow::highlightRow (int i)
309 {
310     for (int j = 0; j < 3; ++j)
311     {
312         QTableWidgetItem* item = musicTable->item(i, j);
313         if (item)
314         {
315             QFont font = item->font();
316             font.setBold(true);
317             font.setItalic(true);
318             item->setFont(font);
319         }
320     }
321 }
322
323 void MainWindow::unhighlightRow (int i)
324 {
325     for (int j = 0; j < 3; ++j)
326     {
327         QTableWidgetItem* item = musicTable->item(i, j);
328         if (item)
329         {
330             QFont font = item->font();
331             font.setBold(false);
332             font.setItalic(false);
333             item->setFont(font);
334         }
335     }
336 }
337
338
339 void MainWindow::tick(qint64 time)
340 {
341     QTime displayTime((time / 3600000), (time / 60000) % 60, (time / 1000) % 60);
342
343     timeLcd->display(displayTime.toString("HH:mm:ss"));
344 }
345
346 void MainWindow::tableClicked(int row, int /* column */)
347 {
348 //    bool wasPlaying = mediaObject->state() == Phonon::PlayingState;
349
350 /*    mediaObject->stop();
351     mediaObject->clearQueue();*/
352
353     if (row >= plman.size())
354         return;
355
356     int index = row;
357     while (index < shuffleList.size () && !plman.getItem(index).playable)
358     {
359         index += 1;
360     }
361     if (plman.size() > index)
362     {
363         if (shuffle)
364             index = shuffleList.indexOf(index);
365         setItem (index, true);
366 //        mediaObject->play();
367     }
368     else
369     {
370         index = 0;
371         while (index < plman.size () && !plman.getItem(index).playable)
372         {
373             index += 1;
374         }
375         if (plman.size() > index)
376         {
377             if (shuffle)
378                 index = shuffleList.indexOf(index);
379             setItem (index, true);
380 //            mediaObject->play();
381         }
382     }
383
384 }
385
386 void MainWindow::sourceChanged(const Phonon::MediaSource &source)
387 {
388     int ind = plman.indexOf(source);
389     highlightRow(ind);
390     unhighlightRow(lastPlayed);
391     lastPlayed = ind;
392     musicTable->selectRow(ind);
393     timeLcd->display("00:00:00");
394 }
395
396
397 void MainWindow::aboutToFinish()
398 {
399     int index = plman.indexOf(mediaObject->currentSource()) + 1;
400     if (shuffle)
401     {
402         index = shuffleList.indexOf(plman.indexOf(mediaObject->currentSource())) + 1;
403         if (index < shuffleList.size ())
404         {
405             mediaObject->enqueue(plman.at (shuffleList[index]));
406         }
407         else if (repeat)
408         {
409             mediaObject->enqueue(plman.at (shuffleList[0]));
410         }
411
412     }
413     else
414     {
415         if (plman.size() > index)
416         {
417             mediaObject->enqueue(plman.at(index));
418         }
419         else if (repeat)
420         {
421             mediaObject->enqueue(plman.at(0));
422         }
423     }
424 }
425
426 void MainWindow::finished()
427 {
428 }
429
430 void MainWindow::setupActions()
431 {
432     playAction = new QAction(QIcon (QPixmap (":images/play")), "", this);
433     playAction->setShortcut(tr("Crl+P"));
434     playAction->setDisabled(true);
435     pauseAction = new QAction(QIcon (QPixmap (":images/pause")), "", this);
436     pauseAction->setShortcut(tr("Ctrl+A"));
437     pauseAction->setDisabled(true);
438     pauseAction->setVisible(false);
439     stopAction = new QAction(QIcon (QPixmap (":images/stop")), "", this);
440     stopAction->setShortcut(tr("Ctrl+S"));
441     stopAction->setDisabled(true);
442     nextAction = new QAction(QIcon (QPixmap (":images/next")), "", this);
443     nextAction->setShortcut(tr("Ctrl+N"));
444     previousAction = new QAction(QIcon (QPixmap (":images/previous")), "", this);
445     previousAction->setShortcut(tr("Ctrl+R"));
446     if (repeat)
447         repeatAction = new QAction(QIcon (QPixmap (":images/repeatActive")), "", this);
448     else
449         repeatAction = new QAction(QIcon (QPixmap (":images/repeat")), "", this);
450     repeatAction->setCheckable(true);
451     repeatAction->setChecked(repeat);
452     repeatAction->setShortcut(tr("Ctrl+I"));
453     if (shuffle)
454         shuffleAction = new QAction(QIcon (QPixmap (":images/shuffleActive")), "", this);
455     else
456         shuffleAction = new QAction(QIcon (QPixmap (":images/shuffle")), "", this);
457     shuffleAction->setCheckable(true);
458     shuffleAction->setChecked(shuffle);
459     shuffleAction->setShortcut(tr("Ctrl+H"));
460     volumeAction = new QAction(QIcon (QPixmap (":images/volume")), "", this);
461     volumeAction->setCheckable(true);
462     volumeAction->setShortcut(tr("Ctrl+V"));
463     addFilesAction = new QAction(tr("Add &File"), this);
464     addFilesAction->setShortcut(tr("Ctrl+F"));
465     addFoldersAction = new QAction(tr("Add F&older"), this);
466     addFoldersAction->setShortcut(tr("Ctrl+O"));
467     addUrlAction = new QAction(tr("Add &Url"), this);
468     addUrlAction->setShortcut(tr("Ctrl+U"));
469     savePlaylistAction = new QAction (tr("Sa&ve Playlist"), this);
470     savePlaylistAction->setShortcut(tr ("Ctrl+V"));
471     loadPlaylistAction = new QAction (tr("&Load Playlist"), this);
472     loadPlaylistAction->setShortcut(tr("Ctrl+L"));
473     clearPlaylistAction = new QAction (tr("&Clear Playlist"), this);
474     clearPlaylistAction->setShortcut(tr("Ctrl+C"));
475     exitAction = new QAction(tr("E&xit"), this);
476     exitAction->setShortcut(tr("Ctrl+X"));
477     aboutAction = new QAction(tr("A&bout"), this);
478     aboutAction->setShortcut(tr("Ctrl+B"));
479     aboutQtAction = new QAction(tr("About &Qt"), this);
480     aboutQtAction->setShortcut(tr("Ctrl+Q"));
481 /*    removeSelected = new QAction (tr("&Delete from playlist"));
482     removeSelected->setShortcut(tr ("Ctrl+D"));*/
483
484     connect(playAction, SIGNAL(triggered()), this, SLOT(play()));
485     connect(pauseAction, SIGNAL(triggered()), mediaObject, SLOT(pause()) );
486     connect(stopAction, SIGNAL(triggered()), this, SLOT(stop()));
487     connect(repeatAction, SIGNAL(triggered()), this, SLOT(repeatToggle()));
488     connect(shuffleAction, SIGNAL(triggered()), this, SLOT(shuffleToggle()));
489     connect(volumeAction, SIGNAL(triggered()), this, SLOT(volumeToggle()));
490
491     connect(addFilesAction, SIGNAL(triggered()), this, SLOT(addFiles()));
492     connect(addFoldersAction, SIGNAL(triggered()), this, SLOT(addFolder()));
493     connect(addUrlAction, SIGNAL(triggered()), this, SLOT(addUrl()));
494     connect (savePlaylistAction, SIGNAL (triggered()), this, SLOT (savePlaylist()));
495     connect (loadPlaylistAction, SIGNAL (triggered()), this, SLOT (loadPlaylist()));
496     connect (clearPlaylistAction, SIGNAL (triggered()), &plman, SLOT (clearPlaylist()));
497     connect (nextAction, SIGNAL(triggered()), this, SLOT(next()));
498     connect (previousAction, SIGNAL(triggered()), this, SLOT(previous()));
499     connect(exitAction, SIGNAL(triggered()), this, SLOT(close()));
500     connect(aboutAction, SIGNAL(triggered()), this, SLOT(about()));
501     connect(aboutQtAction, SIGNAL(triggered()), qApp, SLOT(aboutQt()));
502 //    connect (removeSelected, SIGNAL (triggered()), this, SLOT (removeSelectedItem()));
503 }
504
505 void MainWindow::removeSelectedItem()
506 {
507     if (QMessageBox::question(this, "Confirm remove", "Are you sure you want to remove this item?", QMessageBox::Yes, QMessageBox::No) == QMessageBox::No)
508         return;
509     int row = musicTable->currentRow();
510     if (row >= 0)
511         plman.removeItem(row);
512 }
513
514 void MainWindow::removeAllButSelectedItem()
515 {
516     if (QMessageBox::question(this, "Confirm remove", "Are you sure you want to remove all other items?", QMessageBox::Yes, QMessageBox::No) == QMessageBox::No)
517         return;
518     int row = musicTable->currentRow();
519     if (row >= 0)
520     {
521         QString uri = plman.getItem(row).uri;
522         QStringList lst;
523         lst << uri;
524         plman.clearPlaylist();
525         plman.addStringList(lst);
526     }
527 }
528
529 void MainWindow::repeatToggle ()
530 {
531     repeat = !repeat;
532     settings.setValue("repeat", QVariant (repeat));
533     if (repeat)
534         repeatAction->setIcon(QIcon (QPixmap (":images/repeatActive")));
535     else
536         repeatAction->setIcon(QIcon (QPixmap (":images/repeat")));
537 }
538
539 void MainWindow::shuffleToggle ()
540 {
541     shuffle = !shuffle;
542     settings.setValue("shuffle", QVariant (shuffle));
543     if (shuffle)
544         shuffleAction->setIcon(QIcon (QPixmap (":images/shuffleActive")));
545     else
546         shuffleAction->setIcon(QIcon (QPixmap (":images/shuffle")));
547 }
548
549 void MainWindow::volumeToggle ()
550 {
551     volumeSlider->setVisible(volumeAction->isChecked());
552 }
553
554 void MainWindow::play()
555 {
556     mediaObject->play();
557     lastPlayed = plman.indexOf(mediaObject->currentSource());
558     highlightRow(lastPlayed);
559     isPlaying = true;
560 }
561
562 void MainWindow::stop()
563 {
564     mediaObject->stop();
565     isPlaying = false;
566 }
567
568
569 void MainWindow::setupMenus()
570 {
571     QMenu *fileMenu = menuBar()->addMenu(tr("&File"));
572     fileMenu->addAction(addFilesAction);
573     fileMenu->addAction(addFoldersAction);
574     fileMenu->addAction(addUrlAction);
575     fileMenu->addSeparator();
576     fileMenu->addAction(savePlaylistAction);
577     fileMenu->addAction(loadPlaylistAction);
578     fileMenu->addAction(clearPlaylistAction);
579 //    fileMenu->addAction(exitAction);
580
581     QMenu *aboutMenu = menuBar()->addMenu(tr("&Help"));
582     aboutMenu->addAction(aboutAction);
583     aboutMenu->addAction(aboutQtAction);
584 }
585
586 void MainWindow::setupUi()
587 {
588     QToolBar *bar = new QToolBar;
589
590     bar->setOrientation(Qt::Vertical);
591     bar->setStyleSheet("padding:7px");
592     //bar->addAction(volumeAction);
593
594     seekSlider = new Phonon::SeekSlider(this);
595     seekSlider->setMediaObject(mediaObject);
596
597     volumeSlider = new Phonon::VolumeSlider(this);
598     volumeSlider->setAudioOutput(audioOutput);
599     volumeSlider->setSizePolicy(QSizePolicy::Maximum, QSizePolicy::Maximum);
600     volumeSlider->setOrientation(Qt::Horizontal);
601     volumeSlider->setMuteVisible(false);
602 //    volumeAddedAction = bar->addWidget(volumeSlider);
603 //    volumeAddedAction->setVisible(false);
604     bar->addAction(playAction);
605     bar->addAction(pauseAction);
606     bar->addAction(stopAction);
607     bar->addAction(repeatAction);
608     bar->addAction(shuffleAction);
609     bar->addAction(nextAction);
610     bar->addAction(previousAction);
611
612     contextMenu = new QMenu (this);
613     removeSelected = contextMenu->addAction(tr ("Remove selected"));
614     removeAllButSelected = contextMenu->addAction(tr("Remove all but selected"));
615     connect (removeSelected, SIGNAL (triggered()), this, SLOT (removeSelectedItem()));
616     connect (removeAllButSelected, SIGNAL (triggered()), this, SLOT (removeAllButSelectedItem()));
617
618
619     timeLcd = new QLCDNumber;
620
621     QStringList headers;
622     headers << tr("Artist") << tr("Title") << tr("Album") << "Controls";
623
624     musicTable = new QTableWidget(0, 4);
625     musicTable->setHorizontalHeaderLabels(headers);
626     musicTable->setSelectionMode(QAbstractItemView::SingleSelection);
627     musicTable->setSelectionBehavior(QAbstractItemView::SelectRows);
628     connect(musicTable, SIGNAL(cellDoubleClicked(int,int)),
629         this, SLOT(tableClicked(int,int)));
630     connect(musicTable, SIGNAL(cellClicked(int,int)),
631         this, SLOT(cellClicked(int,int)));
632 /*    for (int i = 0; i < 3; ++i)
633     {
634         if (!musicTable->horizontalHeaderItem(i))
635             continue;
636         musicTable->horizontalHeaderItem(i)->setBackgroundColor(QColor (128, 128, 255));;
637         musicTable->horizontalHeaderItem(i)->setForeground(QColor (255, 255, 255));
638     }*/
639     for (int i = 0; i < musicTable->columnCount(); ++i)
640     {
641         QString lab = QString ("colWidth_%1").arg (i);
642         int val = settings.value(lab, 0).toInt();
643         if (val)
644             musicTable->setColumnWidth(i, val);
645 //        settings.setValue(lab, musicTable->columnWidth(i));
646     }
647
648
649     QHBoxLayout *seekerLayout = new QHBoxLayout;
650     QToolBar* bar2 = new QToolBar;
651     bar2->addAction(volumeAction);
652     seekerLayout->addWidget(bar2);
653     seekerLayout->addWidget(volumeSlider);
654     seekerLayout->addWidget(seekSlider);
655     seekerLayout->addWidget(timeLcd);
656
657     QVBoxLayout *playbackLayout = new QVBoxLayout;
658     volumeSlider->hide ();
659     playbackLayout->addWidget(bar);
660
661     QVBoxLayout *seekAndTableLayout = new QVBoxLayout;
662
663     seekAndTableLayout->addWidget(musicTable);
664     seekAndTableLayout->addLayout(seekerLayout);
665
666     QHBoxLayout *mainLayout = new QHBoxLayout;
667     mainLayout->addLayout(seekAndTableLayout);
668     mainLayout->addLayout(playbackLayout);
669
670     QWidget *widget = new QWidget;
671     widget->setLayout(mainLayout);
672
673     setCentralWidget(widget);
674     setWindowTitle("TomAmp");
675 }
676
677 void MainWindow::cellClicked(int /*row*/, int)
678 {
679 }
680
681 void MainWindow::contextMenuEvent (QContextMenuEvent*e)
682 {
683     if (!childAt (e->pos()))
684         return;
685     if (childAt (e->pos())->parentWidget() != musicTable)
686         return;
687     contextMenu->popup(e->globalPos());
688 }
689
690
691 void MainWindow::setupShuffleList()
692 {
693     QList<int> tmp;
694     int index = plman.indexOf(mediaObject->currentSource());
695     if (index < 0)
696         index = 0;
697     for (int i = 0; i < plman.size(); ++i)
698     {
699         if ((i != index))
700             tmp.append(i);
701     }
702     shuffleList.clear();
703     shuffleList.append (index);
704     while (tmp.size ())
705     {
706         int ind = qrand () % tmp.size();
707         shuffleList.append(tmp[ind]);
708         tmp.removeAt(ind);
709     }
710 }
711
712 void MainWindow::savePlaylist ()
713 {
714     QString filename = QFileDialog::getSaveFileName(this, tr("Please select file name"), "", "Playlist Files (*.m3u *.pls)");
715     if (filename.isEmpty())
716         return;
717     plman.savePlaylist(filename);
718 }
719
720 void MainWindow::loadPlaylist ()
721 {
722     QString filename = QFileDialog::getOpenFileName(this, tr("Select playlist file to load"), "", "*.m3u *.pls");
723     if (filename.isEmpty())
724         return;
725     plman.loadPlaylist (filename);
726 }
727
728 void MainWindow::playlistChanged(int from)
729 {
730     while (musicTable->rowCount() > from)
731     {
732         musicTable->removeRow(musicTable->rowCount () - 1);
733     }
734     int firstGood = -1;
735     for (int i = from; i < plman.size (); ++i)
736     {
737         if (firstGood < 0 && plman.getItem (i).playable)
738             firstGood = i;
739         int currentRow = musicTable->rowCount();
740         musicTable->insertRow(currentRow);
741         setRowFromItem (currentRow, plman.getItem(i));
742     }
743 /*    if (plman.indexOf(mediaObject->currentSource()) < 0)
744     {
745         setItem (firstGood, false);
746     }*/
747     setupShuffleList();
748 }
749
750 void MainWindow::setRowFromItem (int row, const PlaylistItem& item)
751 {
752     if (row >= musicTable->rowCount())
753         return;
754     if (item.artist.isEmpty() && item.title.isEmpty())
755     {
756         QTableWidgetItem *item1 = new QTableWidgetItem(item.uri);
757         item1->setFlags(item1->flags() ^ Qt::ItemIsEditable);
758         musicTable->setItem(row, 1, item1);
759     }
760     else
761     {
762         QTableWidgetItem *item1 = new QTableWidgetItem(item.artist);
763         item1->setFlags(item1->flags() ^ Qt::ItemIsEditable);
764         musicTable->setItem(row, 0, item1);
765         QTableWidgetItem *item2 = new QTableWidgetItem(item.title);
766         item2->setFlags(item2->flags() ^ Qt::ItemIsEditable);
767         musicTable->setItem(row, 1, item2);
768         QTableWidgetItem *item3 = new QTableWidgetItem(item.album);
769         item3->setFlags(item3->flags() ^ Qt::ItemIsEditable);
770         musicTable->setItem(row, 2, item3);
771     }
772     qDebug () << "Widget: " << musicTable->cellWidget(row, 3);
773
774     if (!musicTable->cellWidget(row, 3))
775     {
776         QToolBar* bar = new QToolBar;
777         QPushButton* up = new QPushButton;
778         up->setText("up");
779         up->setSizePolicy(QSizePolicy::Minimum, QSizePolicy::Minimum);
780         bar->setProperty("row", row);
781         bar->addWidget(up);
782         musicTable->setCellWidget(row, 3, bar);
783         connect (up, SIGNAL (clicked ()),  this, SLOT (buttonUp ()));
784     }
785 }
786
787 void MainWindow::buttonUp()
788 {
789     int i = sender()->parent()->property("row").toInt();
790     qDebug () << "Presses up on " << i;
791     if (i)
792     {
793         plman.moveItemUp(i);
794         setRowFromItem (i, plman.getItem(i));
795         setRowFromItem (i - 1, plman.getItem(i - 1));
796         musicTable->cellWidget(i, 3)->setProperty("row", i);
797         musicTable->cellWidget(i - 1, 3)->setProperty("row", i - 1);
798         musicTable->selectRow(i - 1);
799     }
800 }
801
802 void MainWindow::itemUpdated(int index)
803 {
804     if (plman.indexOf(mediaObject->currentSource()) < 0 && plman.getItem (index).playable)
805     {
806         setItem (index, false);
807     }
808     setRowFromItem (index, plman.getItem(index));
809     if (plman.indexOf(mediaObject->currentSource()) == index)
810     {
811         if (shuffle) index = shuffleList.indexOf(index);
812         setItem (index, false);
813     }
814 }