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