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