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