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