52dd36e69648165d69de34119a9a01d29988f2a7
[situare] / src / engine / engine.cpp
1  /*
2     Situare - A location system for Facebook
3     Copyright (C) 2010  Ixonos Plc. Authors:
4
5         Kaj Wallin - kaj.wallin@ixonos.com
6         Henri Lampela - henri.lampela@ixonos.com
7         Jussi Laitinen - jussi.laitinen@ixonos.com
8         Sami Rämö - sami.ramo@ixonos.com
9
10     Situare is free software; you can redistribute it and/or
11     modify it under the terms of the GNU General Public License
12     version 2 as published by the Free Software Foundation.
13
14     Situare is distributed in the hope that it will be useful,
15     but WITHOUT ANY WARRANTY; without even the implied warranty of
16     MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
17     GNU General Public License for more details.
18
19     You should have received a copy of the GNU General Public License
20     along with Situare; if not, write to the Free Software
21     Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301,
22     USA.
23  */
24
25 #include <QMessageBox>
26 #include <QNetworkReply>
27
28 #include "common.h"
29 #include "facebookservice/facebookauthentication.h"
30 #include "gps/gpsposition.h"
31 #include "map/mapengine.h"
32 #include "situareservice/situareservice.h"
33 #include "ui/mainwindow.h"
34 #include <cmath>
35
36 #include "engine.h"
37
38 const QString SETTINGS_GPS_ENABLED = "GPS_ENABLED"; ///< GPS setting
39 const QString SETTINGS_AUTO_CENTERING_ENABLED = "AUTO_CENTERING_ENABLED";///< Auto centering setting
40 const int DEFAULT_ZOOM_LEVEL_WHEN_GPS_IS_AVAILABLE = 12;  ///< Default zoom level when GPS available
41 const qreal USER_MOVEMENT_MINIMUM_LONGITUDE_DIFFERENCE = 0.003;///< Min value for user move latitude
42 const qreal USER_MOVEMENT_MINIMUM_LATITUDE_DIFFERENCE = 0.001;///< Min value for user move longitude
43 const int MIN_UPDATE_INTERVAL_MSECS = 5*60*1000;
44
45 SituareEngine::SituareEngine(QMainWindow *parent)
46     : QObject(parent),
47       m_autoCenteringEnabled(false),
48       m_automaticUpdateFirstStart(true),
49       m_loggedIn(false),
50       m_userMoved(false),
51       m_automaticUpdateEnabled(false),
52       m_automaticUpdateIntervalTimer(0),
53       m_lastUpdatedGPSPosition(QPointF())
54 {    
55     qDebug() << __PRETTY_FUNCTION__;
56     m_ui = new MainWindow;
57     m_ui->updateItemVisibility(m_loggedIn);
58
59     // build MapEngine
60     m_mapEngine = new MapEngine(this);
61     m_ui->setMapViewScene(m_mapEngine->scene());
62
63     // build GPS
64     m_gps = new GPSPosition(this);
65
66     // build SituareService
67     m_situareService = new SituareService(this);
68
69     // build FacebookAuthenticator
70     m_facebookAuthenticator = new FacebookAuthentication(this);
71
72     // connect signals
73     signalsFromMapEngine();
74     signalsFromGPS();
75     signalsFromSituareService();
76     signalsFromMainWindow();
77     signalsFromFacebookAuthenticator();
78
79     connect(this, SIGNAL(userLocationReady(User*)),
80             m_ui, SIGNAL(userLocationReady(User*)));
81
82     connect(this, SIGNAL(friendsLocationsReady(QList<User*>&)),
83             m_ui, SIGNAL(friendsLocationsReady(QList<User*>&)));
84
85     connect(this, SIGNAL(userLocationReady(User*)),
86             m_mapEngine, SLOT(receiveOwnLocation(User*)));
87
88     connect(this, SIGNAL(friendsLocationsReady(QList<User*>&)),
89             m_mapEngine, SIGNAL(friendsLocationsReady(QList<User*>&)));
90
91     m_automaticUpdateIntervalTimer = new QTimer(this);
92     connect(m_automaticUpdateIntervalTimer, SIGNAL(timeout()),
93             this, SLOT(automaticUpdateIntervalTimerTimeout()));
94
95     // signals connected, now it's time to show the main window
96     // but init the MapEngine before so starting location is set
97     m_mapEngine->init();
98     m_ui->show();
99
100     m_facebookAuthenticator->start();
101
102     m_gps->setMode(GPSPosition::Default);
103     initializeGpsAndAutocentering();
104 }
105
106 SituareEngine::~SituareEngine()
107 {
108     qDebug() << __PRETTY_FUNCTION__;
109
110     delete m_ui;
111
112     QSettings settings(DIRECTORY_NAME, FILE_NAME);
113     settings.setValue(SETTINGS_GPS_ENABLED, m_gps->isRunning());
114     settings.setValue(SETTINGS_AUTO_CENTERING_ENABLED, m_autoCenteringEnabled);
115 }
116
117 void SituareEngine::automaticUpdateIntervalTimerTimeout()
118 {
119     qDebug() << __PRETTY_FUNCTION__;
120
121     if (m_gps->isRunning() && m_userMoved) {
122         requestUpdateLocation();
123         m_userMoved = false;
124     }
125 }
126
127 void SituareEngine::changeAutoCenteringSetting(bool enabled)
128 {
129     qDebug() << __PRETTY_FUNCTION__;
130
131     m_autoCenteringEnabled = enabled;
132     enableAutoCentering(enabled);
133 }
134
135 void SituareEngine::disableAutoCentering()
136 {
137     qDebug() << __PRETTY_FUNCTION__;
138
139     changeAutoCenteringSetting(false);
140     m_ui->buildInformationBox(tr("Auto centering disabled"));
141 }
142
143 void SituareEngine::enableAutoCentering(bool enabled)
144 {
145     qDebug() << __PRETTY_FUNCTION__;
146
147     m_ui->setAutoCenteringButtonEnabled(enabled);
148     m_mapEngine->setAutoCentering(enabled);
149
150     if (enabled)
151         m_gps->requestLastPosition();
152 }
153
154 void SituareEngine::enableGPS(bool enabled)
155 {
156     qDebug() << __PRETTY_FUNCTION__;
157
158     m_ui->setOwnLocationCrosshairVisibility(!enabled);
159
160     if (m_gps->isInitialized()) {
161         m_ui->setGPSButtonEnabled(enabled);
162         m_mapEngine->setGPSEnabled(enabled);
163
164         if (enabled && !m_gps->isRunning()) {
165             m_gps->start();
166             enableAutoCentering(m_autoCenteringEnabled);
167             m_gps->requestLastPosition();
168
169             if (!m_automaticUpdateEnabled && m_loggedIn)
170                 m_ui->requestAutomaticLocationUpdateSettings();
171         }
172         else if (!enabled && m_gps->isRunning()) {
173             m_gps->stop();
174             enableAutoCentering(false);
175             enableAutomaticLocationUpdate(false);
176         }
177     }
178     else {
179         if (enabled)
180             m_ui->buildInformationBox(tr("Unable to start GPS"));
181         m_ui->setGPSButtonEnabled(false);
182         m_mapEngine->setGPSEnabled(false);
183     }
184 }
185
186 void SituareEngine::enableAutomaticLocationUpdate(bool enabled, int updateIntervalMsecs)
187 {
188     qDebug() << __PRETTY_FUNCTION__;
189
190     m_automaticUpdateEnabled = enabled;
191
192     //Show automatic update confirmation dialog
193     if (m_automaticUpdateFirstStart && m_gps->isRunning() && m_automaticUpdateEnabled) {
194         m_ui->showEnableAutomaticUpdateLocationDialog(
195                 tr("Do you want to enable automatic location update with %1 min update interval?")
196                 .arg(updateIntervalMsecs/1000/60));
197         m_automaticUpdateFirstStart = false;
198     } else {
199         if (m_automaticUpdateEnabled && m_gps->isRunning()) {
200             m_ui->buildInformationBox(tr("Automatic location update enabled"));
201             if (updateIntervalMsecs < MIN_UPDATE_INTERVAL_MSECS)
202                 m_automaticUpdateIntervalTimer->setInterval(MIN_UPDATE_INTERVAL_MSECS);
203             else
204                 m_automaticUpdateIntervalTimer->setInterval(updateIntervalMsecs);
205
206             m_automaticUpdateIntervalTimer->start();
207
208         } else {
209             m_automaticUpdateIntervalTimer->stop();
210         }
211     }
212 }
213
214 void SituareEngine::error(const int error)
215 {
216     qDebug() << __PRETTY_FUNCTION__;    
217
218     switch(error)
219     {
220     case QNetworkReply::ConnectionRefusedError:
221         m_ui->buildInformationBox(tr("Connection refused by the server"), true);
222         break;
223     case QNetworkReply::RemoteHostClosedError:
224         m_ui->buildInformationBox(tr("Connection closed by the server"), true);
225         break;
226     case QNetworkReply::HostNotFoundError:
227         m_ui->buildInformationBox(tr("Remote server not found"), true);
228         break;
229     case QNetworkReply::TimeoutError:
230         m_ui->buildInformationBox(tr("Connection timed out"), true);
231         break;
232     case SituareError::SESSION_EXPIRED:
233         m_ui->buildInformationBox(tr("Session expired. Please login again"), true);
234         m_facebookAuthenticator->clearAccountInformation(true); // keep username = true
235         m_loggedIn = false;
236         m_situareService->clearUserData();
237         m_ui->loggedIn(false);
238         m_ui->loginFailed();
239         break;
240     case SituareError::LOGIN_FAILED:
241         m_ui->buildInformationBox(tr("Invalid E-mail address or password"), true);
242         break;
243     case SituareError::UPDATE_FAILED:
244         m_ui->buildInformationBox(tr("Update failed, please try again"), true);
245         break;
246     case SituareError::DATA_RETRIEVAL_FAILED:
247         m_ui->buildInformationBox(tr("Data retrieval failed, please try again"), true);
248         break;
249     case SituareError::ADDRESS_RETRIEVAL_FAILED:
250         m_ui->buildInformationBox(tr("Address retrieval failed"), true);
251         break;
252     case SituareError::IMAGE_DOWNLOAD_FAILED:
253         m_ui->buildInformationBox(tr("Image download failed"), true);
254         break;
255     case SituareError::MAP_IMAGE_DOWNLOAD_FAILED:
256         m_ui->buildInformationBox(tr("Map image download failed"), true);
257         break;
258     case SituareError::GPS_INITIALIZATION_FAILED:
259         enableGPS(false);
260         m_ui->buildInformationBox(tr("GPS initialization failed"), true);
261         break;
262     case SituareError::UNKNOWN_REPLY:
263         m_ui->buildInformationBox(tr("Unknown server response"), true);
264         break;
265     case SituareError::INVALID_JSON:
266         m_ui->buildInformationBox(tr("JSON parsing failed, invalid JSON string"), true);
267         break;
268     default:
269         qCritical() << "QNetworkReply::NetworkError :" << error;
270         break;
271     }
272 }
273
274 void SituareEngine::fetchUsernameFromSettings()
275 {
276     qDebug() << __PRETTY_FUNCTION__;
277
278     m_ui->setUsername(m_facebookAuthenticator->loadUsername());
279 }
280
281 void SituareEngine::initializeGpsAndAutocentering()
282 {
283     qDebug() << __PRETTY_FUNCTION__;
284
285     QSettings settings(DIRECTORY_NAME, FILE_NAME);
286     QVariant gpsEnabled = settings.value(SETTINGS_GPS_ENABLED);
287     QVariant autoCenteringEnabled = settings.value(SETTINGS_AUTO_CENTERING_ENABLED);
288
289     if (m_gps->isInitialized()) {
290
291         if (gpsEnabled.toString().isEmpty()) { // First start. Situare.conf file does not exists
292
293             connect(m_gps, SIGNAL(position(QPointF,qreal)),
294                     this, SLOT(setFirstStartZoomLevel(QPointF,qreal)));
295
296             changeAutoCenteringSetting(true);
297             enableGPS(true);
298
299             m_ui->buildInformationBox(tr("GPS enabled"));
300             m_ui->buildInformationBox(tr("Auto centering enabled"));
301
302         } else { // Normal start
303             changeAutoCenteringSetting(autoCenteringEnabled.toBool());
304             enableGPS(gpsEnabled.toBool());
305
306             if (gpsEnabled.toBool())
307                 m_ui->buildInformationBox(tr("GPS enabled"));
308
309             if (gpsEnabled.toBool() && autoCenteringEnabled.toBool())
310                 m_ui->buildInformationBox(tr("Auto centering enabled"));
311         }
312     } else {
313         enableGPS(false);
314     }
315 }
316
317 bool SituareEngine::isUserMoved()
318 {
319     qDebug() << __PRETTY_FUNCTION__;
320
321     return m_userMoved;
322 }
323
324 void SituareEngine::loginActionPressed()
325 {
326     qDebug() << __PRETTY_FUNCTION__;
327
328     if(m_loggedIn) {
329         logout();
330         m_situareService->clearUserData();
331     }
332     else {
333         m_facebookAuthenticator->start();
334     }
335 }
336
337 void SituareEngine::loginOk()
338 {
339     qDebug() << __PRETTY_FUNCTION__;
340
341     m_loggedIn = true;
342     m_ui->loggedIn(m_loggedIn);
343
344     m_ui->show();
345     m_situareService->fetchLocations(); // request user locations
346
347     if (m_gps->isRunning())
348         m_ui->requestAutomaticLocationUpdateSettings();
349 }
350
351 void SituareEngine::loginProcessCancelled()
352 {
353     qDebug() << __PRETTY_FUNCTION__;
354
355     m_ui->toggleProgressIndicator(false);
356     m_ui->updateItemVisibility(m_loggedIn);
357 }
358
359 void SituareEngine::logout()
360 {
361     qDebug() << __PRETTY_FUNCTION__;
362
363     m_loggedIn = false;
364     m_ui->loggedIn(m_loggedIn);
365
366     // signal to clear locationUpdateDialog's data
367     connect(this, SIGNAL(clearUpdateLocationDialogData()),
368             m_ui, SIGNAL(clearUpdateLocationDialogData()));
369     emit clearUpdateLocationDialogData();
370
371     m_facebookAuthenticator->clearAccountInformation(); // clear all
372     m_automaticUpdateEnabled = false;
373     m_automaticUpdateFirstStart = true;
374 }
375
376 void SituareEngine::refreshUserData()
377 {
378     qDebug() << __PRETTY_FUNCTION__;
379
380     m_ui->toggleProgressIndicator(true);
381
382     m_situareService->fetchLocations();
383 }
384
385 void SituareEngine::requestAddress()
386 {
387     qDebug() << __PRETTY_FUNCTION__;
388
389     if (m_gps->isRunning())
390         m_situareService->reverseGeo(m_gps->lastPosition());
391     else
392         m_situareService->reverseGeo(m_mapEngine->centerGeoCoordinate());
393 }
394
395 void SituareEngine::requestUpdateLocation(const QString &status, bool publish)
396 {
397     qDebug() << __PRETTY_FUNCTION__;
398
399     m_ui->toggleProgressIndicator(true);
400
401     if (m_gps->isRunning())
402         m_situareService->updateLocation(m_gps->lastPosition(), status, publish);
403     else
404         m_situareService->updateLocation(m_mapEngine->centerGeoCoordinate(), status, publish);
405 }
406
407 void SituareEngine::saveGPSPosition(QPointF position)
408 {
409     qDebug() << __PRETTY_FUNCTION__;
410
411     if ((fabs(m_lastUpdatedGPSPosition.x() - position.x()) >
412          USER_MOVEMENT_MINIMUM_LONGITUDE_DIFFERENCE) ||
413         (fabs(m_lastUpdatedGPSPosition.y() - position.y()) >
414          USER_MOVEMENT_MINIMUM_LATITUDE_DIFFERENCE)) {
415
416         m_lastUpdatedGPSPosition = position;
417         m_userMoved = true;
418     }
419 }
420
421 void SituareEngine::setFirstStartZoomLevel(QPointF latLonCoordinate, qreal accuracy)
422 {
423     qDebug() << __PRETTY_FUNCTION__;
424
425     Q_UNUSED(latLonCoordinate);
426     Q_UNUSED(accuracy);
427
428     if (m_autoCenteringEnabled) // autocentering is disabled when map is scrolled        
429         m_mapEngine->setZoomLevel(DEFAULT_ZOOM_LEVEL_WHEN_GPS_IS_AVAILABLE);
430
431     disconnect(m_gps, SIGNAL(position(QPointF,qreal)),
432                this, SLOT(setFirstStartZoomLevel(QPointF,qreal)));
433 }
434
435 void SituareEngine::signalsFromFacebookAuthenticator()
436 {
437     qDebug() << __PRETTY_FUNCTION__;
438
439     connect(m_facebookAuthenticator, SIGNAL(error(int)),
440             this, SLOT(error(int)));
441
442     connect(m_facebookAuthenticator, SIGNAL(credentialsReady(FacebookCredentials)),
443             m_situareService, SLOT(credentialsReady(FacebookCredentials)));
444
445     connect(m_facebookAuthenticator, SIGNAL(credentialsReady(FacebookCredentials)),
446             this, SLOT(loginOk()));
447
448     connect(m_facebookAuthenticator, SIGNAL(newLoginRequest()),
449             m_ui, SLOT(startLoginProcess()));
450
451     connect(m_facebookAuthenticator, SIGNAL(loginFailure()),
452             m_ui, SLOT(loginFailed()));
453
454     connect(m_facebookAuthenticator, SIGNAL(saveCookiesRequest()),
455             m_ui, SLOT(saveCookies()));
456
457     connect(m_facebookAuthenticator, SIGNAL(loginUsingCookies()),
458             m_ui, SLOT(loginUsingCookies()));
459 }
460
461 void SituareEngine::signalsFromGPS()
462 {
463     qDebug() << __PRETTY_FUNCTION__;
464
465     connect(m_gps, SIGNAL(position(QPointF,qreal)),
466             m_mapEngine, SLOT(gpsPositionUpdate(QPointF,qreal)));
467
468     connect(m_gps, SIGNAL(timeout()),
469             m_ui, SLOT(gpsTimeout()));
470
471     connect(m_gps, SIGNAL(error(int)),
472             this, SLOT(error(int)));
473
474     connect(m_gps, SIGNAL(position(QPointF,qreal)),
475             this, SLOT(saveGPSPosition(QPointF)));
476 }
477
478 void SituareEngine::signalsFromMainWindow()
479 {
480     qDebug() << __PRETTY_FUNCTION__;    
481
482     connect(m_ui, SIGNAL(error(int)),
483             this, SLOT(error(int)));
484
485     connect(m_ui, SIGNAL(fetchUsernameFromSettings()),
486             this, SLOT(fetchUsernameFromSettings()));
487
488     connect(m_ui, SIGNAL(loginActionPressed()),
489             this, SLOT(loginActionPressed()));
490
491     connect(m_ui, SIGNAL(saveUsername(QString)),
492             m_facebookAuthenticator, SLOT(saveUsername(QString)));
493
494     connect(m_ui, SIGNAL(updateCredentials(QUrl)),
495             m_facebookAuthenticator, SLOT(updateCredentials(QUrl)));
496
497     // signals from map view
498     connect(m_ui, SIGNAL(mapViewScrolled(QPoint)),
499             m_mapEngine, SLOT(setLocation(QPoint)));
500
501     connect(m_ui, SIGNAL(mapViewResized(QSize)),
502             m_mapEngine, SLOT(viewResized(QSize)));
503
504     connect(m_ui, SIGNAL(viewZoomFinished()),
505             m_mapEngine, SLOT(viewZoomFinished()));
506
507     // signals from zoom buttons (zoom panel and volume buttons)
508     connect(m_ui, SIGNAL(zoomIn()),
509             m_mapEngine, SLOT(zoomIn()));
510
511     connect(m_ui, SIGNAL(zoomOut()),
512             m_mapEngine, SLOT(zoomOut()));
513
514     // signals from menu buttons
515     connect(m_ui, SIGNAL(autoCenteringTriggered(bool)),
516             this, SLOT(changeAutoCenteringSetting(bool)));
517
518     connect(m_ui, SIGNAL(gpsTriggered(bool)),
519             this, SLOT(enableGPS(bool)));
520
521     //signals from dialogs
522     connect(m_ui, SIGNAL(cancelLoginProcess()),
523             this, SLOT(loginProcessCancelled()));
524
525     connect(m_ui, SIGNAL(requestReverseGeo()),
526             this, SLOT(requestAddress()));
527
528     connect(m_ui, SIGNAL(statusUpdate(QString,bool)),
529             this, SLOT(requestUpdateLocation(QString,bool)));
530
531     connect(m_ui, SIGNAL(enableAutomaticLocationUpdate(bool, int)),
532             this, SLOT(enableAutomaticLocationUpdate(bool, int)));    
533
534     // signals from user info tab
535     connect(m_ui, SIGNAL(refreshUserData()),
536             this, SLOT(refreshUserData()));
537
538     connect(m_ui, SIGNAL(findUser(QPointF)),
539             m_mapEngine, SLOT(setViewLocation(QPointF)));
540
541     // signals from friend list tab
542     connect(m_ui, SIGNAL(findFriend(QPointF)),
543             m_mapEngine, SLOT(setViewLocation(QPointF)));
544 }
545
546 void SituareEngine::signalsFromMapEngine()
547 {
548     qDebug() << __PRETTY_FUNCTION__;
549
550     connect(m_mapEngine, SIGNAL(error(int)),
551             this, SLOT(error(int)));
552
553     connect(m_mapEngine, SIGNAL(locationChanged(QPoint)),
554             m_ui, SIGNAL(centerToSceneCoordinates(QPoint)));
555
556     connect(m_mapEngine, SIGNAL(zoomLevelChanged(int)),
557             m_ui, SIGNAL(zoomLevelChanged(int)));
558
559     connect(m_mapEngine, SIGNAL(mapScrolledManually()),
560             this, SLOT(disableAutoCentering()));
561
562     connect(m_mapEngine, SIGNAL(maxZoomLevelReached()),
563             m_ui, SIGNAL(maxZoomLevelReached()));
564
565     connect(m_mapEngine, SIGNAL(minZoomLevelReached()),
566             m_ui, SIGNAL(minZoomLevelReached()));
567
568     connect(m_mapEngine, SIGNAL(locationItemClicked(QList<QString>)),
569             m_ui, SIGNAL(locationItemClicked(QList<QString>)));
570
571     connect(m_mapEngine, SIGNAL(newMapResolution(qreal)),
572             m_ui, SIGNAL(newMapResolution(qreal)));
573 }
574
575 void SituareEngine::signalsFromSituareService()
576 {
577     qDebug() << __PRETTY_FUNCTION__;
578
579     connect(m_situareService, SIGNAL(error(int)),
580             this, SLOT(error(int)));
581
582     connect(m_situareService, SIGNAL(error(int)),
583             m_ui, SIGNAL(messageSendingFailed(int)));
584
585     connect(m_situareService, SIGNAL(reverseGeoReady(QString)),
586             m_ui, SIGNAL(reverseGeoReady(QString)));
587
588     connect(m_situareService, SIGNAL(userDataChanged(User*, QList<User*>&)),
589             this, SLOT(userDataChanged(User*, QList<User*>&)));
590
591     connect(m_situareService, SIGNAL(updateWasSuccessful()),
592             this, SLOT(updateWasSuccessful()));
593
594     connect(m_situareService, SIGNAL(updateWasSuccessful()),
595             m_ui, SIGNAL(clearUpdateLocationDialogData()));
596 }
597
598 void SituareEngine::updateWasSuccessful()
599 {
600     qDebug() << __PRETTY_FUNCTION__;
601
602     m_situareService->fetchLocations();
603 }
604
605 void SituareEngine::userDataChanged(User *user, QList<User *> &friendsList)
606 {
607     qDebug() << __PRETTY_FUNCTION__;
608
609     m_ui->toggleProgressIndicator(false);
610
611     emit userLocationReady(user);
612     emit friendsLocationsReady(friendsList);
613 }