Fix for Bug [#6295] Application polls vlc server even when the UI is not visible...
[vlc-remote] / src / playermainwindow.cpp
index 26ea30e..a2de15d 100644 (file)
@@ -15,7 +15,7 @@
   *   Free Software Foundation, Inc.,
   *   51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.
   */
-  #include <QDebug>
+  //#include <QDebug>
   #include <QTime>
   #include <QtGui>
   #include "playermainwindow.h"
   #include "configdialog.h"
   #include "aboutdialog.h"
   #include "accountdialog.h"
+  #include "settingsdialog.h"
   #include "appsettings.h"
+#if defined(Q_WS_S60) || defined(Q_WS_MAEMO_5)
+  #include <QMaemo5InformationBox>
+  #include <mce/dbus-names.h>
+  #include <mce/mode-names.h>
+  #include <QDBusConnection>
+  #include <QDBusMessage>
+  #include <QDBusInterface>
+#endif
+#include <QMessageBox>
+
+#if defined(Q_WS_S60) || defined(Q_WS_MAEMO_5)
+QDBusConnection PlayerMainWindow::dBusConnection = QDBusConnection::systemBus();
+QDBusInterface* PlayerMainWindow::dBusInterface = new QDBusInterface(MCE_SERVICE, MCE_REQUEST_PATH,
+                                   MCE_REQUEST_IF, dBusConnection);
+#endif
 
   PlayerMainWindow::PlayerMainWindow(QWidget *parent) :
          QMainWindow(parent),
@@ -32,7 +48,7 @@
       ui->setupUi(this);
       setWindowTitle("Vlc remote");
 
-
+      mIsFirstStatusCall = true;
 
       mTimer = new QTimer(this);
       mNetManager = new QNetworkAccessManager(this);
@@ -66,6 +82,9 @@
 
 
   #if defined(Q_WS_S60) || defined(Q_WS_MAEMO_5)
+      // Handle screen state on / off
+      dBusConnection.connect(MCE_SERVICE, MCE_SIGNAL_PATH, MCE_SIGNAL_IF,
+                                 MCE_DISPLAY_SIG, this, SLOT(displayStateChanged(const QDBusMessage &)));
 
       mPlayListMainWindow->setParent(this);
       mPlayListMainWindow->setAttribute(Qt::WA_Maemo5StackedWindow, true);
   #endif
 
       connect(mTimer,SIGNAL(timeout()),this,SLOT(askStatus()));
+      connect(ui->actionSettings,SIGNAL(triggered()),this,SLOT(showSettings()));
       connect(ui->actionConfiguration,SIGNAL(triggered()),this,SLOT(showConfig()));
       connect(ui->actionAbout,SIGNAL(triggered()),this,SLOT(showAbout()));
-      connect(ui->actionPortrait,SIGNAL(triggered()),this,SLOT(setPortrait()));
-      connect(ui->actionLandscape,SIGNAL(triggered()),this,SLOT(setLandscape()));
-      connect(ui->actionAutoRotate,SIGNAL(triggered()),this,SLOT(setAutoRotate()));
+      connect(ui->actionFavourites,SIGNAL(triggered()),this,SLOT(showFavourites()));
+      //connect(ui->actionPortrait,SIGNAL(triggered()),this,SLOT(setPortrait()));
+      //connect(ui->actionLandscape,SIGNAL(triggered()),this,SLOT(setLandscape()));
+      //connect(ui->actionAutoRotate,SIGNAL(triggered()),this,SLOT(setAutoRotate()));
       connect(ui->playlistButton,SIGNAL(clicked()),mPlayListMainWindow,SLOT(show()));
       connect(ui->playlistButton,SIGNAL(clicked()),mPlayListMainWindow,SLOT(showPlayList()));
       connect(ui->browseButton,SIGNAL(clicked()),mBrowserMainWindow,SLOT(show()));
 
 
       // check if last used connection is still valid or showConfig
-      QSettings settings;
-      QString last_ip = AccountDialog::currentIp();
-      if (!last_ip.isNull() && !last_ip.isEmpty()) {
-          QTcpSocket * socket = new QTcpSocket;
-          if(last_ip.contains(":"))
-          {
-              QStringList hostSplit = last_ip.split(":");
-              QString ip   = hostSplit.at(0);
-              QString port = hostSplit.at(1);
-              socket->connectToHost(ip,port.toInt());
-          }
-          else {
-              socket->connectToHost(last_ip,8080);
+
+      // check for network
+      if (AppSettings::isConnected()) {
+          QSettings settings;
+          QString last_ip = AppSettings::getCurrentIp(); // AccountDialog::currentIp();
+          if (!last_ip.isNull() && !last_ip.isEmpty()) {
+              QTcpSocket * socket = new QTcpSocket;
+              if(last_ip.contains(":"))
+              {
+                  QStringList hostSplit = last_ip.split(":");
+                  QString ip   = hostSplit.at(0);
+                  QString port = hostSplit.at(1);
+                  socket->connectToHost(ip,port.toInt());
+              }
+              else {
+                  socket->connectToHost(last_ip,8080);
+              }
+              if (!socket->waitForConnected(AppSettings::getConnectionTimeout())) {
+                     showConfig();
+                 }
+              else {
+                  mIp= last_ip;
+
+                 mPlayListMainWindow->init();
+                 mBrowserMainWindow->init();
+                 mTimer->start(AppSettings::getStatusPollTimeout());
+                 askStatus();
+              }
+              delete socket;
           }
-          if (!socket->waitForConnected(1000)) {
-                 showConfig();
-             }
           else {
-              mIp= last_ip;
-
-             mPlayListMainWindow->init();
-             mBrowserMainWindow->init();
-             mTimer->start(5000);
-             askStatus();
+            showConfig();
           }
-          delete socket;
       }
       else {
-        showConfig();
+#if defined(Q_WS_S60) || defined(Q_WS_MAEMO_5)
+        QMaemo5InformationBox::information(this, tr("Network unavailable!"), QMaemo5InformationBox::DefaultTimeout);
+#endif
+          showConfig();
       }
-
-
   }
   
 
       }
   }
 
