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