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