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