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