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