+#if defined(Q_WS_S60) || defined(Q_WS_MAEMO_5)
+  void PlayerMainWindow::displayStateChanged(const QDBusMessage &message)
+  {
+      QString state = message.arguments().at(0).toString();
+      if (!state.isEmpty()) {
+          if (state == MCE_DISPLAY_ON_STRING) {
+              mTimer->start(AppSettings::getStatusPollTimeout());
+          }
+          else if (state == MCE_DISPLAY_OFF_STRING) {
+              mTimer->stop();
+          }
+      }
+  }
+#endif
+
   void PlayerMainWindow::showFavourites() {
       mFavouritesMainWindow->show();
       mFavouritesMainWindow->init();
   }
 
+  void PlayerMainWindow::updateFromSettings()
+  {
+    #if defined(Q_WS_S60) || defined(Q_WS_MAEMO_5)
+    switch (AppSettings::getOrientation()) {
+      case LANDSCAPE:
+          this->setAttribute(Qt::WA_Maemo5LandscapeOrientation, true);
+          break;
+      case PORTRAIT:
+          this->setAttribute(Qt::WA_Maemo5PortraitOrientation, true);
+          break;
+      case AUTO_ROTATE:
+          this->setAttribute(Qt::WA_Maemo5AutoOrientation, true);
+          break;
+    }
+    #endif
+    if (AppSettings::getShowAlbumArt()) {
+        this->mIsFirstStatusCall = true;
+    }
+    mTimer->start(AppSettings::getStatusPollTimeout());
+  }
+
   void PlayerMainWindow::setPortrait()
   {
     #if defined(Q_WS_S60) || defined(Q_WS_MAEMO_5)
       mNetManager->get(QNetworkRequest(QUrl("http://"+mIp+"/requests/status.xml?command=seek&val="+QString::number(value)+"%25")));
   }
 
