Added LocationSearchPanel (which is currently a copy of RoutingPanel)
[situare] / src / ui / mainwindow.cpp
1 /*
2    Situare - A location system for Facebook
3    Copyright (C) 2010  Ixonos Plc. Authors:
4
5       Henri Lampela - henri.lampela@ixonos.com
6       Kaj Wallin - kaj.wallin@ixonos.com
7       Jussi Laitinen - jussi.laitinen@ixonos.com
8       Sami Rämö - sami.ramo@ixonos.com
9       Ville Tiensuu - ville.tiensuu@ixonos.com
10       Katri Kaikkonen - katri.kaikkonen@ixonos.com
11
12    Situare is free software; you can redistribute it and/or
13    modify it under the terms of the GNU General Public License
14    version 2 as published by the Free Software Foundation.
15
16    Situare is distributed in the hope that it will be useful,
17    but WITHOUT ANY WARRANTY; without even the implied warranty of
18    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
19    GNU General Public License for more details.
20
21    You should have received a copy of the GNU General Public License
22    along with Situare; if not, write to the Free Software
23    Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301,
24    USA.
25 */
26
27 #include <QAction>
28 #include <QApplication>
29 #include <QMenuBar>
30 #include <QMessageBox>
31 #include <QtAlgorithms>
32 #include <QtWebKit>
33
34 ///< @todo sort
35 #include "facebookservice/facebookauthentication.h"
36 #include "map/mapcommon.h"
37 #include "map/mapview.h"
38 #include "common.h"
39 #include "error.h"
40 #include "friendlistpanel.h"
41 #include "fullscreenbutton.h"
42 #include "indicatorbuttonpanel.h"
43 #include "locationsearchpanel.h"
44 #include "logindialog.h"
45 #include "mapscale.h"
46 #include "panelcommon.h"
47 #include "routingpanel.h"
48 #include "tabbedpanel.h"
49 #include "searchdialog.h"
50 #include "settingsdialog.h"
51 #include "userinfopanel.h"
52 #include "zoombuttonpanel.h"
53
54 #include "mainwindow.h"
55
56 // These MUST BE HERE, compiling for Maemo fails if moved
57 #ifdef Q_WS_MAEMO_5
58 #include <QtMaemo5/QMaemo5InformationBox>
59 #include <QtGui/QX11Info>
60 #include <X11/Xatom.h>
61 #include <X11/Xlib.h>
62 #endif // Q_WS_MAEMO_5
63
64 MainWindow::MainWindow(QWidget *parent)
65     : QMainWindow(parent),
66       m_errorShown(false),
67       m_loggedIn(false),
68       m_refresh(false),
69       m_mapCenterHorizontalShifting(0),
70       m_progressIndicatorCount(0),
71       m_crosshair(0),
72       m_email(), ///< @todo WTF?!?!?!?
73       m_password(),
74       m_webView(0),
75       m_fullScreenButton(0),
76       m_indicatorButtonPanel(0),
77       m_mapScale(0),
78       m_cookieJar(0)
79 {
80     qDebug() << __PRETTY_FUNCTION__;
81
82     buildMap();
83
84     // map view is the only widget which size & location is handled automatically by the system
85     // default functionality
86     setCentralWidget(m_mapView);
87
88     buildPanels();
89
90     createMenus();
91     setWindowTitle(tr("Situare"));
92
93     // set stacking order of widgets (from top to bottom)
94     // m_tabbedPanel is the topmost one
95     if (m_fullScreenButton) {
96         m_fullScreenButton->stackUnder(m_tabbedPanel);
97         m_crosshair->stackUnder(m_fullScreenButton);
98     } else {
99         m_crosshair->stackUnder(m_tabbedPanel);
100     }
101     m_zoomButtonPanel->stackUnder(m_crosshair);
102     m_indicatorButtonPanel->stackUnder(m_zoomButtonPanel);
103     m_osmLicense->stackUnder(m_indicatorButtonPanel);
104     m_mapScale->stackUnder(m_osmLicense);
105     m_mapView->stackUnder(m_mapScale);
106
107     grabZoomKeys(true);
108
109     // Set default screen size
110     resize(DEFAULT_SCREEN_WIDTH, DEFAULT_SCREEN_HEIGHT);
111 #ifdef Q_WS_MAEMO_5
112     setAttribute(Qt::WA_Maemo5StackedWindow);
113 #endif
114 }
115
116 MainWindow::~MainWindow()
117 {
118     qDebug() << __PRETTY_FUNCTION__;
119
120     grabZoomKeys(false);
121
122     if(m_webView)
123         delete m_webView;
124
125     qDeleteAll(m_queue.begin(), m_queue.end());
126     m_queue.clear();
127
128     qDeleteAll(m_error_queue.begin(), m_error_queue.end());
129     m_error_queue.clear();
130 }
131
132 void MainWindow::automaticUpdateDialogFinished(int result)
133 {
134     qDebug() << __PRETTY_FUNCTION__;
135
136     if (result == QMessageBox::Yes) {
137         readAutomaticLocationUpdateSettings();
138     } else {
139         QSettings settings(DIRECTORY_NAME, FILE_NAME);
140         settings.setValue(SETTINGS_AUTOMATIC_UPDATE_ENABLED, false);
141         readAutomaticLocationUpdateSettings();
142     }
143
144     m_automaticUpdateLocationDialog->deleteLater();
145 }
146
147 void MainWindow::buildCrosshair()
148 {
149     qDebug() << __PRETTY_FUNCTION__;
150
151     m_crosshair = new QLabel(this);
152     QPixmap crosshairImage(":/res/images/sight.png");
153     m_crosshair->setPixmap(crosshairImage);
154     m_crosshair->setFixedSize(crosshairImage.size());
155     m_crosshair->hide();
156     m_crosshair->setAttribute(Qt::WA_TransparentForMouseEvents, true);
157
158     connect(m_mapView, SIGNAL(viewResized(QSize)),
159             this, SLOT(moveCrosshair()));
160
161     connect(m_mapView, SIGNAL(horizontalShiftingChanged(int)),
162             this, SLOT(mapCenterHorizontalShiftingChanged(int)));
163 }
164
165 void MainWindow::buildFriendListPanel()
166 {
167     qDebug() << __PRETTY_FUNCTION__;
168
169     m_friendsListPanel = new FriendListPanel(this);
170
171     connect(this, SIGNAL(friendsLocationsReady(QList<User*>&)),
172             m_friendsListPanel, SLOT(friendInfoReceived(QList<User*>&)));
173
174     connect(this, SIGNAL(locationItemClicked(QList<QString>)),
175             m_friendsListPanel, SLOT(showFriendsInList(QList<QString>)));
176
177     connect(m_friendsListPanel, SIGNAL(findFriend(GeoCoordinate)),
178             this, SIGNAL(centerToCoordinates(GeoCoordinate)));
179
180     connect(this, SIGNAL(friendImageReady(User*)),
181             m_friendsListPanel, SLOT(friendImageReady(User*)));
182
183     connect(m_friendsListPanel, SIGNAL(routeToFriend(const GeoCoordinate&)),
184             this, SIGNAL(routeTo(const GeoCoordinate&)));
185 }
186
187 void MainWindow::buildFullScreenButton()
188 {
189     qDebug() << __PRETTY_FUNCTION__;
190
191 #ifdef Q_WS_MAEMO_5
192     m_fullScreenButton = new FullScreenButton(this);
193
194     if (m_fullScreenButton) {
195         connect(m_fullScreenButton, SIGNAL(clicked()),
196                 this, SLOT(toggleFullScreen()));
197
198         connect(qApp, SIGNAL(showFullScreenButton()),
199                 m_fullScreenButton, SLOT(invoke()));
200     }
201 #endif // Q_WS_MAEMO_5
202 }
203
204 void MainWindow::buildIndicatorButtonPanel()
205 {
206     qDebug() << __PRETTY_FUNCTION__;
207
208     m_indicatorButtonPanel = new IndicatorButtonPanel(this);
209
210     connect(m_indicatorButtonPanel, SIGNAL(autoCenteringTriggered(bool)),
211         this, SIGNAL(autoCenteringTriggered(bool)));
212
213     connect(m_mapView, SIGNAL(viewResized(QSize)),
214             m_indicatorButtonPanel, SLOT(screenResized(QSize)));
215
216     connect(this, SIGNAL(directionIndicatorValuesUpdate(qreal, qreal, bool)),
217             m_indicatorButtonPanel, SIGNAL(directionIndicatorValuesUpdate(qreal, qreal, bool)));
218
219     connect(m_indicatorButtonPanel, SIGNAL(draggingModeTriggered()),
220             this, SIGNAL(draggingModeTriggered()));
221 }
222
223 void MainWindow::buildInformationBox(const QString &message, bool modal)
224 {
225     qDebug() << __PRETTY_FUNCTION__;
226
227     QString errorMessage = message;
228
229 #ifdef Q_WS_MAEMO_5
230
231     QMaemo5InformationBox *msgBox = new QMaemo5InformationBox(this);
232
233     if(modal) {
234         msgBox->setTimeout(QMaemo5InformationBox::NoTimeout);
235         // extra line changes are needed to make error notes broader
236         errorMessage.prepend("\n");
237         errorMessage.append("\n");
238     } else {
239         msgBox->setTimeout(QMaemo5InformationBox::DefaultTimeout);
240     }
241     QLabel *label = new QLabel(msgBox);
242     label->setAlignment(Qt::AlignCenter);
243     label->setText(errorMessage);
244     msgBox->setWidget(label);
245 #else
246     QMessageBox *msgBox = new QMessageBox(this);
247     msgBox->button(QMessageBox::Ok);
248     msgBox->setText(errorMessage);
249     msgBox->setModal(modal);
250 #endif
251
252     queueDialog(msgBox);
253 }
254
255 void MainWindow::buildLocationSearchPanel()
256 {
257     qDebug() << __PRETTY_FUNCTION__;
258
259     m_locationSearchPanel = new LocationSearchPanel(this);
260
261     connect(this, SIGNAL(locationDataParsed(const QList<Location>&)),
262             m_locationSearchPanel, SLOT(populateLocationListView(const QList<Location>&)));
263
264     connect(m_locationSearchPanel, SIGNAL(locationItemClicked(const GeoCoordinate&, const GeoCoordinate&)),
265             this, SIGNAL(locationItemClicked(const GeoCoordinate&, const GeoCoordinate&)));
266
267     connect(m_locationSearchPanel, SIGNAL(routeToLocation(const GeoCoordinate&)),
268             this, SIGNAL(routeTo(const GeoCoordinate&)));
269
270     connect(this, SIGNAL(routeParsed(Route&)),
271             m_locationSearchPanel, SLOT(setRoute(Route&)));
272
273     connect(m_locationSearchPanel, SIGNAL(routeWaypointItemClicked(GeoCoordinate)),
274             this, SIGNAL(centerToCoordinates(GeoCoordinate)));
275
276     connect(m_locationSearchPanel, SIGNAL(requestSearchLocation()),
277             this, SLOT(startLocationSearch()));
278
279     connect(m_locationSearchPanel, SIGNAL(clearRoute()),
280             this, SIGNAL(clearRoute()));
281 }
282
283 void MainWindow::buildMap()
284 {
285     qDebug() << __PRETTY_FUNCTION__;
286
287     m_mapView = new MapView(this);
288
289     buildZoomButtonPanel();
290     buildOsmLicense();
291     buildCrosshair();
292     buildFullScreenButton();
293     buildIndicatorButtonPanel();
294     buildMapScale();
295
296     connect(m_mapView, SIGNAL(viewScrolled(SceneCoordinate)),
297             this, SIGNAL(mapViewScrolled(SceneCoordinate)));
298
299     connect(this, SIGNAL(centerToSceneCoordinates(SceneCoordinate)),
300             m_mapView, SLOT(centerToSceneCoordinates(SceneCoordinate)));
301
302     connect(m_mapView, SIGNAL(viewResized(QSize)),
303             this, SIGNAL(mapViewResized(QSize)));
304
305     connect(m_mapView, SIGNAL(viewResized(QSize)),
306             this, SLOT(drawFullScreenButton(QSize)));
307
308     connect(m_mapView, SIGNAL(viewResized(QSize)),
309             this, SLOT(drawMapScale(QSize)));
310
311     connect(m_mapView, SIGNAL(viewResized(QSize)),
312              this, SLOT(moveCrosshair()));
313
314     connect(this, SIGNAL(zoomLevelChanged(int)),
315             m_mapView, SLOT(setZoomLevel(int)));
316
317     connect(m_mapView, SIGNAL(viewZoomFinished()),
318             this, SIGNAL(viewZoomFinished()));
319
320     connect(m_mapView, SIGNAL(zoomIn()),
321             this, SIGNAL(zoomIn()));
322 }
323
324 void MainWindow::buildMapScale()
325 {
326     m_mapScale = new MapScale(this);
327     connect(this, SIGNAL(newMapResolution(qreal)),
328             m_mapScale, SLOT(updateMapResolution(qreal)));
329 }
330
331 void MainWindow::buildOsmLicense()
332 {
333     qDebug() << __PRETTY_FUNCTION__;
334
335     m_osmLicense = new QLabel(this);
336     m_osmLicense->setAttribute(Qt::WA_TranslucentBackground, true);
337     m_osmLicense->setAttribute(Qt::WA_TransparentForMouseEvents, true);
338     m_osmLicense->setText("<font color='black'>" + OSM_LICENSE + "</font>");
339     m_osmLicense->setFont(QFont("Nokia Sans", 9));
340     m_osmLicense->resize(m_osmLicense->fontMetrics().width(OSM_LICENSE),
341                          m_osmLicense->fontMetrics().height());
342
343     connect(m_mapView, SIGNAL(viewResized(QSize)),
344             this, SLOT(drawOsmLicense(QSize)));
345 }
346
347 void MainWindow::buildPanels()
348 {
349     qDebug() << __PRETTY_FUNCTION__;
350
351     buildUserInfoPanel();
352     buildFriendListPanel();
353     buildLocationSearchPanel();
354     buildRoutingPanel();
355
356     m_tabbedPanel = new TabbedPanel(this);
357     m_tabbedPanel->addTab(m_userInfoPanel, QIcon(":/res/images/user_info.png"));
358     m_tabbedPanel->addTab(m_friendsListPanel, QIcon(":/res/images/friend_list.png"));
359     m_tabbedPanel->addTab(m_locationSearchPanel, QIcon(":/res/images/search.png"));
360     m_tabbedPanel->addTab(m_routingPanel, QIcon(":/res/images/routing.png"));
361
362     connect(m_mapView, SIGNAL(viewResized(QSize)),
363             m_tabbedPanel, SLOT(resizePanel(QSize)));
364
365     connect(m_friendsListPanel, SIGNAL(openPanelRequested(QWidget*)),
366             m_tabbedPanel, SLOT(openPanel(QWidget*)));
367
368     connect(m_routingPanel, SIGNAL(openPanelRequested(QWidget*)),
369             m_tabbedPanel, SLOT(openPanel(QWidget*)));
370
371     connect(m_tabbedPanel, SIGNAL(panelClosed()),
372             m_friendsListPanel, SLOT(anyPanelClosed()));
373
374     connect(m_tabbedPanel, SIGNAL(panelOpened()),
375             m_friendsListPanel, SLOT(anyPanelOpened()));
376
377     connect(m_tabbedPanel, SIGNAL(panelClosed()),
378             m_routingPanel, SLOT(clearListsSelections()));
379
380     connect(m_tabbedPanel, SIGNAL(panelClosed()),
381             m_mapView, SLOT(disableCenterShift()));
382
383     connect(m_tabbedPanel, SIGNAL(panelOpened()),
384             m_mapView, SLOT(enableCenterShift()));
385
386     connect(m_tabbedPanel, SIGNAL(panelClosed()),
387             m_userInfoPanel, SIGNAL(collapse()));
388
389     connect(m_tabbedPanel, SIGNAL(currentChanged(int)),
390             m_userInfoPanel, SIGNAL(collapse()));
391 }
392
393 void MainWindow::buildRoutingPanel()
394 {
395     qDebug() << __PRETTY_FUNCTION__;
396
397     m_routingPanel = new RoutingPanel(this);
398
399     connect(this, SIGNAL(locationDataParsed(const QList<Location>&)),
400             m_routingPanel, SLOT(populateLocationListView(const QList<Location>&)));
401
402     connect(m_routingPanel, SIGNAL(locationItemClicked(const GeoCoordinate&, const GeoCoordinate&)),
403             this, SIGNAL(locationItemClicked(const GeoCoordinate&, const GeoCoordinate&)));
404
405     connect(m_routingPanel, SIGNAL(routeToLocation(const GeoCoordinate&)),
406             this, SIGNAL(routeTo(const GeoCoordinate&)));
407
408     connect(this, SIGNAL(routeParsed(Route&)),
409             m_routingPanel, SLOT(setRoute(Route&)));
410
411     connect(m_routingPanel, SIGNAL(routeWaypointItemClicked(GeoCoordinate)),
412             this, SIGNAL(centerToCoordinates(GeoCoordinate)));
413
414     connect(m_routingPanel, SIGNAL(requestSearchLocation()),
415             this, SLOT(startLocationSearch()));
416
417     connect(m_routingPanel, SIGNAL(clearRoute()),
418             this, SIGNAL(clearRoute()));
419 }
420
421 void MainWindow::buildUserInfoPanel()
422 {
423     qDebug() << __PRETTY_FUNCTION__;
424
425     m_userInfoPanel = new UserInfoPanel(this);
426
427     connect(this, SIGNAL(userLocationReady(User*)),
428             m_userInfoPanel, SLOT(userDataReceived(User*)));
429
430     connect(this, SIGNAL(reverseGeoReady(QString)),
431             m_userInfoPanel, SIGNAL(reverseGeoReady(QString)));
432
433     connect(this, SIGNAL(clearUpdateLocationDialogData()),
434             m_userInfoPanel, SIGNAL(clearUpdateLocationDialogData()));
435
436     connect(m_userInfoPanel, SIGNAL(findUser(GeoCoordinate)),
437             this, SIGNAL(centerToCoordinates(GeoCoordinate)));
438
439     connect(m_userInfoPanel, SIGNAL(requestReverseGeo()),
440             this, SIGNAL(requestReverseGeo()));
441
442     connect(m_userInfoPanel, SIGNAL(statusUpdate(QString,bool)),
443             this, SIGNAL(statusUpdate(QString,bool)));
444
445     connect(m_userInfoPanel, SIGNAL(refreshUserData()),
446             this, SIGNAL(refreshUserData()));
447
448     connect(m_userInfoPanel, SIGNAL(notificateUpdateFailing(QString, bool)),
449             this, SLOT(buildInformationBox(QString, bool)));
450 }
451
452 void MainWindow::buildWebView()
453 {
454     qDebug() << __PRETTY_FUNCTION__;
455
456     if(!m_webView) {
457         m_webView = new QWebView;
458
459         if(!m_cookieJar)
460             m_cookieJar = new NetworkCookieJar(new QNetworkCookieJar(this));
461
462         m_webView->page()->networkAccessManager()->setCookieJar(m_cookieJar);
463
464         connect(m_webView->page()->networkAccessManager(), SIGNAL(finished(QNetworkReply*)),
465                 this, SLOT(webViewRequestFinished(QNetworkReply*)));
466         connect(m_webView, SIGNAL(urlChanged(const QUrl &)),
467                 this, SIGNAL(updateCredentials(QUrl)));
468         connect(m_webView, SIGNAL(loadFinished(bool)),
469                 this, SLOT(loadDone(bool)));
470
471         m_webView->hide();
472     }
473 }
474
475 void MainWindow::buildZoomButtonPanel()
476 {
477     qDebug() << __PRETTY_FUNCTION__;
478
479     m_zoomButtonPanel = new ZoomButtonPanel(this);
480
481     connect(m_zoomButtonPanel->zoomInButton(), SIGNAL(clicked()),
482             this, SIGNAL(zoomIn()));
483
484     connect(m_zoomButtonPanel->zoomOutButton(), SIGNAL(clicked()),
485             this, SIGNAL(zoomOut()));
486
487     connect(this, SIGNAL(zoomLevelChanged(int)),
488             m_zoomButtonPanel, SLOT(resetButtons()));
489
490     connect(this, SIGNAL(maxZoomLevelReached()),
491             m_zoomButtonPanel, SLOT(disableZoomInButton()));
492
493     connect(this, SIGNAL(minZoomLevelReached()),
494             m_zoomButtonPanel, SLOT(disableZoomOutButton()));
495
496     connect(m_mapView, SIGNAL(viewResized(QSize)),
497             m_zoomButtonPanel, SLOT(screenResized(QSize)));
498
499     connect(m_zoomButtonPanel, SIGNAL(draggingModeTriggered()),
500             this, SIGNAL(draggingModeTriggered()));
501 }
502
503 void MainWindow::clearCookieJar()
504 {
505     qDebug() << __PRETTY_FUNCTION__;
506
507     buildWebView();
508
509     m_webView->stop();
510
511     if(!m_cookieJar) {
512         m_cookieJar = new NetworkCookieJar(new QNetworkCookieJar(this));
513     }
514     QList<QNetworkCookie> emptyList;
515     emptyList.clear();
516
517     m_cookieJar->setAllCookies(emptyList);
518     m_webView->page()->networkAccessManager()->setCookieJar(m_cookieJar);
519 }
520
521 void MainWindow::createMenus()
522 {
523     qDebug() << __PRETTY_FUNCTION__;
524
525     // login/logout
526     m_loginAct = new QAction(tr("Login"), this);
527     connect(m_loginAct, SIGNAL(triggered()),
528             this, SIGNAL(loginActionPressed()));
529
530     // settings
531     m_toSettingsAct = new QAction(tr("Settings"), this);
532     connect(m_toSettingsAct, SIGNAL(triggered()),
533         this, SLOT(openSettingsDialog()));
534
535     // GPS
536     m_gpsToggleAct = new QAction(tr("GPS"), this);
537     m_gpsToggleAct->setCheckable(true);
538
539     connect(m_gpsToggleAct, SIGNAL(triggered(bool)),
540             this, SIGNAL(gpsTriggered(bool)));
541
542     // build the actual menu
543     m_viewMenu = menuBar()->addMenu(tr("Main"));
544     m_viewMenu->addAction(m_loginAct);
545     m_viewMenu->addAction(m_toSettingsAct);
546     m_viewMenu->addAction(m_gpsToggleAct);
547     m_viewMenu->setObjectName(tr("Menu"));
548 }
549
550 void MainWindow::dialogFinished(int status)
551 {
552     qDebug() << __PRETTY_FUNCTION__;
553
554     QDialog *dialog = m_queue.takeFirst();
555     LoginDialog *loginDialog = qobject_cast<LoginDialog *>(dialog);
556     SearchDialog *searchDialog = qobject_cast<SearchDialog *>(dialog);
557     if(loginDialog) {
558         if(status != 0) {
559             buildWebView();
560             loginDialog->userInput(m_email, m_password);
561
562             QStringList urlParts;
563             urlParts.append(FACEBOOK_LOGINBASE);
564             urlParts.append(SITUARE_PUBLIC_FACEBOOKAPI_KEY);
565             urlParts.append(INTERVAL1);
566             urlParts.append(SITUARE_LOGIN_SUCCESS);
567             urlParts.append(INTERVAL2);
568             urlParts.append(SITUARE_LOGIN_FAILURE);
569             urlParts.append(FACEBOOK_LOGIN_ENDING);
570
571             emit saveUsername(m_email);
572             m_refresh = true;
573             m_webView->load(QUrl(urlParts.join(EMPTY)));
574             toggleProgressIndicator(true);
575         } else {
576             emit cancelLoginProcess();
577         }
578     } else if(searchDialog) {
579         if(status != 0) {
580             emit searchForLocation(searchDialog->input());
581         }
582     }
583
584     dialog->deleteLater();
585
586     if(!m_error_queue.isEmpty() && m_errorShown == false) {
587         showErrorInformationBox();
588     } else {
589         if(!m_queue.isEmpty()) {
590             showInformationBox();
591         }
592     }
593 }
594
595 void MainWindow::drawFullScreenButton(const QSize &size)
596 {
597     qDebug() << __PRETTY_FUNCTION__ << size.width() << "x" << size.height();
598
599     if (m_fullScreenButton) {
600         m_fullScreenButton->move(size.width() - m_fullScreenButton->size().width(),
601                                  size.height() - m_fullScreenButton->size().height());
602     }
603 }
604
605 void MainWindow::drawMapScale(const QSize &size)
606 {
607     qDebug() << __PRETTY_FUNCTION__;
608
609     const int LEFT_SCALE_MARGIN = 10;
610     const int BOTTOM_SCALE_MARGIN = 2;
611
612     m_mapScale->move(LEFT_SCALE_MARGIN,
613                      size.height() - m_mapScale->size().height() - BOTTOM_SCALE_MARGIN);
614 }
615
616 void MainWindow::drawOsmLicense(const QSize &size)
617 {
618     qDebug() << __PRETTY_FUNCTION__ << size.width() << "x" << size.height();
619
620     m_osmLicense->move(size.width() - m_osmLicense->fontMetrics().width(OSM_LICENSE)
621                        - PANEL_BAR_WIDTH,
622                        size.height() - m_osmLicense->fontMetrics().height());
623 }
624
625 void MainWindow::errorDialogFinished(int status)
626 {
627     qDebug() << __PRETTY_FUNCTION__;
628
629     qDebug() << status;
630     QDialog *dialog = m_error_queue.takeFirst();
631
632     dialog->deleteLater();
633     m_errorShown = false;
634
635     if(!m_error_queue.isEmpty())
636         showErrorInformationBox();
637     else if(!m_queue.isEmpty())
638         showInformationBox();
639 }
640
641 void MainWindow::gpsTimeout()
642 {
643     qDebug() << __PRETTY_FUNCTION__;
644
645     buildInformationBox(tr("GPS timeout"));
646 }
647
648 void MainWindow::grabZoomKeys(bool grab)
649 {
650     qDebug() << __PRETTY_FUNCTION__;
651
652 #ifdef Q_WS_MAEMO_5
653     // Can't grab keys unless we have a window id
654     if (!winId())
655         return;
656
657     unsigned long val = (grab) ? 1 : 0;
658     Atom atom = XInternAtom(QX11Info::display(), "_HILDON_ZOOM_KEY_ATOM", False);
659     if (!atom)
660         return;
661
662     XChangeProperty (QX11Info::display(),
663                      winId(),
664                      atom,
665                      XA_INTEGER,
666                      32,
667                      PropModeReplace,
668                      reinterpret_cast<unsigned char *>(&val),
669                      1);
670 #else
671     Q_UNUSED(grab);
672 #endif // Q_WS_MAEMO_5
673 }
674
675 void MainWindow::keyPressEvent(QKeyEvent* event)
676 {
677     qDebug() << __PRETTY_FUNCTION__;
678
679     switch (event->key()) {
680     case Qt::Key_F7:
681         event->accept();
682         emit zoomIn();
683         break;
684
685     case Qt::Key_F8:
686         event->accept();
687         emit zoomOut();
688         break;
689     }
690     QWidget::keyPressEvent(event);
691 }
692
693 void MainWindow::loadCookies()
694 {
695     qDebug() << __PRETTY_FUNCTION__;
696
697     QSettings settings(DIRECTORY_NAME, FILE_NAME);
698
699     QStringList list = settings.value(COOKIES, EMPTY).toStringList();
700
701     if(!list.isEmpty()) {
702         QList<QNetworkCookie> cookieList;
703         for(int i=0;i<list.count();i++) {
704             cookieList.append(QNetworkCookie::parseCookies(list.at(i).toAscii()));
705         }
706
707         if(!m_cookieJar)
708                m_cookieJar = new NetworkCookieJar(new QNetworkCookieJar(this));
709
710         m_cookieJar->setAllCookies(cookieList);
711         m_webView->page()->networkAccessManager()->setCookieJar(m_cookieJar);
712     }
713 }
714
715 void MainWindow::loadDone(bool done)
716 {
717     qDebug() << __PRETTY_FUNCTION__;
718
719     // for the first time the login page is opened, we need to refresh it to get cookies working
720     if(m_refresh) {
721         m_webView->reload();
722         m_refresh = false;
723     }
724
725     if (done)
726     {
727         QWebFrame* frame = m_webView->page()->currentFrame();
728         if (frame!=NULL)
729         {
730             // set email box
731             QWebElementCollection emailCollection = frame->findAllElements("input[name=email]");
732
733             foreach (QWebElement element, emailCollection) {
734                 element.setAttribute("value", m_email.toAscii());
735             }
736             // set password box
737             QWebElementCollection passwordCollection = frame->findAllElements("input[name=pass]");
738             foreach (QWebElement element, passwordCollection) {
739                 element.setAttribute("value", m_password.toAscii());
740             }
741             // find connect button
742             QWebElementCollection buttonCollection = frame->findAllElements("input[name=login]");
743             foreach (QWebElement element, buttonCollection)
744             {
745                 QPoint pos(element.geometry().center());
746
747                 // send a mouse click event to the web page
748                 QMouseEvent event0(QEvent::MouseButtonPress, pos, Qt::LeftButton, Qt::LeftButton,
749                                    Qt::NoModifier);
750                 QApplication::sendEvent(m_webView->page(), &event0);
751                 QMouseEvent event1(QEvent::MouseButtonRelease, pos, Qt::LeftButton, Qt::LeftButton,
752                                    Qt::NoModifier);
753                 QApplication::sendEvent(m_webView->page(), &event1);
754             }
755         }
756     }
757 }
758
759 void MainWindow::loggedIn(bool logged)
760 {
761     qDebug() << __PRETTY_FUNCTION__;
762
763     m_loggedIn = logged;
764
765     if(logged) {
766         m_loginAct->setText(tr("Logout"));
767     } else {
768         clearCookieJar();
769         m_email.clear();
770         m_password.clear();
771
772         m_loginAct->setText(tr("Login"));
773     }
774     updateItemVisibility();
775 }
776
777 void MainWindow::loginFailed()
778 {
779     qDebug() << __PRETTY_FUNCTION__;
780
781     clearCookieJar();
782     startLoginProcess();
783 }
784
785 bool MainWindow::loginState()
786 {
787     qDebug() << __PRETTY_FUNCTION__;
788
789     return m_loggedIn;
790 }
791
792 void MainWindow::loginUsingCookies()
793 {
794     qDebug() << __PRETTY_FUNCTION__;
795
796     toggleProgressIndicator(true);
797
798     buildWebView();
799     loadCookies();
800
801     QStringList urlParts;
802     urlParts.append(FACEBOOK_LOGINBASE);
803     urlParts.append(SITUARE_PUBLIC_FACEBOOKAPI_KEY);
804     urlParts.append(INTERVAL1);
805     urlParts.append(SITUARE_LOGIN_SUCCESS);
806     urlParts.append(INTERVAL2);
807     urlParts.append(SITUARE_LOGIN_FAILURE);
808     urlParts.append(FACEBOOK_LOGIN_ENDING);
809
810     m_webView->load(QUrl(urlParts.join(EMPTY)));
811
812 }
813
814 void MainWindow::mapCenterHorizontalShiftingChanged(int shifting)
815 {
816     m_mapCenterHorizontalShifting = shifting;
817     moveCrosshair();
818 }
819
820 void MainWindow::moveCrosshair()
821 {
822     qDebug() << __PRETTY_FUNCTION__;
823
824     if (m_crosshair) {
825         int mapHeight = m_mapView->size().height();
826         int mapWidth = m_mapView->size().width();
827         m_crosshair->move(mapWidth / 2 - m_crosshair->pixmap()->width() / 2
828                           - m_mapCenterHorizontalShifting,
829                           mapHeight / 2 - m_crosshair->pixmap()->height() / 2);
830     }
831 }
832
833 void MainWindow::openSettingsDialog()
834 {
835     qDebug() << __PRETTY_FUNCTION__;
836
837     SettingsDialog *settingsDialog = new SettingsDialog(this);
838     settingsDialog->enableSituareSettings((m_loggedIn && m_gpsToggleAct->isChecked()));
839     connect(settingsDialog, SIGNAL(accepted()), this, SLOT(settingsDialogAccepted()));
840
841     settingsDialog->show();
842 }
843
844 void MainWindow::queueDialog(QDialog *dialog)
845 {
846     qDebug() << __PRETTY_FUNCTION__;
847
848     // check is dialog is modal, for now all modal dialogs have hihger priority i.e. errors
849     if(dialog->isModal()) {
850         m_error_queue.append(dialog);
851     } else {
852         m_queue.append(dialog);
853     }
854
855     // show error dialog if there is only one error dialog in the queue and no error dialog is shown
856     if(m_error_queue.count() == 1 && m_errorShown == false)
857         showErrorInformationBox();
858     else if(m_queue.count() == 1 && m_errorShown == false)
859         showInformationBox();
860 }
861
862 void MainWindow::readAutomaticLocationUpdateSettings()
863 {
864     qDebug() << __PRETTY_FUNCTION__;
865
866     QSettings settings(DIRECTORY_NAME, FILE_NAME);
867     bool automaticUpdateEnabled = settings.value(SETTINGS_AUTOMATIC_UPDATE_ENABLED, false).toBool();
868     QTime automaticUpdateInterval = settings.value(SETTINGS_AUTOMATIC_UPDATE_INTERVAL, QTime())
869                                       .toTime();
870
871     if (automaticUpdateEnabled && automaticUpdateInterval.isValid()) {
872         QTime time;
873         emit enableAutomaticLocationUpdate(true, time.msecsTo(automaticUpdateInterval));
874     } else {
875         emit enableAutomaticLocationUpdate(false);
876     }
877 }
878
879 void MainWindow::saveCookies()
880 {
881     qDebug() << __PRETTY_FUNCTION__;
882
883     if(!m_cookieJar)
884         m_cookieJar = new NetworkCookieJar(new QNetworkCookieJar(this));
885
886     QList<QNetworkCookie> cookieList = m_cookieJar->allCookies();
887     QStringList list;
888
889     for(int i=0;i<cookieList.count();i++) {
890         QNetworkCookie cookie = cookieList.at(i);
891         QByteArray byteArray = cookie.toRawForm(QNetworkCookie::Full);
892         list.append(QString(byteArray));
893     }
894     list.removeDuplicates();
895
896     QSettings settings(DIRECTORY_NAME, FILE_NAME);
897     settings.setValue(COOKIES, list);
898 }
899
900 void MainWindow::setCrosshairVisibility(bool visibility)
901 {
902     qDebug() << __PRETTY_FUNCTION__;
903
904     if (visibility) {
905         m_crosshair->show();
906         moveCrosshair();
907     } else {
908         m_crosshair->hide();
909     }
910 }
911
912 void MainWindow::setGPSButtonEnabled(bool enabled)
913 {
914     qDebug() << __PRETTY_FUNCTION__;
915
916     m_gpsToggleAct->setChecked(enabled);
917 }
918
919 void MainWindow::setIndicatorButtonEnabled(bool enabled)
920 {
921     qDebug() << __PRETTY_FUNCTION__;
922
923     m_indicatorButtonPanel->setIndicatorButtonEnabled(enabled);
924 }
925
926 void MainWindow::setMapViewScene(QGraphicsScene *scene)
927 {
928     qDebug() << __PRETTY_FUNCTION__;
929
930     m_mapView->setScene(scene);
931 }
932
933 void MainWindow::settingsDialogAccepted()
934 {
935     qDebug() << __PRETTY_FUNCTION__;
936
937     readAutomaticLocationUpdateSettings();
938 }
939
940 void MainWindow::setUsername(const QString &username)
941 {
942     qDebug() << __PRETTY_FUNCTION__;
943
944     m_email = username;
945 }
946
947 void MainWindow::showEnableAutomaticUpdateLocationDialog(const QString &text)
948 {
949     qDebug() << __PRETTY_FUNCTION__;
950
951     m_automaticUpdateLocationDialog = new QMessageBox(QMessageBox::Question,
952                                                       tr("Automatic location update"), text,
953                                                       QMessageBox::Yes | QMessageBox::No |
954                                                       QMessageBox::Cancel, this);
955     connect(m_automaticUpdateLocationDialog, SIGNAL(finished(int)),
956             this, SLOT(automaticUpdateDialogFinished(int)));
957
958     m_automaticUpdateLocationDialog->show();
959 }
960
961 void MainWindow::showErrorInformationBox()
962 {
963     qDebug() << __PRETTY_FUNCTION__;
964
965     if(m_error_queue.count()) {
966         m_errorShown = true;
967         QDialog *dialog = m_error_queue.first();
968         connect(dialog, SIGNAL(finished(int)),
969                 this, SLOT(errorDialogFinished(int)));
970         dialog->show();
971     }
972 }
973
974 void MainWindow::showInformationBox()
975 {
976     qDebug() << __PRETTY_FUNCTION__;
977
978     if(m_queue.count()) {
979         QDialog *dialog = m_queue.first();
980         connect(dialog, SIGNAL(finished(int)),
981                 this, SLOT(dialogFinished(int)));
982         dialog->show();
983     }
984 }
985
986 void MainWindow::showPanels()
987 {
988     qDebug() << __PRETTY_FUNCTION__;
989
990 ///< @todo check how this is called and can this method be removed
991
992 //    if(m_loggedIn) {
993 //        if(!m_friendsListPanel->isVisible()) {
994 //            m_friendsListPanel->show();
995 //            m_friendsListPanelSidebar->show();
996 //        }
997
998 //        if(!m_userPanel->isVisible()) {
999 //            m_userPanel->show();
1000 //            m_userPanelSidebar->show();
1001 //        }
1002 //    }
1003 }
1004
1005 void MainWindow::startLocationSearch()
1006 {
1007     qDebug() << __PRETTY_FUNCTION__;
1008
1009     SearchDialog *searchDialog = new SearchDialog();
1010     queueDialog(searchDialog);
1011 }
1012
1013 void MainWindow::startLoginProcess()
1014 {
1015     qDebug() << __PRETTY_FUNCTION__;
1016
1017     LoginDialog *loginDialog = new LoginDialog();
1018
1019     emit fetchUsernameFromSettings();
1020
1021     loginDialog->clearTextFields();
1022
1023     if(!m_email.isEmpty())
1024         loginDialog->setEmailField(m_email);
1025
1026     queueDialog(loginDialog);
1027 }
1028
1029 void MainWindow::toggleFullScreen()
1030 {
1031     qDebug() << __PRETTY_FUNCTION__;
1032
1033     if(windowState() == Qt::WindowNoState)
1034         showFullScreen();
1035     else
1036         showNormal();
1037 }
1038
1039 void MainWindow::toggleProgressIndicator(bool value)
1040 {
1041     qDebug() << __PRETTY_FUNCTION__;
1042
1043 #ifdef Q_WS_MAEMO_5
1044     if(value) {
1045         m_progressIndicatorCount++;
1046         setAttribute(Qt::WA_Maemo5ShowProgressIndicator, true);
1047     } else {
1048         if(m_progressIndicatorCount > 0)
1049             m_progressIndicatorCount--;
1050
1051         if(m_progressIndicatorCount == 0)
1052             setAttribute(Qt::WA_Maemo5ShowProgressIndicator, false);
1053     }
1054 #else
1055     Q_UNUSED(value);
1056 #endif // Q_WS_MAEMO_5
1057 }
1058
1059 void MainWindow::updateItemVisibility()
1060 {
1061     qDebug() << __PRETTY_FUNCTION__;
1062
1063 ///< @todo can this be removed?
1064
1065 //    if(!m_loggedIn) {
1066 //        m_friendsListPanel->closePanel();
1067 //        m_friendsListPanel->hide();
1068 //        m_friendsListPanelSidebar->hide();
1069
1070 //        m_userPanel->closePanel();
1071 //        m_userPanel->hide();
1072 //        m_userPanelSidebar->hide();
1073 //    }
1074 }
1075
1076 const QString MainWindow::username()
1077 {
1078     qDebug() << __PRETTY_FUNCTION__;
1079
1080     return m_email;
1081 }
1082
1083 void MainWindow::webViewRequestFinished(QNetworkReply *reply)
1084 {
1085     qDebug() << __PRETTY_FUNCTION__;
1086
1087     // omit QNetworkReply::OperationCanceledError due to it's nature to be called when ever
1088     // qwebview starts to load a new page while the current page loading is not finished
1089     if(reply->error() != QNetworkReply::OperationCanceledError &&
1090        reply->error() != QNetworkReply::NoError) {
1091         emit error(ErrorContext::NETWORK, reply->error());
1092     }
1093 }