Merge branch 'master' into situare_interact
[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 <cmath>
26
27 #include <QMessageBox>
28 #include <QNetworkReply>
29
30 #include "application.h"
31 #include "common.h"
32 #include "contactmanager.h"
33 #include "../error.h"
34 #include "facebookservice/facebookauthentication.h"
35 #include "gps/gpsposition.h"
36 #include "map/mapengine.h"
37 #include "routing/geocodingservice.h"
38 #include "routing/routingservice.h"
39 #include "mce.h"
40 #include "network/networkaccessmanager.h"
41 #include "situareservice/situareservice.h"
42 #include "ui/mainwindow.h"
43
44 #include "engine.h"
45
46 const QString SETTINGS_GPS_ENABLED = "GPS_ENABLED"; ///< GPS setting
47 const QString SETTINGS_AUTO_CENTERING_ENABLED = "AUTO_CENTERING_ENABLED";///< Auto centering setting
48 const int DEFAULT_ZOOM_LEVEL_WHEN_GPS_IS_AVAILABLE = 12;  ///< Default zoom level when GPS available
49 const qreal USER_MOVEMENT_MINIMUM_LONGITUDE_DIFFERENCE = 0.003;///< Min value for user move latitude
50 const qreal USER_MOVEMENT_MINIMUM_LATITUDE_DIFFERENCE = 0.001;///< Min value for user move longitude
51 const int MIN_UPDATE_INTERVAL_MSECS = 5*60*1000;
52
53 SituareEngine::SituareEngine()
54     : m_autoCenteringEnabled(false),
55       m_automaticUpdateFirstStart(true),
56       m_automaticUpdateRequest(false),
57       m_userMoved(false),
58       m_automaticUpdateIntervalTimer(0),
59       m_lastUpdatedGPSPosition(GeoCoordinate())
60 {
61     qDebug() << __PRETTY_FUNCTION__;
62
63     m_ui = new MainWindow;
64     m_ui->updateItemVisibility();
65
66     Application *application = static_cast<Application *>(qApp);
67     application->registerWindow(m_ui->winId());
68
69     connect(application, SIGNAL(topmostWindowChanged(bool)),
70             this, SLOT(topmostWindowChanged(bool)));
71
72     m_networkAccessManager = new NetworkAccessManager(this);
73
74     // build MapEngine
75     m_mapEngine = new MapEngine(this);
76     m_ui->setMapViewScene(m_mapEngine->scene());
77
78     // build GPS
79     m_gps = new GPSPosition(this);
80
81     // build SituareService
82     m_situareService = new SituareService(this);
83
84     // build FacebookAuthenticator
85     m_facebookAuthenticator = new FacebookAuthentication(this);
86
87     // build routing service
88     m_routingService = new RoutingService(this); // create this when needed, not in constructor!
89
90     // build geocoding service
91     m_geocodingService = new GeocodingService(this);
92
93     // connect signals
94     signalsFromMapEngine();
95     signalsFromGeocodingService();
96     signalsFromGPS();
97     signalsFromRoutingService();
98     signalsFromSituareService();
99     signalsFromMainWindow();
100     signalsFromFacebookAuthenticator();
101
102     connect(this, SIGNAL(userLocationReady(User*)),
103             m_ui, SIGNAL(userLocationReady(User*)));
104
105     connect(this, SIGNAL(friendsLocationsReady(QList<User*>&)),
106             m_ui, SIGNAL(friendsLocationsReady(QList<User*>&)));
107
108     connect(this, SIGNAL(userLocationReady(User*)),
109             m_mapEngine, SLOT(receiveOwnLocation(User*)));
110
111     connect(this, SIGNAL(friendsLocationsReady(QList<User*>&)),
112             m_mapEngine, SIGNAL(friendsLocationsReady(QList<User*>&)));
113
114     connect(this, SIGNAL(userImageReady(QString,QPixmap)),
115             m_ui, SIGNAL(userImageReady(QString,QPixmap)));
116
117     connect(this, SIGNAL(friendImageReady(QString,QPixmap)),
118             m_ui, SIGNAL(friendImageReady(QString,QPixmap)));
119
120     connect(this, SIGNAL(friendImageReady(QString,QPixmap)),
121             m_mapEngine, SIGNAL(friendImageReady(QString,QPixmap)));
122
123     m_automaticUpdateIntervalTimer = new QTimer(this);
124     connect(m_automaticUpdateIntervalTimer, SIGNAL(timeout()),
125             this, SLOT(startAutomaticUpdate()));
126
127     // signals connected, now it's time to show the main window
128     // but init the MapEngine before so starting location is set
129     m_mapEngine->init();
130     m_ui->show();
131
132     m_facebookAuthenticator->start();
133
134     m_gps->setMode(GPSPosition::Default);
135     initializeGpsAndAutocentering();
136
137     m_mce = new MCE(this);
138     connect(m_mce, SIGNAL(displayOff(bool)), this, SLOT(setPowerSaving(bool)));
139     
140     m_contactManager = new ContactManager(this);
141     m_contactManager->requestContactGuids();
142 }
143
144 SituareEngine::~SituareEngine()
145 {
146     qDebug() << __PRETTY_FUNCTION__;
147
148     delete m_ui;
149
150     QSettings settings(DIRECTORY_NAME, FILE_NAME);
151     settings.setValue(SETTINGS_GPS_ENABLED, m_gps->isRunning());
152     settings.setValue(SETTINGS_AUTO_CENTERING_ENABLED, m_autoCenteringEnabled);
153 }
154
155 void SituareEngine::changeAutoCenteringSetting(bool enabled)
156 {
157     qDebug() << __PRETTY_FUNCTION__ << enabled;
158
159     m_autoCenteringEnabled = enabled;
160     setAutoCentering(enabled);
161 }
162
163 void SituareEngine::disableAutoCentering()
164 {
165     qDebug() << __PRETTY_FUNCTION__;
166
167     changeAutoCenteringSetting(false);
168 }
169
170 void SituareEngine::draggingModeTriggered()
171 {
172     qDebug() << __PRETTY_FUNCTION__;
173
174     if (m_mce)
175         m_mce->vibrationFeedback();
176 }
177
178 void SituareEngine::enableAutomaticLocationUpdate(bool enabled, int updateIntervalMsecs)
179 {
180     qDebug() << __PRETTY_FUNCTION__;
181
182     //Show automatic update confirmation dialog
183     if (m_automaticUpdateFirstStart && m_gps->isRunning() && enabled) {
184         m_ui->showEnableAutomaticUpdateLocationDialog(
185                 tr("Do you want to enable automatic location update with %1 min update interval?")
186                 .arg(updateIntervalMsecs/1000/60));
187         m_automaticUpdateFirstStart = false;
188     } else {
189         if (enabled && m_gps->isRunning()) {
190             m_ui->buildInformationBox(tr("Automatic location update enabled"));
191             if (updateIntervalMsecs < MIN_UPDATE_INTERVAL_MSECS)
192                 m_automaticUpdateIntervalTimer->setInterval(MIN_UPDATE_INTERVAL_MSECS);
193             else
194                 m_automaticUpdateIntervalTimer->setInterval(updateIntervalMsecs);
195
196             connect(m_gps, SIGNAL(position(GeoCoordinate, qreal)),
197                     this, SLOT(requestAutomaticUpdateIfMoved(GeoCoordinate)));
198
199             m_automaticUpdateIntervalTimer->start();
200
201         } else {
202             disconnect(m_gps, SIGNAL(position(GeoCoordinate, qreal)),
203                     this, SLOT(requestAutomaticUpdateIfMoved(GeoCoordinate)));
204
205             m_automaticUpdateIntervalTimer->stop();
206         }
207     }
208 }
209
210 void SituareEngine::error(const int context, const int error)
211 {
212     qDebug() << __PRETTY_FUNCTION__;
213
214     switch(error)
215     {
216     case SituareError::ERROR_GENERAL:
217         if(context == ErrorContext::SITUARE) {
218             m_ui->toggleProgressIndicator(false);
219             m_ui->buildInformationBox(tr("Unknown server error"), true);
220         }
221         break;
222     case 1: //errors: SituareError::ERROR_MISSING_ARGUMENT and QNetworkReply::ConnectionRefusedError
223         m_ui->toggleProgressIndicator(false);
224         if(context == ErrorContext::SITUARE) {
225             m_ui->buildInformationBox(tr("Missing parameter from request"), true);
226         } else if(context == ErrorContext::NETWORK) {
227             m_ui->buildInformationBox(tr("Connection refused by the server"), true);
228         }
229         break;
230     case QNetworkReply::RemoteHostClosedError:
231         if(context == ErrorContext::NETWORK) {
232             m_ui->toggleProgressIndicator(false);
233             m_ui->buildInformationBox(tr("Connection closed by the server"), true);
234         }
235         break;
236     case QNetworkReply::HostNotFoundError:
237         if(context == ErrorContext::NETWORK) {
238             m_ui->toggleProgressIndicator(false);
239             m_ui->buildInformationBox(tr("Remote server not found"), true);
240         }
241         break;
242     case QNetworkReply::TimeoutError:
243         if(context == ErrorContext::NETWORK) {
244             m_ui->toggleProgressIndicator(false);
245             m_ui->buildInformationBox(tr("Connection timed out"), true);
246         }
247         break;
248     case QNetworkReply::UnknownNetworkError:
249         if(context == ErrorContext::NETWORK) {
250             m_ui->toggleProgressIndicator(false);
251             m_ui->buildInformationBox(tr("No network connection"), true);
252         }
253         break;
254     case SituareError::SESSION_EXPIRED:
255         m_ui->buildInformationBox(tr("Session expired. Please login again"), true);
256         m_facebookAuthenticator->clearAccountInformation(true); // keep username = true
257         m_situareService->clearUserData();
258         m_ui->loggedIn(false);
259         m_ui->loginFailed();
260         break;
261     case SituareError::LOGIN_FAILED:
262         m_ui->toggleProgressIndicator(false);
263         m_ui->buildInformationBox(tr("Invalid E-mail address or password"), true);
264         m_ui->loginFailed();
265         break;
266     case SituareError::UPDATE_FAILED:
267         m_ui->toggleProgressIndicator(false);
268         m_ui->buildInformationBox(tr("Update failed, please try again"), true);
269         break;
270     case SituareError::DATA_RETRIEVAL_FAILED:
271         m_ui->toggleProgressIndicator(false);
272         m_ui->buildInformationBox(tr("Data retrieval failed, please try again"), true);
273         break;
274     case SituareError::ADDRESS_RETRIEVAL_FAILED:
275         m_ui->toggleProgressIndicator(false);
276         m_ui->buildInformationBox(tr("Address retrieval failed"), true);
277         break;
278     case SituareError::IMAGE_DOWNLOAD_FAILED:
279         m_ui->buildInformationBox(tr("Image download failed"), true);
280         break;
281     case SituareError::MAP_IMAGE_DOWNLOAD_FAILED:
282         m_ui->buildInformationBox(tr("Map image download failed"), true);
283         break;
284     case SituareError::GPS_INITIALIZATION_FAILED:
285         setGPS(false);
286         m_ui->buildInformationBox(tr("GPS initialization failed"), true);
287         break;
288     case SituareError::INVALID_JSON:
289         m_ui->buildInformationBox(tr("Malformatted reply from server"), true);
290         m_ui->loggedIn(false);
291         m_facebookAuthenticator->clearAccountInformation(false); // clean all
292         break;
293     case SituareError::ERROR_ROUTING_FAILED:
294         m_ui->toggleProgressIndicator(false);
295         m_ui->buildInformationBox(tr("Routing failed"), true);
296         break;
297     case SituareError::ERROR_LOCATION_SEARCH_FAILED:
298         m_ui->buildInformationBox(tr("No results found"), true);
299         break;
300     default:
301         m_ui->toggleProgressIndicator(false);
302         if(context == ErrorContext::NETWORK)
303             qCritical() << __PRETTY_FUNCTION__ << "QNetworkReply::NetworkError: " << error;
304         else
305             qCritical() << __PRETTY_FUNCTION__ << "Unknown error: " << error;
306         break;
307     }
308 }
309
310 void SituareEngine::fetchUsernameFromSettings()
311 {
312     qDebug() << __PRETTY_FUNCTION__;
313
314     m_ui->setUsername(m_facebookAuthenticator->loadUsername());
315 }
316
317 void SituareEngine::imageReady(const QString &id, const QPixmap &image)
318 {
319     qDebug() << __PRETTY_FUNCTION__;
320
321     if(m_facebookAuthenticator->loginCredentials().userID() == id)
322         emit userImageReady(id, image);
323     else
324         emit friendImageReady(id, image);
325 }
326
327 void SituareEngine::initializeGpsAndAutocentering()
328 {
329     qDebug() << __PRETTY_FUNCTION__;
330
331     QSettings settings(DIRECTORY_NAME, FILE_NAME);
332     QVariant gpsEnabled = settings.value(SETTINGS_GPS_ENABLED);
333     QVariant autoCenteringEnabled = settings.value(SETTINGS_AUTO_CENTERING_ENABLED);
334
335     if (m_gps->isInitialized()) {
336
337         if (gpsEnabled.toString().isEmpty()) { // First start. Situare.conf file does not exists
338
339             connect(m_gps, SIGNAL(position(GeoCoordinate, qreal)),
340                     this, SLOT(setFirstStartZoomLevel()));
341
342             changeAutoCenteringSetting(true);
343             setGPS(true);
344
345             m_ui->buildInformationBox(tr("GPS enabled"));
346
347         } else { // Normal start
348             changeAutoCenteringSetting(autoCenteringEnabled.toBool());
349             setGPS(gpsEnabled.toBool());
350
351             if (gpsEnabled.toBool())
352                 m_ui->buildInformationBox(tr("GPS enabled"));
353         }
354     } else {
355         setGPS(false);
356     }
357 }
358
359 void SituareEngine::locationSearch(QString location)
360 {
361     qDebug() << __PRETTY_FUNCTION__;
362
363     if(!location.isEmpty())
364         m_geocodingService->requestLocation(location);
365 }
366
367 void SituareEngine::loginActionPressed()
368 {
369     qDebug() << __PRETTY_FUNCTION__;
370
371     if (m_networkAccessManager->isConnected()) {
372         if(m_ui->loginState()) {
373             logout();
374             m_situareService->clearUserData();
375         } else {
376             m_facebookAuthenticator->start();
377         }
378     }
379     else {
380         error(ErrorContext::NETWORK, QNetworkReply::UnknownNetworkError);
381     }
382 }
383
384 void SituareEngine::loginOk()
385 {
386     qDebug() << __PRETTY_FUNCTION__;
387
388     m_ui->loggedIn(true);
389
390     m_ui->show();
391     m_situareService->fetchLocations(); // request user locations
392
393     if (m_gps->isRunning())
394         m_ui->readAutomaticLocationUpdateSettings();
395 }
396
397 void SituareEngine::loginProcessCancelled()
398 {
399     qDebug() << __PRETTY_FUNCTION__;
400
401     m_ui->toggleProgressIndicator(false);
402     m_ui->updateItemVisibility();
403 }
404
405 void SituareEngine::logout()
406 {
407     qDebug() << __PRETTY_FUNCTION__;
408
409     m_ui->loggedIn(false);
410
411     // signal to clear locationUpdateDialog's data
412     connect(this, SIGNAL(clearUpdateLocationDialogData()),
413             m_ui, SIGNAL(clearUpdateLocationDialogData()));
414     emit clearUpdateLocationDialogData();
415
416     m_facebookAuthenticator->clearAccountInformation(); // clear all
417     m_automaticUpdateFirstStart = true;
418 }
419
420 void SituareEngine::refreshUserData()
421 {
422     qDebug() << __PRETTY_FUNCTION__;
423
424     if (m_networkAccessManager->isConnected()) {
425         m_ui->toggleProgressIndicator(true);
426         m_situareService->fetchLocations();
427     }
428     else {
429         error(ErrorContext::NETWORK, QNetworkReply::UnknownNetworkError);
430     }
431 }
432
433 void SituareEngine::requestAddress()
434 {
435     qDebug() << __PRETTY_FUNCTION__;
436
437     if (m_networkAccessManager->isConnected()) {
438         if (m_gps->isRunning())
439             m_situareService->reverseGeo(m_gps->lastPosition());
440         else
441             m_situareService->reverseGeo(m_mapEngine->centerGeoCoordinate());
442     }
443     else {
444         error(ErrorContext::NETWORK, QNetworkReply::UnknownNetworkError);
445     }
446 }
447
448 void SituareEngine::requestUpdateLocation(const QString &status, bool publish)
449 {
450     qDebug() << __PRETTY_FUNCTION__;
451
452     if (m_networkAccessManager->isConnected()) {
453         m_ui->toggleProgressIndicator(true);
454
455         if (m_gps->isRunning())
456             m_situareService->updateLocation(m_gps->lastPosition(), status, publish);
457         else
458             m_situareService->updateLocation(m_mapEngine->centerGeoCoordinate(), status, publish);
459     }
460     else {
461         error(ErrorContext::NETWORK, QNetworkReply::UnknownNetworkError);
462     }
463 }
464
465 void SituareEngine::requestAutomaticUpdateIfMoved(GeoCoordinate position)
466 {
467     qDebug() << __PRETTY_FUNCTION__;
468
469     if ((fabs(m_lastUpdatedGPSPosition.longitude() - position.longitude()) >
470          USER_MOVEMENT_MINIMUM_LONGITUDE_DIFFERENCE) ||
471         (fabs(m_lastUpdatedGPSPosition.latitude() - position.latitude()) >
472          USER_MOVEMENT_MINIMUM_LATITUDE_DIFFERENCE)) {
473
474         m_lastUpdatedGPSPosition = position;
475         m_userMoved = true;
476     }
477
478     if (m_automaticUpdateRequest && m_userMoved) {
479         requestUpdateLocation(tr("Automatic location update"));
480         m_automaticUpdateRequest = false;
481         m_userMoved = false;
482     }
483 }
484
485 void SituareEngine::requestInterestingPeople()
486 {
487     qDebug() << __PRETTY_FUNCTION__;
488
489     QRectF currentSceneRect = m_mapEngine->currentViewSceneRect();
490     SceneCoordinate bottomLeftSceneCoordinate(currentSceneRect.left(), currentSceneRect.bottom());
491     SceneCoordinate topRightSceneCoordinate(currentSceneRect.right(), currentSceneRect.top());
492
493     m_situareService->fetchPeopleWithSimilarInterest(GeoCoordinate(bottomLeftSceneCoordinate),
494                                                      GeoCoordinate(topRightSceneCoordinate));
495 }
496
497 void SituareEngine::routeParsed(Route &route)
498 {
499     qDebug() << __PRETTY_FUNCTION__;
500
501     Q_UNUSED(route);
502
503     m_ui->toggleProgressIndicator(false);
504 }
505
506 void SituareEngine::routeTo(const GeoCoordinate &endPointCoordinates)
507 {
508     qDebug() << __PRETTY_FUNCTION__;
509
510     m_ui->toggleProgressIndicator(true);
511
512     if (m_gps->isRunning())
513         m_routingService->requestRoute(m_gps->lastPosition(), endPointCoordinates);
514     else
515         m_routingService->requestRoute(m_mapEngine->centerGeoCoordinate(), endPointCoordinates);
516 }
517
518 void SituareEngine::routeToCursor()
519 {
520     qDebug() << __PRETTY_FUNCTION__;
521
522     routeTo(m_mapEngine->centerGeoCoordinate());
523 }
524
525 void SituareEngine::setAutoCentering(bool enabled)
526 {
527     qDebug() << __PRETTY_FUNCTION__ << enabled;
528
529     m_ui->setIndicatorButtonEnabled(enabled);
530     m_mapEngine->setAutoCentering(enabled);
531     m_ui->setCrosshairVisibility(!enabled);
532
533     if (enabled) {
534         setGPS(true);
535         m_gps->requestLastPosition();
536     }
537 }
538
539 void SituareEngine::setFirstStartZoomLevel()
540 {
541     qDebug() << __PRETTY_FUNCTION__;
542
543     if (m_autoCenteringEnabled) // autocentering is disabled when map is scrolled
544         m_mapEngine->setZoomLevel(DEFAULT_ZOOM_LEVEL_WHEN_GPS_IS_AVAILABLE);
545
546     disconnect(m_gps, SIGNAL(position(GeoCoordinate, qreal)),
547                this, SLOT(setFirstStartZoomLevel()));
548 }
549
550 void SituareEngine::setGPS(bool enabled)
551 {
552     qDebug() << __PRETTY_FUNCTION__ << enabled;
553
554     if (m_gps->isInitialized()) {
555         m_ui->setGPSButtonEnabled(enabled);
556         m_mapEngine->setGPSEnabled(enabled);
557
558         if (enabled && !m_gps->isRunning()) {
559             m_gps->start();
560             m_gps->requestLastPosition();
561
562             if(m_ui->loginState())
563                 m_ui->readAutomaticLocationUpdateSettings();
564         }
565         else if (!enabled && m_gps->isRunning()) {
566             m_gps->stop();
567             changeAutoCenteringSetting(false);
568             enableAutomaticLocationUpdate(false);
569         }
570     }
571     else {
572         if (enabled)
573             m_ui->buildInformationBox(tr("Unable to start GPS"));
574         m_ui->setGPSButtonEnabled(false);
575         m_mapEngine->setGPSEnabled(false);
576     }
577 }
578
579 void SituareEngine::setPowerSaving(bool enabled)
580 {
581     qDebug() << __PRETTY_FUNCTION__ << enabled;
582
583     m_gps->enablePowerSave(enabled);
584
585     if(m_autoCenteringEnabled)
586         m_mapEngine->setAutoCentering(!enabled);
587 }
588
589 void SituareEngine::showContactDialog(const QString &facebookId)
590 {
591     qDebug() << __PRETTY_FUNCTION__;
592
593     QString guid = m_contactManager->contactGuid(facebookId);
594
595     if (!guid.isEmpty())
596         m_ui->showContactDialog(guid);
597     else
598         m_ui->buildInformationBox(tr("Unable to find contact.\nAdd Facebook IM "
599                                      "account from Conversations to use this feature."), true);
600 }
601
602 void SituareEngine::signalsFromFacebookAuthenticator()
603 {
604     qDebug() << __PRETTY_FUNCTION__;
605
606     connect(m_facebookAuthenticator, SIGNAL(error(int, int)),
607             this, SLOT(error(int, int)));
608
609     connect(m_facebookAuthenticator, SIGNAL(credentialsReady(FacebookCredentials)),
610             m_situareService, SLOT(credentialsReady(FacebookCredentials)));
611
612     connect(m_facebookAuthenticator, SIGNAL(credentialsReady(FacebookCredentials)),
613             this, SLOT(loginOk()));
614
615     connect(m_facebookAuthenticator, SIGNAL(newLoginRequest()),
616             m_ui, SLOT(startLoginProcess()));
617
618     connect(m_facebookAuthenticator, SIGNAL(saveCookiesRequest()),
619             m_ui, SLOT(saveCookies()));
620
621     connect(m_facebookAuthenticator, SIGNAL(loginUsingCookies()),
622             m_ui, SLOT(loginUsingCookies()));
623 }
624
625 void SituareEngine::signalsFromGeocodingService()
626 {
627     qDebug() << __PRETTY_FUNCTION__;
628
629     connect(m_geocodingService, SIGNAL(locationDataParsed(const QList<Location>&)),
630             m_ui, SIGNAL(locationDataParsed(const QList<Location>&)));
631
632     connect(m_geocodingService, SIGNAL(error(int, int)),
633             this, SLOT(error(int, int)));
634 }
635
636 void SituareEngine::signalsFromGPS()
637 {
638     qDebug() << __PRETTY_FUNCTION__;
639
640     connect(m_gps, SIGNAL(position(GeoCoordinate, qreal)),
641             m_mapEngine, SLOT(gpsPositionUpdate(GeoCoordinate, qreal)));
642
643     connect(m_gps, SIGNAL(timeout()),
644             m_ui, SLOT(gpsTimeout()));
645
646     connect(m_gps, SIGNAL(error(int, int)),
647             this, SLOT(error(int, int)));
648 }
649
650 void SituareEngine::signalsFromMainWindow()
651 {
652     qDebug() << __PRETTY_FUNCTION__;
653
654     connect(m_ui, SIGNAL(error(int, int)),
655             this, SLOT(error(int, int)));
656
657     connect(m_ui, SIGNAL(fetchUsernameFromSettings()),
658             this, SLOT(fetchUsernameFromSettings()));
659
660     connect(m_ui, SIGNAL(loginActionPressed()),
661             this, SLOT(loginActionPressed()));
662
663     connect(m_ui, SIGNAL(saveUsername(QString)),
664             m_facebookAuthenticator, SLOT(saveUsername(QString)));
665
666     connect(m_ui, SIGNAL(updateCredentials(QUrl)),
667             m_facebookAuthenticator, SLOT(updateCredentials(QUrl)));
668
669     // signals from map view
670     connect(m_ui, SIGNAL(mapViewScrolled(SceneCoordinate)),
671             m_mapEngine, SLOT(setCenterPosition(SceneCoordinate)));
672
673     connect(m_ui, SIGNAL(mapViewResized(QSize)),
674             m_mapEngine, SLOT(viewResized(QSize)));
675
676     connect(m_ui, SIGNAL(viewZoomFinished()),
677             m_mapEngine, SLOT(viewZoomFinished()));
678
679     // signals from zoom buttons (zoom panel and volume buttons)
680     connect(m_ui, SIGNAL(zoomIn()),
681             m_mapEngine, SLOT(zoomIn()));
682
683     connect(m_ui, SIGNAL(zoomOut()),
684             m_mapEngine, SLOT(zoomOut()));
685
686     // signals from menu buttons
687     connect(m_ui, SIGNAL(gpsTriggered(bool)),
688             this, SLOT(setGPS(bool)));
689
690     //signals from dialogs
691     connect(m_ui, SIGNAL(cancelLoginProcess()),
692             this, SLOT(loginProcessCancelled()));
693
694     connect(m_ui, SIGNAL(requestReverseGeo()),
695             this, SLOT(requestAddress()));
696
697     connect(m_ui, SIGNAL(statusUpdate(QString,bool)),
698             this, SLOT(requestUpdateLocation(QString,bool)));
699
700     connect(m_ui, SIGNAL(enableAutomaticLocationUpdate(bool, int)),
701             this, SLOT(enableAutomaticLocationUpdate(bool, int)));
702
703     // signals from user info tab
704     connect(m_ui, SIGNAL(refreshUserData()),
705             this, SLOT(refreshUserData()));
706
707     connect(m_ui, SIGNAL(centerToCoordinates(GeoCoordinate)),
708             m_mapEngine, SLOT(centerToCoordinates(GeoCoordinate)));
709
710     // routing signal from friend list tab & search location tab
711     connect(m_ui, SIGNAL(routeTo(const GeoCoordinate&)),
712             this, SLOT(routeTo(const GeoCoordinate&)));
713
714     connect(m_ui, SIGNAL(requestContactDialog(const QString &)),
715             this, SLOT(showContactDialog(const QString &)));
716
717     // signals from location search panel
718     connect(m_ui,
719             SIGNAL(locationItemClicked(const GeoCoordinate&, const GeoCoordinate&)),
720             m_mapEngine,
721             SLOT(showMapArea(const GeoCoordinate&, const GeoCoordinate&)));
722
723     connect(m_ui, SIGNAL(searchHistoryItemClicked(QString)),
724             this, SLOT(locationSearch(QString)));
725
726     // signals from routing tab
727     connect(m_ui, SIGNAL(clearRoute()),
728             m_mapEngine, SLOT(clearRoute()));
729
730     connect(m_ui, SIGNAL(routeToCursor()),
731             this, SLOT(routeToCursor()));
732
733     // signals from distance indicator button
734     connect(m_ui, SIGNAL(autoCenteringTriggered(bool)),
735             this, SLOT(changeAutoCenteringSetting(bool)));
736
737     connect(m_ui, SIGNAL(draggingModeTriggered()),
738             this, SLOT(draggingModeTriggered()));
739
740     // signal from search location dialog
741     connect(m_ui, SIGNAL(searchForLocation(QString)),
742             this, SLOT(locationSearch(QString)));
743
744     // signals from meet people panel
745     connect(m_ui, SIGNAL(requestInterestingPeople()),
746             this, SLOT(requestInterestingPeople()));
747
748     // signals from notifications panel
749     connect(m_ui, SIGNAL(requestNotifications()),
750             m_situareService, SLOT(fetchNotifications()));
751 }
752
753 void SituareEngine::signalsFromMapEngine()
754 {
755     qDebug() << __PRETTY_FUNCTION__;
756
757     connect(m_mapEngine, SIGNAL(error(int, int)),
758             this, SLOT(error(int, int)));
759
760     connect(m_mapEngine, SIGNAL(locationChanged(SceneCoordinate)),
761             m_ui, SIGNAL(centerToSceneCoordinates(SceneCoordinate)));
762
763     connect(m_mapEngine, SIGNAL(zoomLevelChanged(int)),
764             m_ui, SIGNAL(zoomLevelChanged(int)));
765
766     connect(m_mapEngine, SIGNAL(mapScrolledManually()),
767             this, SLOT(disableAutoCentering()));
768
769     connect(m_mapEngine, SIGNAL(maxZoomLevelReached()),
770             m_ui, SIGNAL(maxZoomLevelReached()));
771
772     connect(m_mapEngine, SIGNAL(minZoomLevelReached()),
773             m_ui, SIGNAL(minZoomLevelReached()));
774
775     connect(m_mapEngine, SIGNAL(locationItemClicked(QList<QString>)),
776             m_ui, SIGNAL(locationItemClicked(QList<QString>)));
777
778     connect(m_mapEngine, SIGNAL(newMapResolution(qreal)),
779             m_ui, SIGNAL(newMapResolution(qreal)));
780
781     connect(m_mapEngine, SIGNAL(directionIndicatorValuesUpdate(qreal, qreal, bool)),
782             m_ui, SIGNAL(directionIndicatorValuesUpdate(qreal, qreal, bool)));
783 }
784
785 void SituareEngine::signalsFromRoutingService()
786 {
787     qDebug() << __PRETTY_FUNCTION__;
788
789     connect(m_routingService, SIGNAL(routeParsed(Route&)),
790             this, SLOT(routeParsed(Route&)));
791
792     connect(m_routingService, SIGNAL(routeParsed(Route&)),
793             m_mapEngine, SLOT(setRoute(Route&)));
794
795     connect(m_routingService, SIGNAL(routeParsed(Route&)),
796             m_ui, SIGNAL(routeParsed(Route&)));
797
798     connect(m_routingService, SIGNAL(error(int, int)),
799             this, SLOT(error(int, int)));
800 }
801
802 void SituareEngine::signalsFromSituareService()
803 {
804     qDebug() << __PRETTY_FUNCTION__;
805
806     connect(m_situareService, SIGNAL(error(int, int)),
807             this, SLOT(error(int, int)));
808
809     connect(m_situareService, SIGNAL(imageReady(QString,QPixmap)),
810             this, SLOT(imageReady(QString,QPixmap)));
811
812     connect(m_situareService, SIGNAL(reverseGeoReady(QString)),
813             m_ui, SIGNAL(reverseGeoReady(QString)));
814
815     connect(m_situareService, SIGNAL(userDataChanged(User*, QList<User*>&)),
816             this, SLOT(userDataChanged(User*, QList<User*>&)));
817
818     connect(m_situareService, SIGNAL(updateWasSuccessful()),
819             this, SLOT(updateWasSuccessful()));
820
821     connect(m_situareService, SIGNAL(updateWasSuccessful()),
822             m_ui, SIGNAL(clearUpdateLocationDialogData()));
823
824     connect(m_situareService, SIGNAL(interestingPeopleReceived(QList<User>&)),
825             m_ui, SIGNAL(interestingPeopleReceived(QList<User>&)));
826
827     connect(m_situareService, SIGNAL(notificationsReceived(QList<Notification>&)),
828             m_ui, SIGNAL(notificationsReceived(QList<Notification>&)));
829 }
830
831 void SituareEngine::startAutomaticUpdate()
832 {
833     qDebug() << __PRETTY_FUNCTION__;
834
835     m_gps->requestUpdate();
836     m_automaticUpdateRequest = true;
837 }
838
839 void SituareEngine::topmostWindowChanged(bool isMainWindow)
840 {
841     qDebug() << __PRETTY_FUNCTION__;
842
843     setPowerSaving(!isMainWindow);
844 }
845
846 void SituareEngine::updateWasSuccessful()
847 {
848     qDebug() << __PRETTY_FUNCTION__;
849
850     if (m_networkAccessManager->isConnected())
851         m_situareService->fetchLocations();
852     else
853         error(ErrorContext::NETWORK, QNetworkReply::UnknownNetworkError);
854 }
855
856 void SituareEngine::userDataChanged(User *user, QList<User *> &friendsList)
857 {
858     qDebug() << __PRETTY_FUNCTION__;
859
860     m_ui->toggleProgressIndicator(false);
861
862     emit userLocationReady(user);
863     emit friendsLocationsReady(friendsList);
864 }