+  void PlayerMainWindow::showSettings()
+  {
+    SettingsDialog * dialog = new SettingsDialog(this);
+    connect(dialog, SIGNAL(closeSignal()), this, SLOT(updateFromSettings()));
+    dialog->exec();
+  }
   void PlayerMainWindow::showConfig()
   {
       mTimer->stop();
-      AccountDialog * dialog = new AccountDialog;
-      dialog->exec();
-     
-       mIp= AccountDialog::currentIp();
+      // check for network
+      if (AppSettings::isConnected()) {
+          AccountDialog * dialog = new AccountDialog(this);
+          dialog->exec();
+
+          mIp= AppSettings::getCurrentIp(); //AccountDialog::currentIp();
 
-      mPlayListMainWindow->init();
-      mBrowserMainWindow->init();
-      mTimer->start(5000);
-      askStatus();
+          mPlayListMainWindow->init();
+          mBrowserMainWindow->init();
+          mTimer->start(AppSettings::getStatusPollTimeout());
+          askStatus();
+      }
+      else {
+#if defined(Q_WS_S60) || defined(Q_WS_MAEMO_5)
+        QMaemo5InformationBox::information(this, tr("Network unavailable!"), QMaemo5InformationBox::DefaultTimeout);
+#endif
+        QTimer::singleShot(AppSettings::getRetryNetworkTimeout(), this, SLOT(showConfig()));
+      }
   }
   void PlayerMainWindow::showAbout()
   {
 
   void PlayerMainWindow::askStatus()
   {
-      //qDebug() << "Status requested. at:" << QTime::currentTime().toString("hh::mm:ss");
-      QNetworkReply * reply =  mNetManager->get(QNetworkRequest(QUrl("http://"+mIp+"/requests/status.xml")));
-      connect(reply,SIGNAL(readyRead()),this,SLOT(parseXmlStatus()));
+      if (AppSettings::isConnected()) {
+          QNetworkReply * reply =  mNetManager->get(QNetworkRequest(QUrl("http://"+mIp+"/requests/status.xml")));
+          connect(reply,SIGNAL(readyRead()),this,SLOT(parseXmlStatus()));
+          connect(reply,SIGNAL(error(QNetworkReply::NetworkError)),this,SLOT(error(QNetworkReply::NetworkError)));
+      }
+      else {
+        showConfig(); // this will handle stopping and restarting the timer.
+      }
   }
 
   void PlayerMainWindow::parseXmlStatus()
       doc.setContent(reply->readAll());
       delete reply;
       QDomElement docElem = doc.documentElement();
+      VlcStatusState oldState = mCurrentStatus.state;
       // Get the raw values
       int volume = docElem.namedItem("volume").toElement().text().toInt();
       int length = docElem.namedItem("length").toElement().text().toInt();
       // now would be a good time to work out if we are a new track / file or not.
       // key if we are going to look for album art later
       // for now we check length and title this will require further examination later
-      mCurrentStatus.newtrack = true;
-      if (mCurrentStatus.length == length && !mCurrentStatus.title.isNull() && 0 == QString::compare(mCurrentStatus.title, title)) {
-        mCurrentStatus.newtrack = false;
-      }
-      mCurrentStatus.volume = volume;
-      mCurrentStatus.length = length;
-      mCurrentStatus.time = time;
-      mCurrentStatus.position = position;
-      mCurrentStatus.random = (1 == random);
-      mCurrentStatus.loop = (1 == loop);
-      mCurrentStatus.repeat = (1 == repeat);
-      mCurrentStatus.title = title;
-      mCurrentStatus.artist = artist;
-      mCurrentStatus.album = album;
-      mCurrentStatus.nowplaying = now_playing;
-      mCurrentStatus.hasart = (!art_url.isNull() && !art_url.isEmpty());
       if (!state.isNull() && !state.isEmpty()) {
           if (0 == QString::compare("playing", state, Qt::CaseInsensitive)) {
             mCurrentStatus.state = PLAYING;
           }
           else {
             mCurrentStatus.state = UNKNOWN;
+            mIsFirstStatusCall = true;
           }
       }
       else {
           mCurrentStatus.state = UNKNOWN;
+          mIsFirstStatusCall = true;
+      }
+      mCurrentStatus.newtrack = true;
+      if (mIsFirstStatusCall) {
+          mIsFirstStatusCall = false;
+          mCurrentStatus.newtrack = true; // unneeded but self-documenting
       }
+      else if (STOP == oldState && STOP != mCurrentStatus.state) {
+          mCurrentStatus.newtrack = true; // unneeded but self-documenting
+      }
+      else {
+          if ( (0 == mCurrentStatus.length || STOP == mCurrentStatus.state) // stopped or null
+                  || // same track as current playing
+               (mCurrentStatus.length == length && !mCurrentStatus.title.isNull() && !title.isNull() && 0 == QString::compare(mCurrentStatus.title, title)) ){
+            mCurrentStatus.newtrack = false;
+          }
+      }
+      mCurrentStatus.volume = volume;
+      mCurrentStatus.length = length;
+      mCurrentStatus.time = time;
+      mCurrentStatus.position = position;
+      mCurrentStatus.random = (1 == random);
+      mCurrentStatus.loop = (1 == loop);
+      mCurrentStatus.repeat = (1 == repeat);
+      mCurrentStatus.title = title;
+      mCurrentStatus.artist = artist;
+      mCurrentStatus.album = album;
+      mCurrentStatus.nowplaying = now_playing;
+      mCurrentStatus.hasart = (!art_url.isNull() && !art_url.isEmpty());
       // What's our mute status?
       if (0 < mCurrentStatus.volume) {
           this->mVolume = mCurrentStatus.volume;
           ui->playpauseButton->setIcon(QIcon::fromTheme("camera_playback"));
       }
 
-      if (mCurrentStatus.newtrack) {
+      if (STOP == mCurrentStatus.state || !AppSettings::getShowAlbumArt()) {
+          ui->labelArtPortrait->setVisible(false);
+          ui->labelArtLandscape->setVisible(false);
+      }
+
+      if (mCurrentStatus.newtrack && STOP != mCurrentStatus.state) {
           // potential actions:
           //   rebuild display layout
           //   retrieve album art
-          mHasImage = false;
-          QTimer::singleShot(500, mPlayListMainWindow, SLOT(requestPlayList()));
+          if (AppSettings::getShowAlbumArt()) {
+              mHasImage = false;
+              QTimer::singleShot(AppSettings::getRetrieveArtTimeout(), mPlayListMainWindow, SLOT(requestPlayList()));
+          }
       }
       // Update the buttons on the playlist window
       if (NULL != this->mPlayListMainWindow) {
       }
   }
   void PlayerMainWindow::error(QNetworkReply::NetworkError code) {
-      qDebug() << "Error Code: " << code;
+      Q_UNUSED(code);
+      //qDebug() << "Error Code: " << code;
   }
   void PlayerMainWindow::readReady() {
     QNetworkReply * reply = qobject_cast<QNetworkReply*>(sender());
     delete reply;
   }
   void PlayerMainWindow::getCoverArt(int id) {
-      qDebug() << "getCoverArt id=!" << id;
     mResponse.clear();
     QNetworkReply * reply =  mNetManager->get(QNetworkRequest(QUrl("http://"+mIp+"/art?id=" + QString::number(id))));
     connect(reply,SIGNAL(readyRead()),this,SLOT(readReady()));
     QPixmap* image = new QPixmap();
     if (image->loadFromData(data)) {
         mHasImage = true;
-        ui->labelArtLandscape->setPixmap(image->scaledToHeight(120, Qt::SmoothTransformation));
+        ui->labelArtLandscape->setPixmap(image->scaledToHeight(160, Qt::SmoothTransformation));
         ui->labelArtPortrait->setPixmap(image->scaledToHeight(310, Qt::SmoothTransformation));
         if (mIsLandscape) {
             ui->labelArtPortrait->setVisible(false);
         }
     }
     else {
-        qDebug() << "image load failed!";
-        qDebug() << "data.length" << data.length();
         ui->labelArtPortrait->setVisible(false);
         ui->labelArtLandscape->setVisible(false);
     }
   }
   void PlayerMainWindow::setCoverArtFromPixmap(QPixmap image) {
     mHasImage = true;
-    ui->labelArtLandscape->setPixmap(image.scaledToHeight(120, Qt::SmoothTransformation));
-    ui->labelArtPortrait->setPixmap(image.scaledToHeight(320, Qt::SmoothTransformation));
+    ui->labelArtLandscape->setPixmap(image.scaledToHeight(160, Qt::SmoothTransformation));
+    ui->labelArtPortrait->setPixmap(image.scaledToHeight(310, Qt::SmoothTransformation));
     if (mIsLandscape) {
         ui->labelArtPortrait->setVisible(false);
         ui->labelArtLandscape->setVisible(true);
         ui->labelArtPortrait->setVisible(true);
     }
   }
+  void PlayerMainWindow::closeEvent(QCloseEvent * event) {
+      if (!AppSettings::getAlertOnClose() || PLAYING != mCurrentStatus.state) {
+          event->accept();
+      }
+      else { // handle alert
+          if (QMessageBox::Yes == QMessageBox::question(this
+                                                       , tr("Really quit?")
+                                                       , tr("You currently have media playing on your remote machine. Are you sure you wish to quit vlc-remote?")
+                                                       , QMessageBox::Yes | QMessageBox::No
+                                                       , QMessageBox::No)) {
+            event->accept();
+          }
+          else {
+            event->ignore();
+          }
+      }
+  }