Cleaning out old login code 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::imageReady(User *user)
312 {
313     qDebug() << __PRETTY_FUNCTION__;
314
315     if(user->type())
316         emit userLocationReady(user);
317     else
318         emit friendImageReady(user);
319 }
320
321 void SituareEngine::initializeGpsAndAutocentering()
322 {
323     qDebug() << __PRETTY_FUNCTION__;
324
325     QSettings settings(DIRECTORY_NAME, FILE_NAME);
326     QVariant gpsEnabled = settings.value(SETTINGS_GPS_ENABLED);
327     QVariant autoCenteringEnabled = settings.value(SETTINGS_AUTO_CENTERING_ENABLED);
328
329     if (m_gps->isInitialized()) {
330
331         if (gpsEnabled.toString().isEmpty()) { // First start. Situare.conf file does not exists
332
333             connect(m_gps, SIGNAL(position(GeoCoordinate, qreal)),
334                     this, SLOT(setFirstStartZoomLevel()));
335
336             changeAutoCenteringSetting(true);
337             setGPS(true);
338
339             m_ui->buildInformationBox(tr("GPS enabled"));
340
341         } else { // Normal start
342             changeAutoCenteringSetting(autoCenteringEnabled.toBool());
343             setGPS(gpsEnabled.toBool());
344
345             if (gpsEnabled.toBool())
346                 m_ui->buildInformationBox(tr("GPS enabled"));
347         }
348     } else {
349         setGPS(false);
350     }
351 }
352
353 void SituareEngine::locationSearch(QString location)
354 {
355     qDebug() << __PRETTY_FUNCTION__;
356
357     if(!location.isEmpty())
358         m_geocodingService->requestLocation(location);
359 }
360
361 void SituareEngine::login()
362 {
363     qWarning() << __PRETTY_FUNCTION__;
364
365     FacebookLoginBrowser *browser = m_ui->buildFacebookLoginBrowser();
366
367     connect(browser, SIGNAL(loadFinished(bool)),
368             m_facebookAuthenticator, SLOT(loadFinished(bool)));
369
370     connect(browser, SIGNAL(urlChanged(QUrl)),
371             m_facebookAuthenticator, SLOT(urlChanged(QUrl)));
372
373 //    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"));
374
375     QString url = "https://www.facebook.com/login.php?";
376     url.append("api_key=cf77865a5070f2c2ba3b52cbf3371579&"); ///< @todo hard coded test server api key
377     url.append("cancel_url=http://www.facebook.com/connect/login_failure.html&");
378     url.append("display=touch&");
379     url.append("fbconnect=1&");
380     url.append("next=http://www.facebook.com/connect/login_success.html&");
381     url.append("return_session=1&");
382     url.append("session_version=3&");
383     url.append("v=1.0&");
384     url.append("req_perms=publish_stream");
385
386     browser->load(QUrl(url));
387 }
388
389 void SituareEngine::loggedIn()
390 {
391     qWarning() << __PRETTY_FUNCTION__;
392
393     m_ui->destroyFacebookLoginBrowser();
394
395     loginOk();
396 }
397
398 void SituareEngine::loginActionPressed()
399 {
400     qDebug() << __PRETTY_FUNCTION__;
401
402     if (m_networkAccessManager->isConnected()) {
403         if(m_ui->loginState()) {
404             logout();
405             m_situareService->clearUserData();
406         } else {
407             login();
408         }
409     }
410     else {
411         error(ErrorContext::NETWORK, QNetworkReply::UnknownNetworkError);
412     }
413 }
414
415 void SituareEngine::loginOk()
416 {
417     qDebug() << __PRETTY_FUNCTION__;
418
419     m_ui->loggedIn(true);
420
421     m_ui->show();
422     m_situareService->fetchLocations(); // request user locations
423
424     if (m_gps->isRunning())
425         m_ui->readAutomaticLocationUpdateSettings();
426 }
427
428 void SituareEngine::loginProcessCancelled()
429 {
430     qDebug() << __PRETTY_FUNCTION__;
431
432     m_ui->toggleProgressIndicator(false);
433     m_ui->updateItemVisibility();
434 }
435
436 void SituareEngine::logout()
437 {
438     qDebug() << __PRETTY_FUNCTION__;
439
440     m_ui->loggedIn(false);
441
442     // signal to clear locationUpdateDialog's data
443     connect(this, SIGNAL(clearUpdateLocationDialogData()),
444             m_ui, SIGNAL(clearUpdateLocationDialogData()));
445     emit clearUpdateLocationDialogData();
446
447     m_facebookAuthenticator->clearAccountInformation(); // clear all
448     m_automaticUpdateFirstStart = true;
449 }
450
451 void SituareEngine::refreshUserData()
452 {
453     qDebug() << __PRETTY_FUNCTION__;
454
455     if (m_networkAccessManager->isConnected()) {
456         m_ui->toggleProgressIndicator(true);
457         m_situareService->fetchLocations();
458     }
459     else {
460         error(ErrorContext::NETWORK, QNetworkReply::UnknownNetworkError);
461     }
462 }
463
464 void SituareEngine::requestAddress()
465 {
466     qDebug() << __PRETTY_FUNCTION__;
467
468     if (m_networkAccessManager->isConnected()) {
469         if (m_gps->isRunning())
470             m_situareService->reverseGeo(m_gps->lastPosition());
471         else
472             m_situareService->reverseGeo(m_mapEngine->centerGeoCoordinate());
473     }
474     else {
475         error(ErrorContext::NETWORK, QNetworkReply::UnknownNetworkError);
476     }
477 }
478
479 void SituareEngine::requestUpdateLocation(const QString &status, bool publish)
480 {
481     qDebug() << __PRETTY_FUNCTION__;
482
483     if (m_networkAccessManager->isConnected()) {
484         m_ui->toggleProgressIndicator(true);
485
486         if (m_gps->isRunning())
487             m_situareService->updateLocation(m_gps->lastPosition(), status, publish);
488         else
489             m_situareService->updateLocation(m_mapEngine->centerGeoCoordinate(), status, publish);
490     }
491     else {
492         error(ErrorContext::NETWORK, QNetworkReply::UnknownNetworkError);
493     }
494 }
495
496 void SituareEngine::requestAutomaticUpdateIfMoved(GeoCoordinate position)
497 {
498     qDebug() << __PRETTY_FUNCTION__;
499
500     if ((fabs(m_lastUpdatedGPSPosition.longitude() - position.longitude()) >
501          USER_MOVEMENT_MINIMUM_LONGITUDE_DIFFERENCE) ||
502         (fabs(m_lastUpdatedGPSPosition.latitude() - position.latitude()) >
503          USER_MOVEMENT_MINIMUM_LATITUDE_DIFFERENCE)) {
504
505         m_lastUpdatedGPSPosition = position;
506         m_userMoved = true;
507     }
508
509     if (m_automaticUpdateRequest && m_userMoved) {
510         requestUpdateLocation(tr("Automatic location update"));
511         m_automaticUpdateRequest = false;
512         m_userMoved = false;
513     }
514 }
515
516 void SituareEngine::routeParsed(Route &route)
517 {
518     qDebug() << __PRETTY_FUNCTION__;
519
520     Q_UNUSED(route);
521
522     m_ui->toggleProgressIndicator(false);
523 }
524
525 void SituareEngine::routeTo(const GeoCoordinate &endPointCoordinates)
526 {
527     qDebug() << __PRETTY_FUNCTION__;
528
529     m_ui->toggleProgressIndicator(true);
530
531     if (m_gps->isRunning())
532         m_routingService->requestRoute(m_gps->lastPosition(), endPointCoordinates);
533     else
534         m_routingService->requestRoute(m_mapEngine->centerGeoCoordinate(), endPointCoordinates);
535 }
536
537 void SituareEngine::routeToCursor()
538 {
539     qDebug() << __PRETTY_FUNCTION__;
540
541     routeTo(m_mapEngine->centerGeoCoordinate());
542 }
543
544 void SituareEngine::setAutoCentering(bool enabled)
545 {
546     qDebug() << __PRETTY_FUNCTION__ << enabled;
547
548     m_ui->setIndicatorButtonEnabled(enabled);
549     m_mapEngine->setAutoCentering(enabled);
550     m_ui->setCrosshairVisibility(!enabled);
551
552     if (enabled) {
553         setGPS(true);
554         m_gps->requestLastPosition();
555     }
556 }
557
558 void SituareEngine::setFirstStartZoomLevel()
559 {
560     qDebug() << __PRETTY_FUNCTION__;
561
562     if (m_autoCenteringEnabled) // autocentering is disabled when map is scrolled
563         m_mapEngine->setZoomLevel(DEFAULT_ZOOM_LEVEL_WHEN_GPS_IS_AVAILABLE);
564
565     disconnect(m_gps, SIGNAL(position(GeoCoordinate, qreal)),
566                this, SLOT(setFirstStartZoomLevel()));
567 }
568
569 void SituareEngine::setGPS(bool enabled)
570 {
571     qDebug() << __PRETTY_FUNCTION__ << enabled;
572
573     if (m_gps->isInitialized()) {
574         m_ui->setGPSButtonEnabled(enabled);
575         m_mapEngine->setGPSEnabled(enabled);
576
577         if (enabled && !m_gps->isRunning()) {
578             m_gps->start();
579             m_gps->requestLastPosition();
580
581             if(m_ui->loginState())
582                 m_ui->readAutomaticLocationUpdateSettings();
583         }
584         else if (!enabled && m_gps->isRunning()) {
585             m_gps->stop();
586             changeAutoCenteringSetting(false);
587             enableAutomaticLocationUpdate(false);
588         }
589     }
590     else {
591         if (enabled)
592             m_ui->buildInformationBox(tr("Unable to start GPS"));
593         m_ui->setGPSButtonEnabled(false);
594         m_mapEngine->setGPSEnabled(false);
595     }
596 }
597
598 void SituareEngine::setPowerSaving(bool enabled)
599 {
600     qDebug() << __PRETTY_FUNCTION__ << enabled;
601
602     m_gps->enablePowerSave(enabled);
603
604     if(m_autoCenteringEnabled)
605         m_mapEngine->setAutoCentering(!enabled);
606 }
607
608 void SituareEngine::showContactDialog(const QString &facebookId)
609 {
610     qDebug() << __PRETTY_FUNCTION__;
611
612     QString guid = m_contactManager->contactGuid(facebookId);
613
614     if (!guid.isEmpty())
615         m_ui->showContactDialog(guid);
616     else
617         m_ui->buildInformationBox(tr("Unable to find contact.\nAdd Facebook IM "
618                                      "account from Conversations to use this feature."), true);
619 }
620
621 void SituareEngine::signalsFromFacebookAuthenticator()
622 {
623     qDebug() << __PRETTY_FUNCTION__;
624
625     connect(m_facebookAuthenticator, SIGNAL(error(int, int)),
626             this, SLOT(error(int, int)));
627
628     connect(m_facebookAuthenticator, SIGNAL(credentialsReady(FacebookCredentials)),
629             m_situareService, SLOT(credentialsReady(FacebookCredentials)));
630
631     connect(m_facebookAuthenticator, SIGNAL(credentialsReady(FacebookCredentials)),
632             this, SLOT(loginOk()));
633
634     connect(m_facebookAuthenticator, SIGNAL(newLoginRequest()),
635             m_ui, SLOT(startLoginProcess()));
636
637     connect(m_facebookAuthenticator, SIGNAL(saveCookiesRequest()),
638             m_ui, SLOT(saveCookies()));
639
640     connect(m_facebookAuthenticator, SIGNAL(loginUsingCookies()),
641             m_ui, SLOT(loginUsingCookies()));
642
643     connect(m_facebookAuthenticator, SIGNAL(loggedIn(QString)),
644             m_situareService, SLOT(updateAccessToken(QString)));
645
646     connect(m_facebookAuthenticator, SIGNAL(loggedIn(QString)),
647             this, SLOT(loggedIn()));
648 }
649
650 void SituareEngine::signalsFromGeocodingService()
651 {
652     qDebug() << __PRETTY_FUNCTION__;
653
654     connect(m_geocodingService, SIGNAL(locationDataParsed(const QList<Location>&)),
655             m_ui, SIGNAL(locationDataParsed(const QList<Location>&)));
656
657     connect(m_geocodingService, SIGNAL(error(int, int)),
658             this, SLOT(error(int, int)));
659 }
660
661 void SituareEngine::signalsFromGPS()
662 {
663     qDebug() << __PRETTY_FUNCTION__;
664
665     connect(m_gps, SIGNAL(position(GeoCoordinate, qreal)),
666             m_mapEngine, SLOT(gpsPositionUpdate(GeoCoordinate, qreal)));
667
668     connect(m_gps, SIGNAL(timeout()),
669             m_ui, SLOT(gpsTimeout()));
670
671     connect(m_gps, SIGNAL(error(int, int)),
672             this, SLOT(error(int, int)));
673 }
674
675 void SituareEngine::signalsFromMainWindow()
676 {
677     qDebug() << __PRETTY_FUNCTION__;
678
679     connect(m_ui, SIGNAL(error(int, int)),
680             this, SLOT(error(int, int)));
681
682     connect(m_ui, SIGNAL(fetchUsernameFromSettings()),
683             this, SLOT(fetchUsernameFromSettings()));
684
685     connect(m_ui, SIGNAL(loginActionPressed()),
686             this, SLOT(loginActionPressed()));
687
688     connect(m_ui, SIGNAL(saveUsername(QString)),
689             m_facebookAuthenticator, SLOT(saveUsername(QString)));
690
691     connect(m_ui, SIGNAL(updateCredentials(QUrl)),
692             m_facebookAuthenticator, SLOT(updateCredentials(QUrl)));
693
694     // signals from map view
695     connect(m_ui, SIGNAL(mapViewScrolled(SceneCoordinate)),
696             m_mapEngine, SLOT(setCenterPosition(SceneCoordinate)));
697
698     connect(m_ui, SIGNAL(mapViewResized(QSize)),
699             m_mapEngine, SLOT(viewResized(QSize)));
700
701     connect(m_ui, SIGNAL(viewZoomFinished()),
702             m_mapEngine, SLOT(viewZoomFinished()));
703
704     // signals from zoom buttons (zoom panel and volume buttons)
705     connect(m_ui, SIGNAL(zoomIn()),
706             m_mapEngine, SLOT(zoomIn()));
707
708     connect(m_ui, SIGNAL(zoomOut()),
709             m_mapEngine, SLOT(zoomOut()));
710
711     // signals from menu buttons
712     connect(m_ui, SIGNAL(gpsTriggered(bool)),
713             this, SLOT(setGPS(bool)));
714
715     //signals from dialogs
716     connect(m_ui, SIGNAL(cancelLoginProcess()),
717             this, SLOT(loginProcessCancelled()));
718
719     connect(m_ui, SIGNAL(requestReverseGeo()),
720             this, SLOT(requestAddress()));
721
722     connect(m_ui, SIGNAL(statusUpdate(QString,bool)),
723             this, SLOT(requestUpdateLocation(QString,bool)));
724
725     connect(m_ui, SIGNAL(enableAutomaticLocationUpdate(bool, int)),
726             this, SLOT(enableAutomaticLocationUpdate(bool, int)));
727
728     // signals from user info tab
729     connect(m_ui, SIGNAL(refreshUserData()),
730             this, SLOT(refreshUserData()));
731
732     connect(m_ui, SIGNAL(centerToCoordinates(GeoCoordinate)),
733             m_mapEngine, SLOT(centerToCoordinates(GeoCoordinate)));
734
735     // routing signal from friend list tab & search location tab
736     connect(m_ui, SIGNAL(routeTo(const GeoCoordinate&)),
737             this, SLOT(routeTo(const GeoCoordinate&)));
738
739     // signals from location search panel
740     connect(m_ui,
741             SIGNAL(locationItemClicked(const GeoCoordinate&, const GeoCoordinate&)),
742             m_mapEngine,
743             SLOT(showMapArea(const GeoCoordinate&, const GeoCoordinate&)));
744
745     connect(m_ui, SIGNAL(searchHistoryItemClicked(QString)),
746             this, SLOT(locationSearch(QString)));
747
748     // signals from routing tab
749     connect(m_ui, SIGNAL(clearRoute()),
750             m_mapEngine, SLOT(clearRoute()));
751
752     connect(m_ui, SIGNAL(routeToCursor()),
753             this, SLOT(routeToCursor()));
754
755     // signals from distance indicator button
756     connect(m_ui, SIGNAL(autoCenteringTriggered(bool)),
757             this, SLOT(changeAutoCenteringSetting(bool)));
758
759     connect(m_ui, SIGNAL(draggingModeTriggered()),
760             this, SLOT(draggingModeTriggered()));
761
762     // signal from search location dialog
763     connect(m_ui, SIGNAL(searchForLocation(QString)),
764             this, SLOT(locationSearch(QString)));
765
766     // signal from friend list panel
767     connect(m_ui, SIGNAL(requestContactDialog(const QString &)),
768             this, SLOT(showContactDialog(const QString &)));
769 }
770
771 void SituareEngine::signalsFromMapEngine()
772 {
773     qDebug() << __PRETTY_FUNCTION__;
774
775     connect(m_mapEngine, SIGNAL(error(int, int)),
776             this, SLOT(error(int, int)));
777
778     connect(m_mapEngine, SIGNAL(locationChanged(SceneCoordinate)),
779             m_ui, SIGNAL(centerToSceneCoordinates(SceneCoordinate)));
780
781     connect(m_mapEngine, SIGNAL(zoomLevelChanged(int)),
782             m_ui, SIGNAL(zoomLevelChanged(int)));
783
784     connect(m_mapEngine, SIGNAL(mapScrolledManually()),
785             this, SLOT(disableAutoCentering()));
786
787     connect(m_mapEngine, SIGNAL(maxZoomLevelReached()),
788             m_ui, SIGNAL(maxZoomLevelReached()));
789
790     connect(m_mapEngine, SIGNAL(minZoomLevelReached()),
791             m_ui, SIGNAL(minZoomLevelReached()));
792
793     connect(m_mapEngine, SIGNAL(locationItemClicked(QList<QString>)),
794             m_ui, SIGNAL(locationItemClicked(QList<QString>)));
795
796     connect(m_mapEngine, SIGNAL(newMapResolution(qreal)),
797             m_ui, SIGNAL(newMapResolution(qreal)));
798
799     connect(m_mapEngine, SIGNAL(directionIndicatorValuesUpdate(qreal, qreal, bool)),
800             m_ui, SIGNAL(directionIndicatorValuesUpdate(qreal, qreal, bool)));
801 }
802
803 void SituareEngine::signalsFromRoutingService()
804 {
805     qDebug() << __PRETTY_FUNCTION__;
806
807     connect(m_routingService, SIGNAL(routeParsed(Route&)),
808             this, SLOT(routeParsed(Route&)));
809
810     connect(m_routingService, SIGNAL(routeParsed(Route&)),
811             m_mapEngine, SLOT(setRoute(Route&)));
812
813     connect(m_routingService, SIGNAL(routeParsed(Route&)),
814             m_ui, SIGNAL(routeParsed(Route&)));
815
816     connect(m_routingService, SIGNAL(error(int, int)),
817             this, SLOT(error(int, int)));
818 }
819
820 void SituareEngine::signalsFromSituareService()
821 {
822     qDebug() << __PRETTY_FUNCTION__;
823
824     connect(m_situareService, SIGNAL(error(int, int)),
825             this, SLOT(error(int, int)));
826
827     connect(m_situareService, SIGNAL(imageReady(User*)),
828             this, SLOT(imageReady(User*)));
829
830     connect(m_situareService, SIGNAL(reverseGeoReady(QString)),
831             m_ui, SIGNAL(reverseGeoReady(QString)));
832
833     connect(m_situareService, SIGNAL(userDataChanged(User*, QList<User*>&)),
834             this, SLOT(userDataChanged(User*, QList<User*>&)));
835
836     connect(m_situareService, SIGNAL(updateWasSuccessful()),
837             this, SLOT(updateWasSuccessful()));
838
839     connect(m_situareService, SIGNAL(updateWasSuccessful()),
840             m_ui, SIGNAL(clearUpdateLocationDialogData()));
841 }
842
843 void SituareEngine::startAutomaticUpdate()
844 {
845     qDebug() << __PRETTY_FUNCTION__;
846
847     m_gps->requestUpdate();
848     m_automaticUpdateRequest = true;
849 }
850
851 void SituareEngine::topmostWindowChanged(bool isMainWindow)
852 {
853     qDebug() << __PRETTY_FUNCTION__;
854
855     setPowerSaving(!isMainWindow);
856 }
857
858 void SituareEngine::updateWasSuccessful()
859 {
860     qDebug() << __PRETTY_FUNCTION__;
861
862     if (m_networkAccessManager->isConnected())
863         m_situareService->fetchLocations();
864     else
865         error(ErrorContext::NETWORK, QNetworkReply::UnknownNetworkError);
866 }
867
868 void SituareEngine::userDataChanged(User *user, QList<User *> &friendsList)
869 {
870     qDebug() << __PRETTY_FUNCTION__;
871
872     m_ui->toggleProgressIndicator(false);
873
874     emit userLocationReady(user);
875     emit friendsLocationsReady(friendsList);
876 }