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