Power save mode review and iteration.
[situare] / src / engine / engine.cpp
index 36fdeb1..f5358c8 100644 (file)
@@ -23,6 +23,7 @@
  */
 
 #include <QMessageBox>
+#include <QNetworkReply>
 
 #include "common.h"
 #include "facebookservice/facebookauthentication.h"
 #include "map/mapengine.h"
 #include "situareservice/situareservice.h"
 #include "ui/mainwindow.h"
+#include "mce.h"
 #include <cmath>
 
 #include "engine.h"
 
+
 const QString SETTINGS_GPS_ENABLED = "GPS_ENABLED"; ///< GPS setting
 const QString SETTINGS_AUTO_CENTERING_ENABLED = "AUTO_CENTERING_ENABLED";///< Auto centering setting
 const int DEFAULT_ZOOM_LEVEL_WHEN_GPS_IS_AVAILABLE = 12;  ///< Default zoom level when GPS available
@@ -45,14 +48,14 @@ SituareEngine::SituareEngine(QMainWindow *parent)
     : QObject(parent),
       m_autoCenteringEnabled(false),
       m_automaticUpdateFirstStart(true),
-      m_loggedIn(false),
+      m_automaticUpdateRequest(false),
+      m_userMoved(false),
       m_automaticUpdateIntervalTimer(0),
-      m_lastUpdatedGPSPosition(QPointF()),
-      m_userMoved(false)
-{
+      m_lastUpdatedGPSPosition(QPointF())
+{    
     qDebug() << __PRETTY_FUNCTION__;
     m_ui = new MainWindow;
-    m_ui->updateItemVisibility(m_loggedIn);
+    m_ui->updateItemVisibility();
 
     // build MapEngine
     m_mapEngine = new MapEngine(this);
@@ -60,7 +63,6 @@ SituareEngine::SituareEngine(QMainWindow *parent)
 
     // build GPS
     m_gps = new GPSPosition(this);
-    m_gps->setMode(GPSPosition::Default);
 
     // build SituareService
     m_situareService = new SituareService(this);
@@ -87,6 +89,10 @@ SituareEngine::SituareEngine(QMainWindow *parent)
     connect(this, SIGNAL(friendsLocationsReady(QList<User*>&)),
             m_mapEngine, SIGNAL(friendsLocationsReady(QList<User*>&)));
 
+    m_automaticUpdateIntervalTimer = new QTimer(this);
+    connect(m_automaticUpdateIntervalTimer, SIGNAL(timeout()),
+            this, SLOT(startAutomaticUpdate()));
+
     // signals connected, now it's time to show the main window
     // but init the MapEngine before so starting location is set
     m_mapEngine->init();
@@ -94,11 +100,11 @@ SituareEngine::SituareEngine(QMainWindow *parent)
 
     m_facebookAuthenticator->start();
 
+    m_gps->setMode(GPSPosition::Default);
     initializeGpsAndAutocentering();
 
-    m_automaticUpdateIntervalTimer = new QTimer(this);
-    connect(m_automaticUpdateIntervalTimer, SIGNAL(timeout()),
-            this, SLOT(automaticUpdateIntervalTimerTimeout()));
+    m_mce = new MCE(this);
+    connect(m_mce, SIGNAL(displayStateChanged(bool)), this, SLOT(displayStateChanged(bool)));
 }
 
 SituareEngine::~SituareEngine()
@@ -108,22 +114,10 @@ SituareEngine::~SituareEngine()
     delete m_ui;
 
     QSettings settings(DIRECTORY_NAME, FILE_NAME);
-    qDebug() << __PRETTY_FUNCTION__ << m_autoCenteringEnabled;
     settings.setValue(SETTINGS_GPS_ENABLED, m_gps->isRunning());
     settings.setValue(SETTINGS_AUTO_CENTERING_ENABLED, m_autoCenteringEnabled);
 }
 
-void SituareEngine::automaticUpdateIntervalTimerTimeout()
-{
-    qDebug() << __PRETTY_FUNCTION__;
-
-    if (m_gps->isRunning() && m_userMoved) {
-//        requestUpdateLocation();
-        qWarning() << __PRETTY_FUNCTION__ << "requestUpdateLocation()";
-        m_userMoved = false;
-    }
-}
-
 void SituareEngine::changeAutoCenteringSetting(bool enabled)
 {
     qDebug() << __PRETTY_FUNCTION__;
@@ -140,6 +134,16 @@ void SituareEngine::disableAutoCentering()
     m_ui->buildInformationBox(tr("Auto centering disabled"));
 }
 
