bf396bbc2b2ca1d8f836538b3416314f8849a985
[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
27 #include "common.h"
28 #include "facebookservice/facebookauthentication.h"
29 #include "gps/gpsposition.h"
30 #include "map/mapengine.h"
31 #include "situareservice/situareservice.h"
32 #include "ui/mainwindow.h"
33 #include <cmath>
34
35 #include "engine.h"
36
37 const QString SETTINGS_GPS_ENABLED = "GPS_ENABLED"; ///< GPS setting
38 const QString SETTINGS_AUTO_CENTERING_ENABLED = "AUTO_CENTERING_ENABLED";///< Auto centering setting
39 const int DEFAULT_ZOOM_LEVEL_WHEN_GPS_IS_AVAILABLE = 12;  ///< Default zoom level when GPS available
40 const qreal USER_MOVEMENT_MINIMUM_LONGITUDE_DIFFERENCE = 0.003;///< Min value for user move latitude
41 const qreal USER_MOVEMENT_MINIMUM_LATITUDE_DIFFERENCE = 0.001;///< Min value for user move longitude
42 const int MIN_UPDATE_INTERVAL_MSECS = 5*60*1000;
43
44 SituareEngine::SituareEngine(QMainWindow *parent)
45     : QObject(parent),
46       m_autoCenteringEnabled(false),
47       m_automaticUpdateFirstStart(true),
48       m_loggedIn(false),
49       m_userMoved(false),
50       m_automaticUpdateEnabled(false),
51       m_automaticUpdateIntervalTimer(0),
52       m_lastUpdatedGPSPosition(QPointF())
53 {    
54     qDebug() << __PRETTY_FUNCTION__;
55     m_ui = new MainWindow;
56     m_ui->updateItemVisibility(m_loggedIn);
57
58     // build MapEngine
59     m_mapEngine = new MapEngine(this);
60     m_ui->setMapViewScene(m_mapEngine->scene());
61
62     // build GPS
63     m_gps = new GPSPosition(this);
64
65     // build SituareService
66     m_situareService = new SituareService(this);
67
68     // build FacebookAuthenticator
69     m_facebookAuthenticator = new FacebookAuthentication(this);
70
71     // connect signals
72     signalsFromMapEngine();
73     signalsFromGPS();
74     signalsFromSituareService();
75     signalsFromMainWindow();
76     signalsFromFacebookAuthenticator();
77
78     connect(this, SIGNAL(userLocationReady(User*)),
79             m_ui, SIGNAL(userLocationReady(User*)));
80
81     connect(this, SIGNAL(friendsLocationsReady(QList<User*>&)),
82             m_ui, SIGNAL(friendsLocationsReady(QList<User*>&)));
83
84     connect(this, SIGNAL(userLocationReady(User*)),
85             m_mapEngine, SLOT(receiveOwnLocation(User*)));
86
87     connect(this, SIGNAL(friendsLocationsReady(QList<User*>&)),
88             m_mapEngine, SIGNAL(friendsLocationsReady(QList<User*>&)));
89
90     m_automaticUpdateIntervalTimer = new QTimer(this);
91     connect(m_automaticUpdateIntervalTimer, SIGNAL(timeout()),
92             this, SLOT(automaticUpdateIntervalTimerTimeout()));
93
94     // signals connected, now it's time to show the main window
95     // but init the MapEngine before so starting location is set
96     m_mapEngine->init();
97     m_ui->show();
98
99     m_facebookAuthenticator->start();
100
101     m_gps->setMode(GPSPosition::Default);
102     initializeGpsAndAutocentering();
103 }
104
105 SituareEngine::~SituareEngine()
106 {
107     qDebug() << __PRETTY_FUNCTION__;
108
109     delete m_ui;
110
111     QSettings settings(DIRECTORY_NAME, FILE_NAME);
112     settings.setValue(SETTINGS_GPS_ENABLED, m_gps->isRunning());
113     settings.setValue(SETTINGS_AUTO_CENTERING_ENABLED, m_autoCenteringEnabled);
114 }
115
116 void SituareEngine::automaticUpdateIntervalTimerTimeout()
117 {
118     qDebug() << __PRETTY_FUNCTION__;
119
120     if (m_gps->isRunning() && m_userMoved) {
121         requestUpdateLocation();
122         m_userMoved = false;
123     }
124 }
125
126 void SituareEngine::changeAutoCenteringSetting(bool enabled)
127 {
128     qDebug() << __PRETTY_FUNCTION__;
129
130     m_autoCenteringEnabled = enabled;
131     enableAutoCentering(enabled);
132 }
133
134 void SituareEngine::disableAutoCentering()
135 {
136     qDebug() << __PRETTY_FUNCTION__;
137
138     changeAutoCenteringSetting(false);
139     m_ui->buildInformationBox(tr("Auto centering disabled"));
140 }
141
142 void SituareEngine::enableAutoCentering(bool enabled)
143 {
144     qDebug() << __PRETTY_FUNCTION__;
145
146     m_ui->setAutoCenteringButtonEnabled(enabled);
147     m_mapEngine->setAutoCentering(enabled);
148
149     if (enabled)
150         m_gps->requestLastPosition();
151 }
152
153 void SituareEngine::enableGPS(bool enabled)
154 {
155     qDebug() << __PRETTY_FUNCTION__;
156
157     if (m_gps->isInitialized()) {
158         m_ui->setGPSButtonEnabled(enabled);
159         m_mapEngine->setGPSEnabled(enabled);
160
161         if (enabled && !m_gps->isRunning()) {
162             m_gps->start();
163             enableAutoCentering(m_autoCenteringEnabled);
164             m_gps->requestLastPosition();
165
166             if (!m_automaticUpdateEnabled && m_loggedIn)
167                 m_ui->requestAutomaticLocationUpdateSettings();
168         }
169         else if (!enabled && m_gps->isRunning()) {
170             m_gps->stop();
171             enableAutoCentering(false);
172             enableAutomaticLocationUpdate(false);
173         }
174     }
175     else {
176         if (enabled)
177             m_ui->buildInformationBox(tr("Unable to start GPS"));
178         m_ui->setGPSButtonEnabled(false);
179         m_mapEngine->setGPSEnabled(false);
180     }
181 }
182
183 void SituareEngine::enableAutomaticLocationUpdate(bool enabled, int updateIntervalMsecs)
184 {
185     qDebug() << __PRETTY_FUNCTION__;
186
187     m_automaticUpdateEnabled = enabled;
188
189     //Show automatic update confirmation dialog
190     if (m_automaticUpdateFirstStart && m_gps->isRunning() && m_automaticUpdateEnabled) {
191         m_ui->showEnableAutomaticUpdateLocationDialog(
192                 tr("Do you want to enable automatic location update with %1 min update interval?")
193                 .arg(updateIntervalMsecs/1000/60));
194         m_automaticUpdateFirstStart = false;
195     } else {
196         if (m_automaticUpdateEnabled && m_gps->isRunning()) {
197             m_ui->buildInformationBox(tr("Automatic location update enabled"));
198             if (updateIntervalMsecs < MIN_UPDATE_INTERVAL_MSECS)
199                 m_automaticUpdateIntervalTimer->setInterval(MIN_UPDATE_INTERVAL_MSECS);
200             else
201                 m_automaticUpdateIntervalTimer->setInterval(updateIntervalMsecs);
202
203             m_automaticUpdateIntervalTimer->start();
204
205         } else {
206             m_automaticUpdateIntervalTimer->stop();
207         }
208     }
209 }
210
211 void SituareEngine::error(const QString &error)
212 {
213     qDebug() << __PRETTY_FUNCTION__;    
214
215     m_ui->buildInformationBox(error, true);
216
217     if(error.compare(SESSION_EXPIRED) == 0) {
218         m_facebookAuthenticator->clearAccountInformation(true); // keep username = true
219         m_ui->loggedIn(false);
220         m_ui->loginFailed();
221     }
222 }
223
224 void SituareEngine::fetchUsernameFromSettings()
225 {
226     qDebug() << __PRETTY_FUNCTION__;
227
228     m_ui->setUsername(m_facebookAuthenticator->loadUsername());
229 }
230
231 void SituareEngine::initializeGpsAndAutocentering()
232 {
233     qDebug() << __PRETTY_FUNCTION__;
234
235     QSettings settings(DIRECTORY_NAME, FILE_NAME);
236     QVariant gpsEnabled = settings.value(SETTINGS_GPS_ENABLED);
237     QVariant autoCenteringEnabled = settings.value(SETTINGS_AUTO_CENTERING_ENABLED);
238
239     if (m_gps->isInitialized()) {
240
241         if (gpsEnabled.toString().isEmpty()) { // First start. Situare.conf file does not exists
242
243             connect(m_gps, SIGNAL(position(QPointF,qreal)),
244                     this, SLOT(setFirstStartZoomLevel(QPointF,qreal)));
245
246             changeAutoCenteringSetting(true);
247             enableGPS(true);
248
249             m_ui->buildInformationBox(tr("GPS enabled"));
250             m_ui->buildInformationBox(tr("Auto centering enabled"));
251
252         } else { // Normal start
253             changeAutoCenteringSetting(autoCenteringEnabled.toBool());
254             enableGPS(gpsEnabled.toBool());
255
256             if (gpsEnabled.toBool())
257                 m_ui->buildInformationBox(tr("GPS enabled"));
258
259             if (gpsEnabled.toBool() && autoCenteringEnabled.toBool())
260                 m_ui->buildInformationBox(tr("Auto centering enabled"));
261         }
262     } else {
263         enableGPS(false);
264     }
265 }
266
267 bool SituareEngine::isUserMoved()
268 {
269     qDebug() << __PRETTY_FUNCTION__;
270
271     return m_userMoved;
272 }
273
274 void SituareEngine::loginActionPressed()
275 {
276     qDebug() << __PRETTY_FUNCTION__;
277
278     if(m_loggedIn) {
279         logout();
280         m_situareService->clearUserData();
281     }
282     else {
283         m_facebookAuthenticator->start();
284     }
285 }
286
287 void SituareEngine::loginOk()
288 {
289     qDebug() << __PRETTY_FUNCTION__;
290
291     m_loggedIn = true;
292     m_ui->loggedIn(m_loggedIn);
293
294     m_ui->show();
295     m_situareService->fetchLocations(); // request user locations
296
297     if (m_gps->isRunning())
298         m_ui->requestAutomaticLocationUpdateSettings();
299 }
300
301 void SituareEngine::loginProcessCancelled()
302 {
303     qDebug() << __PRETTY_FUNCTION__;
304
305     m_ui->toggleProgressIndicator(false);
306     m_ui->updateItemVisibility(m_loggedIn);
307 }
308
309 void SituareEngine::logout()
310 {
311     qDebug() << __PRETTY_FUNCTION__;
312
313     m_loggedIn = false;
314     m_ui->loggedIn(m_loggedIn);
315     m_facebookAuthenticator->clearAccountInformation(); // clear all
316     m_automaticUpdateEnabled = false;
317     m_automaticUpdateFirstStart = true;
318 }
319
320 void SituareEngine::refreshUserData()
321 {
322     qDebug() << __PRETTY_FUNCTION__;
323
324     m_ui->toggleProgressIndicator(true);
325
326     m_situareService->fetchLocations();
327 }
328
329 void SituareEngine::requestAddress()
330 {
331     qDebug() << __PRETTY_FUNCTION__;
332
333     if (m_gps->isRunning())
334         m_situareService->reverseGeo(m_gps->lastPosition());
335     else
336         m_situareService->reverseGeo(m_mapEngine->centerGeoCoordinate());
337 }
338
339 void SituareEngine::requestUpdateLocation(const QString &status, bool publish)
340 {
341     qDebug() << __PRETTY_FUNCTION__;
342
343     m_ui->toggleProgressIndicator(true);
344
345     if (m_gps->isRunning())
346         m_situareService->updateLocation(m_gps->lastPosition(), status, publish);
347     else
348         m_situareService->updateLocation(m_mapEngine->centerGeoCoordinate(), status, publish);
349 }
350
351 void SituareEngine::saveGPSPosition(QPointF position)
352 {
353     qDebug() << __PRETTY_FUNCTION__;
354
355     if ((fabs(m_lastUpdatedGPSPosition.x() - position.x()) >
356          USER_MOVEMENT_MINIMUM_LONGITUDE_DIFFERENCE) ||
357         (fabs(m_lastUpdatedGPSPosition.y() - position.y()) >
358          USER_MOVEMENT_MINIMUM_LATITUDE_DIFFERENCE)) {
359
360         m_lastUpdatedGPSPosition = position;
361         m_userMoved = true;
362     }
363 }
364
365 void SituareEngine::setFirstStartZoomLevel(QPointF latLonCoordinate, qreal accuracy)
366 {
367     qDebug() << __PRETTY_FUNCTION__;
368
369     Q_UNUSED(latLonCoordinate);
370     Q_UNUSED(accuracy);
371
372     if (m_autoCenteringEnabled) // autocentering is disabled when map is scrolled        
373         m_mapEngine->setZoomLevel(DEFAULT_ZOOM_LEVEL_WHEN_GPS_IS_AVAILABLE);
374
375     disconnect(m_gps, SIGNAL(position(QPointF,qreal)),
376                this, SLOT(setFirstStartZoomLevel(QPointF,qreal)));
377 }
378
379 void SituareEngine::signalsFromFacebookAuthenticator()
380 {
381     qDebug() << __PRETTY_FUNCTION__;
382
383     connect(m_facebookAuthenticator, SIGNAL(error(QString)),
384             this, SLOT(error(QString)));
385
386     connect(m_facebookAuthenticator, SIGNAL(credentialsReady(FacebookCredentials)),
387             m_situareService, SLOT(credentialsReady(FacebookCredentials)));
388
389     connect(m_facebookAuthenticator, SIGNAL(credentialsReady(FacebookCredentials)),
390             this, SLOT(loginOk()));
391
392     connect(m_facebookAuthenticator, SIGNAL(newLoginRequest()),
393             m_ui, SLOT(startLoginProcess()));
394
395     connect(m_facebookAuthenticator, SIGNAL(loginFailure()),
396             m_ui, SLOT(loginFailed()));
397
398     connect(m_facebookAuthenticator, SIGNAL(saveCookiesRequest()),
399             m_ui, SLOT(saveCookies()));
400
401     connect(m_facebookAuthenticator, SIGNAL(loginUsingCookies()),
402             m_ui, SLOT(loginUsingCookies()));
403 }
404
405 void SituareEngine::signalsFromGPS()
406 {
407     qDebug() << __PRETTY_FUNCTION__;
408
409     connect(m_gps, SIGNAL(position(QPointF,qreal)),
410             m_mapEngine, SLOT(gpsPositionUpdate(QPointF,qreal)));
411
412     connect(m_gps, SIGNAL(timeout()),
413             m_ui, SLOT(gpsTimeout()));
414
415     connect(m_gps, SIGNAL(error(QString)),
416             this, SLOT(error(QString)));
417
418     connect(m_gps, SIGNAL(position(QPointF,qreal)),
419             this, SLOT(saveGPSPosition(QPointF)));
420 }
421
422 void SituareEngine::signalsFromMainWindow()
423 {
424     qDebug() << __PRETTY_FUNCTION__;    
425
426     connect(m_ui, SIGNAL(fetchUsernameFromSettings()),
427             this, SLOT(fetchUsernameFromSettings()));
428
429     connect(m_ui, SIGNAL(loginActionPressed()),
430             this, SLOT(loginActionPressed()));
431
432     connect(m_ui, SIGNAL(saveUsername(QString)),
433             m_facebookAuthenticator, SLOT(saveUsername(QString)));
434
435     connect(m_ui, SIGNAL(updateCredentials(QUrl)),
436             m_facebookAuthenticator, SLOT(updateCredentials(QUrl)));
437
438     // signals from map view
439     connect(m_ui, SIGNAL(mapViewScrolled(QPoint)),
440             m_mapEngine, SLOT(setLocation(QPoint)));
441
442     connect(m_ui, SIGNAL(mapViewResized(QSize)),
443             m_mapEngine, SLOT(viewResized(QSize)));
444
445     connect(m_ui, SIGNAL(viewZoomFinished()),
446             m_mapEngine, SLOT(viewZoomFinished()));
447
448     // signals from zoom buttons (zoom panel and volume buttons)
449     connect(m_ui, SIGNAL(zoomIn()),
450             m_mapEngine, SLOT(zoomIn()));
451
452     connect(m_ui, SIGNAL(zoomOut()),
453             m_mapEngine, SLOT(zoomOut()));
454
455     // signals from menu buttons
456     connect(m_ui, SIGNAL(autoCenteringTriggered(bool)),
457             this, SLOT(changeAutoCenteringSetting(bool)));
458
459     connect(m_ui, SIGNAL(gpsTriggered(bool)),
460             this, SLOT(enableGPS(bool)));
461
462     //signals from dialogs
463     connect(m_ui, SIGNAL(cancelLoginProcess()),
464             this, SLOT(loginProcessCancelled()));
465
466     connect(m_ui, SIGNAL(requestReverseGeo()),
467             this, SLOT(requestAddress()));
468
469     connect(m_ui, SIGNAL(statusUpdate(QString,bool)),
470             this, SLOT(requestUpdateLocation(QString,bool)));
471
472     connect(m_ui, SIGNAL(enableAutomaticLocationUpdate(bool, int)),
473             this, SLOT(enableAutomaticLocationUpdate(bool, int)));    
474
475     // signals from user info tab
476     connect(m_ui, SIGNAL(refreshUserData()),
477             this, SLOT(refreshUserData()));
478
479     connect (m_ui, SIGNAL(notificateUpdateFailing(QString)),
480              this, SLOT(error(QString)));
481
482     connect(m_ui, SIGNAL(findUser(QPointF)),
483             m_mapEngine, SLOT(setViewLocation(QPointF)));
484
485     // signals from friend list tab
486     connect(m_ui, SIGNAL(findFriend(QPointF)),
487             m_mapEngine, SLOT(setViewLocation(QPointF)));
488 }
489
490 void SituareEngine::signalsFromMapEngine()
491 {
492     qDebug() << __PRETTY_FUNCTION__;
493
494     connect(m_mapEngine, SIGNAL(error(QString)),
495             this, SLOT(error(QString)));
496
497     connect(m_mapEngine, SIGNAL(locationChanged(QPoint)),
498             m_ui, SIGNAL(centerToSceneCoordinates(QPoint)));
499
500     connect(m_mapEngine, SIGNAL(zoomLevelChanged(int)),
501             m_ui, SIGNAL(zoomLevelChanged(int)));
502
503     connect(m_mapEngine, SIGNAL(mapScrolledManually()),
504             this, SLOT(disableAutoCentering()));
505
506     connect(m_mapEngine, SIGNAL(maxZoomLevelReached()),
507             m_ui, SIGNAL(maxZoomLevelReached()));
508
509     connect(m_mapEngine, SIGNAL(minZoomLevelReached()),
510             m_ui, SIGNAL(minZoomLevelReached()));
511
512     connect(m_mapEngine, SIGNAL(locationItemClicked(QList<QString>)),
513             m_ui, SIGNAL(locationItemClicked(QList<QString>)));
514
515     connect(m_mapEngine, SIGNAL(newMapResolution(qreal)),
516             m_ui, SIGNAL(newMapResolution(qreal)));
517 }
518
519 void SituareEngine::signalsFromSituareService()
520 {
521     qDebug() << __PRETTY_FUNCTION__;
522
523     connect(m_situareService, SIGNAL(error(QString)),
524             this, SLOT(error(QString)));
525
526     connect(m_situareService, SIGNAL(reverseGeoReady(QString)),
527             m_ui, SIGNAL(reverseGeoReady(QString)));
528
529     connect(m_situareService, SIGNAL(userDataChanged(User*, QList<User*>&)),
530             this, SLOT(userDataChanged(User*, QList<User*>&)));
531
532     connect(m_situareService, SIGNAL(updateWasSuccessful()),
533             this, SLOT(updateWasSuccessful()));
534
535     connect(m_situareService, SIGNAL(updateWasSuccessful()),
536             m_ui, SIGNAL(updateWasSuccessful()));
537
538     connect(m_situareService, SIGNAL(error(QString)),
539             m_ui, SIGNAL(messageSendingFailed(QString)));
540 }
541
542 void SituareEngine::updateWasSuccessful()
543 {
544     qDebug() << __PRETTY_FUNCTION__;
545
546     m_situareService->fetchLocations();
547 }
548
549 void SituareEngine::userDataChanged(User *user, QList<User *> &friendsList)
550 {
551     qDebug() << __PRETTY_FUNCTION__;
552
553     m_ui->toggleProgressIndicator(false);
554
555     emit userLocationReady(user);
556     emit friendsLocationsReady(friendsList);
557 }