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