+void SituareEngine::displayStateChanged(bool enabled)
+{
+    qDebug() << __PRETTY_FUNCTION__;
+
+    m_gps->enablePowerSave(!enabled);
+
+    if (m_autoCenteringEnabled)
+        enableAutoCentering(enabled);
+}
+
 void SituareEngine::enableAutoCentering(bool enabled)
 {
     qDebug() << __PRETTY_FUNCTION__;
@@ -155,17 +159,31 @@ void SituareEngine::enableGPS(bool enabled)
 {
     qDebug() << __PRETTY_FUNCTION__;
 
-    m_ui->setGPSButtonEnabled(enabled);
-    m_mapEngine->setGPSEnabled(enabled);
+    m_ui->setOwnLocationCrosshairVisibility(!enabled);
 
-    if (enabled) {
-        m_gps->start();
-        enableAutoCentering(m_autoCenteringEnabled);
-        m_gps->requestLastPosition();
+    if (m_gps->isInitialized()) {
+        m_ui->setGPSButtonEnabled(enabled);
+        m_mapEngine->setGPSEnabled(enabled);
+
+        if (enabled && !m_gps->isRunning()) {
+            m_gps->start();
+            enableAutoCentering(m_autoCenteringEnabled);
+            m_gps->requestLastPosition();
+
+            if(m_ui->loginState())
+                m_ui->readAutomaticLocationUpdateSettings();
+        }
+        else if (!enabled && m_gps->isRunning()) {
+            m_gps->stop();
+            enableAutoCentering(false);
+            enableAutomaticLocationUpdate(false);
+        }
     }
     else {
-        m_gps->stop();
-        enableAutoCentering(false);
+        if (enabled)
+            m_ui->buildInformationBox(tr("Unable to start GPS"));
+        m_ui->setGPSButtonEnabled(false);
+        m_mapEngine->setGPSEnabled(false);
     }
 }
 
@@ -173,48 +191,102 @@ void SituareEngine::enableAutomaticLocationUpdate(bool enabled, int updateInterv
 {
     qDebug() << __PRETTY_FUNCTION__;
 
-    bool accepted = false;
-
-    if (m_automaticUpdateFirstStart && enabled) {
-        accepted = m_ui->showEnableAutomaticUpdateLocationDialog(
+    //Show automatic update confirmation dialog
+    if (m_automaticUpdateFirstStart && m_gps->isRunning() && enabled) {
+        m_ui->showEnableAutomaticUpdateLocationDialog(
                 tr("Do you want to enable automatic location update with %1 min update interval?")
                 .arg(updateIntervalMsecs/1000/60));
         m_automaticUpdateFirstStart = false;
-        m_ui->automaticLocationUpdateEnabled(accepted);
-    }
-    else {
-        accepted = true;
-    }
+    } else {
+        if (enabled && m_gps->isRunning()) {
+            m_ui->buildInformationBox(tr("Automatic location update enabled"));
+            if (updateIntervalMsecs < MIN_UPDATE_INTERVAL_MSECS)
+                m_automaticUpdateIntervalTimer->setInterval(MIN_UPDATE_INTERVAL_MSECS);
+            else
+                m_automaticUpdateIntervalTimer->setInterval(updateIntervalMsecs);
+
+            connect(m_gps, SIGNAL(position(QPointF,qreal)),
+                    this, SLOT(requestAutomaticUpdateIfMoved(QPointF)));
 
-    if (accepted) {
+            m_automaticUpdateIntervalTimer->start();
 
-        if (m_automaticUpdateIntervalTimer) {
-            if (enabled && m_gps->isRunning()) {
-                if (updateIntervalMsecs < MIN_UPDATE_INTERVAL_MSECS)
-                    m_automaticUpdateIntervalTimer->setInterval(MIN_UPDATE_INTERVAL_MSECS / 60);
-                else
-                    m_automaticUpdateIntervalTimer->setInterval(updateIntervalMsecs / 60);
+        } else {
+            disconnect(m_gps, SIGNAL(position(QPointF,qreal)),
+                    this, SLOT(requestAutomaticUpdateIfMoved(QPointF)));
 
-                m_automaticUpdateIntervalTimer->start();
-            }
-            else {
-                m_automaticUpdateIntervalTimer->stop();
-            }
+            m_automaticUpdateIntervalTimer->stop();
         }
     }
 }
 
-void SituareEngine::error(const QString &error)
+void SituareEngine::error(const int error)
 {
-    qDebug() << __PRETTY_FUNCTION__;
-    qDebug() << "ERROR MESSAGE: " << error;
-
-    m_ui->buildInformationBox(error, true);
+    qDebug() << __PRETTY_FUNCTION__;    
 
-    if(error.compare(SESSION_EXPIRED) == 0) {
+    switch(error)
+    {
+    case QNetworkReply::ConnectionRefusedError:
+        m_ui->toggleProgressIndicator(false);
+        m_ui->buildInformationBox(tr("Connection refused by the server"), true);
+        break;
+    case QNetworkReply::RemoteHostClosedError:
+        m_ui->toggleProgressIndicator(false);
+        m_ui->buildInformationBox(tr("Connection closed by the server"), true);
+        break;
+    case QNetworkReply::HostNotFoundError:
+        m_ui->toggleProgressIndicator(false);
+        m_ui->buildInformationBox(tr("Remote server not found"), true);
+        break;
+    case QNetworkReply::TimeoutError:
+        m_ui->toggleProgressIndicator(false);
+        m_ui->buildInformationBox(tr("Connection timed out"), true);
+        break;
+    case SituareError::SESSION_EXPIRED:
+        m_ui->buildInformationBox(tr("Session expired. Please login again"), true);
         m_facebookAuthenticator->clearAccountInformation(true); // keep username = true
+        m_situareService->clearUserData();
         m_ui->loggedIn(false);
         m_ui->loginFailed();
+        break;
+    case SituareError::LOGIN_FAILED:
+        m_ui->toggleProgressIndicator(false);
+        m_ui->buildInformationBox(tr("Invalid E-mail address or password"), true);
+        m_ui->loginFailed();
+        break;
+    case SituareError::UPDATE_FAILED:
+        m_ui->toggleProgressIndicator(false);
+        m_ui->buildInformationBox(tr("Update failed, please try again"), true);
+        break;
+    case SituareError::DATA_RETRIEVAL_FAILED:
+        m_ui->toggleProgressIndicator(false);
+        m_ui->buildInformationBox(tr("Data retrieval failed, please try again"), true);
+        break;
+    case SituareError::ADDRESS_RETRIEVAL_FAILED:
+        m_ui->buildInformationBox(tr("Address retrieval failed"), true);
+        break;
+    case SituareError::IMAGE_DOWNLOAD_FAILED:
+        m_ui->buildInformationBox(tr("Image download failed"), true);
+        break;
+    case SituareError::MAP_IMAGE_DOWNLOAD_FAILED:
+        m_ui->buildInformationBox(tr("Map image download failed"), true);
+        break;
+    case SituareError::GPS_INITIALIZATION_FAILED:
+        enableGPS(false);
+        m_ui->buildInformationBox(tr("GPS initialization failed"), true);
+        break;
+    case SituareError::UNKNOWN_REPLY:
+        m_ui->toggleProgressIndicator(false);
+        m_ui->buildInformationBox(tr("Unknown server response"), true);
+        break;
+    case SituareError::INVALID_JSON:
+        m_ui->buildInformationBox(tr("Malformatted reply from server"), true);
+        m_ui->loggedIn(false);
+        m_facebookAuthenticator->clearAccountInformation(false); // clean all
+        break;
+    default:
+        m_ui->toggleProgressIndicator(false);
+        qCritical() << "QNetworkReply::NetworkError :" << error;
+        break;
     }
 }
 
@@ -231,61 +303,59 @@ void SituareEngine::initializeGpsAndAutocentering()
 
     QSettings settings(DIRECTORY_NAME, FILE_NAME);
     QVariant gpsEnabled = settings.value(SETTINGS_GPS_ENABLED);
-    QVariant autoCenteringEnabled = settings.value(SETTINGS_AUTO_CENTERING_ENABLED);     
-
-    if (gpsEnabled.toString().isEmpty()) { // First start. Situare.conf file does not exists
+    QVariant autoCenteringEnabled = settings.value(SETTINGS_AUTO_CENTERING_ENABLED);
 
-        connect(m_gps, SIGNAL(position(QPointF,qreal)),
-                this, SLOT(setFirstStartZoomLevel(QPointF,qreal)));
+    if (m_gps->isInitialized()) {
 
-        changeAutoCenteringSetting(true);
-        enableGPS(true);
+        if (gpsEnabled.toString().isEmpty()) { // First start. Situare.conf file does not exists
 
-        m_ui->buildInformationBox(tr("GPS enabled"));
-        m_ui->buildInformationBox(tr("Auto centering enabled"));
+            connect(m_gps, SIGNAL(position(QPointF,qreal)),
+                    this, SLOT(setFirstStartZoomLevel(QPointF,qreal)));
 
-    } else { // Normal start
-        changeAutoCenteringSetting(autoCenteringEnabled.toBool());
-        enableGPS(gpsEnabled.toBool());
+            changeAutoCenteringSetting(true);
+            enableGPS(true);
 
-        if (gpsEnabled.toBool())
             m_ui->buildInformationBox(tr("GPS enabled"));
-
-        if (gpsEnabled.toBool() && autoCenteringEnabled.toBool())
             m_ui->buildInformationBox(tr("Auto centering enabled"));
-    }
-}
 
-bool SituareEngine::isUserMoved()
-{
-    qDebug() << __PRETTY_FUNCTION__;
+        } else { // Normal start
+            changeAutoCenteringSetting(autoCenteringEnabled.toBool());
+            enableGPS(gpsEnabled.toBool());
+
+            if (gpsEnabled.toBool())
+                m_ui->buildInformationBox(tr("GPS enabled"));
 
-    return m_userMoved;
+            if (gpsEnabled.toBool() && autoCenteringEnabled.toBool())
+                m_ui->buildInformationBox(tr("Auto centering enabled"));
+        }
+    } else {
+        enableGPS(false);
+    }
 }
 
 void SituareEngine::loginActionPressed()
 {
     qDebug() << __PRETTY_FUNCTION__;
 
-    if(m_loggedIn) {
+    if(m_ui->loginState()) {
         logout();
         m_situareService->clearUserData();
-    }
-    else {
+    } else {
         m_facebookAuthenticator->start();
     }
 }
 
 void SituareEngine::loginOk()
 {
-    qWarning() << __PRETTY_FUNCTION__;
+    qDebug() << __PRETTY_FUNCTION__;
 
-    m_loggedIn = true;
-    m_ui->loggedIn(m_loggedIn);
+    m_ui->loggedIn(true);
 
     m_ui->show();
     m_situareService->fetchLocations(); // request user locations
-    m_ui->requestAutomaticLocationUpdateSettings();
+
+    if (m_gps->isRunning())
+        m_ui->readAutomaticLocationUpdateSettings();
 }
 
 void SituareEngine::loginProcessCancelled()
@@ -293,16 +363,22 @@ void SituareEngine::loginProcessCancelled()
     qDebug() << __PRETTY_FUNCTION__;
 
     m_ui->toggleProgressIndicator(false);
-    m_ui->updateItemVisibility(m_loggedIn);
+    m_ui->updateItemVisibility();
 }
 
 void SituareEngine::logout()
 {
     qDebug() << __PRETTY_FUNCTION__;
 
-    m_loggedIn = false;
-    m_ui->loggedIn(m_loggedIn);
+    m_ui->loggedIn(false);
+
+    // signal to clear locationUpdateDialog's data
+    connect(this, SIGNAL(clearUpdateLocationDialogData()),
+            m_ui, SIGNAL(clearUpdateLocationDialogData()));
+    emit clearUpdateLocationDialogData();
+
     m_facebookAuthenticator->clearAccountInformation(); // clear all
+    m_automaticUpdateFirstStart = true;
 }
 
 void SituareEngine::refreshUserData()
@@ -336,7 +412,7 @@ void SituareEngine::requestUpdateLocation(const QString &status, bool publish)
         m_situareService->updateLocation(m_mapEngine->centerGeoCoordinate(), status, publish);
 }
 
-void SituareEngine::saveGPSPosition(QPointF position)
+void SituareEngine::requestAutomaticUpdateIfMoved(QPointF position)
 {
     qDebug() << __PRETTY_FUNCTION__;
 
@@ -348,6 +424,12 @@ void SituareEngine::saveGPSPosition(QPointF position)
         m_lastUpdatedGPSPosition = position;
         m_userMoved = true;
     }
+
+    if (m_automaticUpdateRequest && m_userMoved) {
+        requestUpdateLocation(tr("Automatic location update."));
+        m_automaticUpdateRequest = false;
+        m_userMoved = false;
+    }
 }
 
 void SituareEngine::setFirstStartZoomLevel(QPointF latLonCoordinate, qreal accuracy)
@@ -368,8 +450,8 @@ void SituareEngine::signalsFromFacebookAuthenticator()
 {
     qDebug() << __PRETTY_FUNCTION__;
 
-    connect(m_facebookAuthenticator, SIGNAL(error(QString)),
-            this, SLOT(error(QString)));
+    connect(m_facebookAuthenticator, SIGNAL(error(int)),
+            this, SLOT(error(int)));
 
     connect(m_facebookAuthenticator, SIGNAL(credentialsReady(FacebookCredentials)),
             m_situareService, SLOT(credentialsReady(FacebookCredentials)));
@@ -380,9 +462,6 @@ void SituareEngine::signalsFromFacebookAuthenticator()
     connect(m_facebookAuthenticator, SIGNAL(newLoginRequest()),
             m_ui, SLOT(startLoginProcess()));
 
-    connect(m_facebookAuthenticator, SIGNAL(loginFailure()),
-            m_ui, SLOT(loginFailed()));
-
     connect(m_facebookAuthenticator, SIGNAL(saveCookiesRequest()),
             m_ui, SLOT(saveCookies()));
 
@@ -400,17 +479,17 @@ void SituareEngine::signalsFromGPS()
     connect(m_gps, SIGNAL(timeout()),
             m_ui, SLOT(gpsTimeout()));
 
-    connect(m_gps, SIGNAL(error(QString)),
-            this, SLOT(error(QString)));
-
-    connect(m_gps, SIGNAL(position(QPointF,qreal)),
-            this, SLOT(saveGPSPosition(QPointF)));
+    connect(m_gps, SIGNAL(error(int)),
+            this, SLOT(error(int)));
 }
 
 void SituareEngine::signalsFromMainWindow()
 {
     qDebug() << __PRETTY_FUNCTION__;    
 
+    connect(m_ui, SIGNAL(error(int)),
+            this, SLOT(error(int)));
+
     connect(m_ui, SIGNAL(fetchUsernameFromSettings()),
             this, SLOT(fetchUsernameFromSettings()));
 
@@ -464,9 +543,6 @@ void SituareEngine::signalsFromMainWindow()
     connect(m_ui, SIGNAL(refreshUserData()),
             this, SLOT(refreshUserData()));
 
-    connect (m_ui, SIGNAL(notificateUpdateFailing(QString)),
-             this, SLOT(error(QString)));
-
     connect(m_ui, SIGNAL(findUser(QPointF)),
             m_mapEngine, SLOT(setViewLocation(QPointF)));
 
@@ -479,8 +555,8 @@ void SituareEngine::signalsFromMapEngine()
 {
     qDebug() << __PRETTY_FUNCTION__;
 
-    connect(m_mapEngine, SIGNAL(error(QString)),
-            this, SLOT(error(QString)));
+    connect(m_mapEngine, SIGNAL(error(int)),
+            this, SLOT(error(int)));
 
     connect(m_mapEngine, SIGNAL(locationChanged(QPoint)),
             m_ui, SIGNAL(centerToSceneCoordinates(QPoint)));
@@ -499,14 +575,20 @@ void SituareEngine::signalsFromMapEngine()
 
     connect(m_mapEngine, SIGNAL(locationItemClicked(QList<QString>)),
             m_ui, SIGNAL(locationItemClicked(QList<QString>)));
+
+    connect(m_mapEngine, SIGNAL(newMapResolution(qreal)),
+            m_ui, SIGNAL(newMapResolution(qreal)));
 }
 
 void SituareEngine::signalsFromSituareService()
 {
     qDebug() << __PRETTY_FUNCTION__;
 
-    connect(m_situareService, SIGNAL(error(QString)),
-            this, SLOT(error(QString)));
+    connect(m_situareService, SIGNAL(error(int)),
+            this, SLOT(error(int)));
+
+    connect(m_situareService, SIGNAL(error(int)),
+            m_ui, SIGNAL(messageSendingFailed(int)));
 
     connect(m_situareService, SIGNAL(reverseGeoReady(QString)),
             m_ui, SIGNAL(reverseGeoReady(QString)));
@@ -518,10 +600,15 @@ void SituareEngine::signalsFromSituareService()
             this, SLOT(updateWasSuccessful()));
 
     connect(m_situareService, SIGNAL(updateWasSuccessful()),
-            m_ui, SIGNAL(updateWasSuccessful()));
+            m_ui, SIGNAL(clearUpdateLocationDialogData()));
+}
+
+void SituareEngine::startAutomaticUpdate()
+{
+    qDebug() << __PRETTY_FUNCTION__;
 
-    connect(m_situareService, SIGNAL(error(QString)),
-            m_ui, SIGNAL(messageSendingFailed(QString)));
+    m_gps->requestUpdate();
+    m_automaticUpdateRequest = true;
 }
 
 void SituareEngine::updateWasSuccessful()
@@ -536,6 +623,7 @@ void SituareEngine::userDataChanged(User *user, QList<User *> &friendsList)
     qDebug() << __PRETTY_FUNCTION__;
 
     m_ui->toggleProgressIndicator(false);
+    m_ui->showPanels();
 
     emit userLocationReady(user);
     emit friendsLocationsReady(friendsList);