0b749bf3d39daa4751c98c3ad2062c2a5c89ce92
[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_automaticUpdateIntervalTimer(0),
50       m_lastUpdatedGPSPosition(QPointF()),
51       m_userMoved(false),
52       m_automaticUpdateEnabled(false)
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     m_gps->setMode(GPSPosition::Default);
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     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     m_ui->setGPSButtonEnabled(enabled);
158     m_mapEngine->setGPSEnabled(enabled);
159
160     if (enabled && !m_gps->isRunning()) {
161         m_gps->start();
162         enableAutoCentering(m_autoCenteringEnabled);
163         m_gps->requestLastPosition();
164
165         if (!m_automaticUpdateEnabled && m_loggedIn)
166             m_ui->requestAutomaticLocationUpdateSettings();
167     }
168     else if (!enabled && m_gps->isRunning()) {
169         m_gps->stop();
170         enableAutoCentering(false);
171         enableAutomaticLocationUpdate(false);
172     }
173 }
174
175 void SituareEngine::enableAutomaticLocationUpdate(bool enabled, int updateIntervalMsecs)
176 {
177     qDebug() << __PRETTY_FUNCTION__;
178
179     bool accepted = true;
180
181     m_automaticUpdateEnabled = enabled;
182
183     //Show automatic update confirmation dialog
184     if (m_automaticUpdateFirstStart && m_gps->isRunning() && m_automaticUpdateEnabled) {
185         m_ui->showEnableAutomaticUpdateLocationDialog(
186                 tr("Do you want to enable automatic location update with %1 min update interval?")
187                 .arg(updateIntervalMsecs/1000/60));
188         m_automaticUpdateFirstStart = false;
189     }
190     else {
191         if (!m_automaticUpdateFirstStart && m_automaticUpdateEnabled && accepted)
192             m_ui->buildInformationBox(tr("Automatic location update enabled"));
193
194         if (accepted && m_gps->isRunning() && m_automaticUpdateEnabled) {
195             if (updateIntervalMsecs < MIN_UPDATE_INTERVAL_MSECS)
196                 m_automaticUpdateIntervalTimer->setInterval(MIN_UPDATE_INTERVAL_MSECS);
197             else
198                 m_automaticUpdateIntervalTimer->setInterval(updateIntervalMsecs);
199
200             m_automaticUpdateIntervalTimer->start();
201
202         } else {
203             m_automaticUpdateIntervalTimer->stop();
204         }
205     }
206 }
207
208 void SituareEngine::error(const QString &error)
209 {
210     qDebug() << __PRETTY_FUNCTION__;
211     qDebug() << "ERROR MESSAGE: " << error;
212
213     m_ui->buildInformationBox(error, true);
214
215     if(error.compare(SESSION_EXPIRED) == 0) {
216         m_facebookAuthenticator->clearAccountInformation(true); // keep username = true
217         m_ui->loggedIn(false);
218         m_ui->loginFailed();
219     }
220 }
221
222 void SituareEngine::fetchUsernameFromSettings()
223 {
224     qDebug() << __PRETTY_FUNCTION__;
225
226     m_ui->setUsername(m_facebookAuthenticator->loadUsername());
227 }
228
229 void SituareEngine::initializeGpsAndAutocentering()
230 {
231     qDebug() << __PRETTY_FUNCTION__;
232
233     QSettings settings(DIRECTORY_NAME, FILE_NAME);
234     QVariant gpsEnabled = settings.value(SETTINGS_GPS_ENABLED);
235     QVariant autoCenteringEnabled = settings.value(SETTINGS_AUTO_CENTERING_ENABLED);     
236
237     if (gpsEnabled.toString().isEmpty()) { // First start. Situare.conf file does not exists
238
239         connect(m_gps, SIGNAL(position(QPointF,qreal)),
240                 this, SLOT(setFirstStartZoomLevel(QPointF,qreal)));
241
242         changeAutoCenteringSetting(true);
243         enableGPS(true);
244
245         m_ui->buildInformationBox(tr("GPS enabled"));
246         m_ui->buildInformationBox(tr("Auto centering enabled"));
247
248     } else { // Normal start
249         changeAutoCenteringSetting(autoCenteringEnabled.toBool());
250         enableGPS(gpsEnabled.toBool());
251
252         if (gpsEnabled.toBool())
253             m_ui->buildInformationBox(tr("GPS enabled"));
254
255         if (gpsEnabled.toBool() && autoCenteringEnabled.toBool())
256             m_ui->buildInformationBox(tr("Auto centering enabled"));
257     }
258 }
259
260 bool SituareEngine::isUserMoved()
261 {
262     qDebug() << __PRETTY_FUNCTION__;
263
264     return m_userMoved;
265 }
266
267 void SituareEngine::loginActionPressed()
268 {
269     qDebug() << __PRETTY_FUNCTION__;
270
271     if(m_loggedIn) {
272         logout();
273         m_situareService->clearUserData();
274     }
275     else {
276         m_facebookAuthenticator->start();
277     }
278 }
279
280 void SituareEngine::loginOk()
281 {
282     qWarning() << __PRETTY_FUNCTION__;
283
284     m_loggedIn = true;
285     m_ui->loggedIn(m_loggedIn);
286
287     m_ui->show();
288     m_situareService->fetchLocations(); // request user locations
289
290     if (m_gps->isRunning())
291         m_ui->requestAutomaticLocationUpdateSettings();
292 }
293
294 void SituareEngine::loginProcessCancelled()
295 {
296     qDebug() << __PRETTY_FUNCTION__;
297
298     m_ui->toggleProgressIndicator(false);
299     m_ui->updateItemVisibility(m_loggedIn);
300 }
301
302 void SituareEngine::logout()
303 {
304     qDebug() << __PRETTY_FUNCTION__;
305
306     m_loggedIn = false;
307     m_ui->loggedIn(m_loggedIn);
308     m_facebookAuthenticator->clearAccountInformation(); // clear all
309 }
310
311 void SituareEngine::refreshUserData()
312 {
313     qDebug() << __PRETTY_FUNCTION__;
314
315     m_ui->toggleProgressIndicator(true);
316
317     m_situareService->fetchLocations();
318 }
319
320 void SituareEngine::requestAddress()
321 {
322     qDebug() << __PRETTY_FUNCTION__;
323
324     if (m_gps->isRunning())
325         m_situareService->reverseGeo(m_gps->lastPosition());
326     else
327         m_situareService->reverseGeo(m_mapEngine->centerGeoCoordinate());
328 }
329
330 void SituareEngine::requestUpdateLocation(const QString &status, bool publish)
331 {
332     qDebug() << __PRETTY_FUNCTION__;
333
334     m_ui->toggleProgressIndicator(true);
335
336     if (m_gps->isRunning())
337         m_situareService->updateLocation(m_gps->lastPosition(), status, publish);
338     else
339         m_situareService->updateLocation(m_mapEngine->centerGeoCoordinate(), status, publish);
340 }
341
342 void SituareEngine::saveGPSPosition(QPointF position)
343 {
344     qDebug() << __PRETTY_FUNCTION__;
345
346     if ((fabs(m_lastUpdatedGPSPosition.x() - position.x()) >
347          USER_MOVEMENT_MINIMUM_LONGITUDE_DIFFERENCE) ||
348         (fabs(m_lastUpdatedGPSPosition.y() - position.y()) >
349          USER_MOVEMENT_MINIMUM_LATITUDE_DIFFERENCE)) {
350
351         m_lastUpdatedGPSPosition = position;
352         m_userMoved = true;
353     }
354 }
355
356 void SituareEngine::setFirstStartZoomLevel(QPointF latLonCoordinate, qreal accuracy)
357 {
358     qDebug() << __PRETTY_FUNCTION__;
359
360     Q_UNUSED(latLonCoordinate);
361     Q_UNUSED(accuracy);
362
363     if (m_autoCenteringEnabled) // autocentering is disabled when map is scrolled        
364         m_mapEngine->setZoomLevel(DEFAULT_ZOOM_LEVEL_WHEN_GPS_IS_AVAILABLE);
365
366     disconnect(m_gps, SIGNAL(position(QPointF,qreal)),
367                this, SLOT(setFirstStartZoomLevel(QPointF,qreal)));
368 }
369
370 void SituareEngine::signalsFromFacebookAuthenticator()
371 {
372     qDebug() << __PRETTY_FUNCTION__;
373
374     connect(m_facebookAuthenticator, SIGNAL(error(QString)),
375             this, SLOT(error(QString)));
376
377     connect(m_facebookAuthenticator, SIGNAL(credentialsReady(FacebookCredentials)),
378             m_situareService, SLOT(credentialsReady(FacebookCredentials)));
379
380     connect(m_facebookAuthenticator, SIGNAL(credentialsReady(FacebookCredentials)),
381             this, SLOT(loginOk()));
382
383     connect(m_facebookAuthenticator, SIGNAL(newLoginRequest()),
384             m_ui, SLOT(startLoginProcess()));
385
386     connect(m_facebookAuthenticator, SIGNAL(loginFailure()),
387             m_ui, SLOT(loginFailed()));
388
389     connect(m_facebookAuthenticator, SIGNAL(saveCookiesRequest()),
390             m_ui, SLOT(saveCookies()));
391
392     connect(m_facebookAuthenticator, SIGNAL(loginUsingCookies()),
393             m_ui, SLOT(loginUsingCookies()));
394 }
395
396 void SituareEngine::signalsFromGPS()
397 {
398     qDebug() << __PRETTY_FUNCTION__;
399
400     connect(m_gps, SIGNAL(position(QPointF,qreal)),
401             m_mapEngine, SLOT(gpsPositionUpdate(QPointF,qreal)));
402
403     connect(m_gps, SIGNAL(timeout()),
404             m_ui, SLOT(gpsTimeout()));
405
406     connect(m_gps, SIGNAL(error(QString)),
407             this, SLOT(error(QString)));
408
409     connect(m_gps, SIGNAL(position(QPointF,qreal)),
410             this, SLOT(saveGPSPosition(QPointF)));
411 }
412
413 void SituareEngine::signalsFromMainWindow()
414 {
415     qDebug() << __PRETTY_FUNCTION__;    
416
417     connect(m_ui, SIGNAL(fetchUsernameFromSettings()),
418             this, SLOT(fetchUsernameFromSettings()));
419
420     connect(m_ui, SIGNAL(loginActionPressed()),
421             this, SLOT(loginActionPressed()));
422
423     connect(m_ui, SIGNAL(saveUsername(QString)),
424             m_facebookAuthenticator, SLOT(saveUsername(QString)));
425
426     connect(m_ui, SIGNAL(updateCredentials(QUrl)),
427             m_facebookAuthenticator, SLOT(updateCredentials(QUrl)));
428
429     // signals from map view
430     connect(m_ui, SIGNAL(mapViewScrolled(QPoint)),
431             m_mapEngine, SLOT(setLocation(QPoint)));
432
433     connect(m_ui, SIGNAL(mapViewResized(QSize)),
434             m_mapEngine, SLOT(viewResized(QSize)));
435
436     connect(m_ui, SIGNAL(viewZoomFinished()),
437             m_mapEngine, SLOT(viewZoomFinished()));
438
439     // signals from zoom buttons (zoom panel and volume buttons)
440     connect(m_ui, SIGNAL(zoomIn()),
441             m_mapEngine, SLOT(zoomIn()));
442
443     connect(m_ui, SIGNAL(zoomOut()),
444             m_mapEngine, SLOT(zoomOut()));
445
446     // signals from menu buttons
447     connect(m_ui, SIGNAL(autoCenteringTriggered(bool)),
448             this, SLOT(changeAutoCenteringSetting(bool)));
449
450     connect(m_ui, SIGNAL(gpsTriggered(bool)),
451             this, SLOT(enableGPS(bool)));
452
453     //signals from dialogs
454     connect(m_ui, SIGNAL(cancelLoginProcess()),
455             this, SLOT(loginProcessCancelled()));
456
457     connect(m_ui, SIGNAL(requestReverseGeo()),
458             this, SLOT(requestAddress()));
459
460     connect(m_ui, SIGNAL(statusUpdate(QString,bool)),
461             this, SLOT(requestUpdateLocation(QString,bool)));
462
463     connect(m_ui, SIGNAL(enableAutomaticLocationUpdate(bool, int)),
464             this, SLOT(enableAutomaticLocationUpdate(bool, int)));    
465
466     // signals from user info tab
467     connect(m_ui, SIGNAL(refreshUserData()),
468             this, SLOT(refreshUserData()));
469
470     connect (m_ui, SIGNAL(notificateUpdateFailing(QString)),
471              this, SLOT(error(QString)));
472
473     connect(m_ui, SIGNAL(findUser(QPointF)),
474             m_mapEngine, SLOT(setViewLocation(QPointF)));
475
476     // signals from friend list tab
477     connect(m_ui, SIGNAL(findFriend(QPointF)),
478             m_mapEngine, SLOT(setViewLocation(QPointF)));
479 }
480
481 void SituareEngine::signalsFromMapEngine()
482 {
483     qDebug() << __PRETTY_FUNCTION__;
484
485     connect(m_mapEngine, SIGNAL(error(QString)),
486             this, SLOT(error(QString)));
487
488     connect(m_mapEngine, SIGNAL(locationChanged(QPoint)),
489             m_ui, SIGNAL(centerToSceneCoordinates(QPoint)));
490
491     connect(m_mapEngine, SIGNAL(zoomLevelChanged(int)),
492             m_ui, SIGNAL(zoomLevelChanged(int)));
493
494     connect(m_mapEngine, SIGNAL(mapScrolledManually()),
495             this, SLOT(disableAutoCentering()));
496
497     connect(m_mapEngine, SIGNAL(maxZoomLevelReached()),
498             m_ui, SIGNAL(maxZoomLevelReached()));
499
500     connect(m_mapEngine, SIGNAL(minZoomLevelReached()),
501             m_ui, SIGNAL(minZoomLevelReached()));
502
503     connect(m_mapEngine, SIGNAL(locationItemClicked(QList<QString>)),
504             m_ui, SIGNAL(locationItemClicked(QList<QString>)));
505
506     connect(m_mapEngine, SIGNAL(newMapResolution(qreal)),
507             m_ui, SIGNAL(newMapResolution(qreal)));
508 }
509
510 void SituareEngine::signalsFromSituareService()
511 {
512     qDebug() << __PRETTY_FUNCTION__;
513
514     connect(m_situareService, SIGNAL(error(QString)),
515             this, SLOT(error(QString)));
516
517     connect(m_situareService, SIGNAL(reverseGeoReady(QString)),
518             m_ui, SIGNAL(reverseGeoReady(QString)));
519
520     connect(m_situareService, SIGNAL(userDataChanged(User*, QList<User*>&)),
521             this, SLOT(userDataChanged(User*, QList<User*>&)));
522
523     connect(m_situareService, SIGNAL(updateWasSuccessful()),
524             this, SLOT(updateWasSuccessful()));
525
526     connect(m_situareService, SIGNAL(updateWasSuccessful()),
527             m_ui, SIGNAL(updateWasSuccessful()));
528
529     connect(m_situareService, SIGNAL(error(QString)),
530             m_ui, SIGNAL(messageSendingFailed(QString)));
531 }
532
533 void SituareEngine::updateWasSuccessful()
534 {
535     qDebug() << __PRETTY_FUNCTION__;
536
537     m_situareService->fetchLocations();
538 }
539
540 void SituareEngine::userDataChanged(User *user, QList<User *> &friendsList)
541 {
542     qDebug() << __PRETTY_FUNCTION__;
543
544     m_ui->toggleProgressIndicator(false);
545
546     emit userLocationReady(user);
547     emit friendsLocationsReady(friendsList);
548 }