Merge branch 'master' into new_panels_with_context_buttons
[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)),
266             this, SIGNAL(mapViewScrolled(SceneCoordinate)));
267
268     connect(this, SIGNAL(centerToSceneCoordinates(SceneCoordinate)),
269             m_mapView, SLOT(centerToSceneCoordinates(SceneCoordinate)));
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, SIGNAL(locationItemClicked(const GeoCoordinate&, const GeoCoordinate&)),
364             this, SIGNAL(locationItemClicked(const GeoCoordinate&, const GeoCoordinate&)));
365
366     connect(m_routingPanel, SIGNAL(routeToLocation(const GeoCoordinate&)),
367             this, SIGNAL(routeTo(const GeoCoordinate&)));
368
369     connect(this, SIGNAL(routeParsed(Route&)),
370             m_routingPanel, SLOT(setRoute(Route&)));
371
372     connect(m_routingPanel, SIGNAL(routeWaypointItemClicked(GeoCoordinate)),
373             this, SIGNAL(centerToCoordinates(GeoCoordinate)));
374
375     connect(m_routingPanel, SIGNAL(requestSearchLocation()),
376             this, SLOT(startLocationSearch()));
377 }
378
379 void MainWindow::buildUserInfoPanel()
380 {
381     qDebug() << __PRETTY_FUNCTION__;
382
383     m_userInfoPanel = new UserInfoPanel(this);
384
385     connect(this, SIGNAL(userLocationReady(User*)),
386             m_userInfoPanel, SLOT(userDataReceived(User*)));
387
388     connect(this, SIGNAL(reverseGeoReady(QString)),
389             m_userInfoPanel, SIGNAL(reverseGeoReady(QString)));
390
391     connect(this, SIGNAL(clearUpdateLocationDialogData()),
392             m_userInfoPanel, SIGNAL(clearUpdateLocationDialogData()));
393
394     connect(m_userInfoPanel, SIGNAL(findUser(GeoCoordinate)),
395             this, SIGNAL(centerToCoordinates(GeoCoordinate)));
396
397     connect(m_userInfoPanel, SIGNAL(requestReverseGeo()),
398             this, SIGNAL(requestReverseGeo()));
399
400     connect(m_userInfoPanel, SIGNAL(statusUpdate(QString,bool)),
401             this, SIGNAL(statusUpdate(QString,bool)));
402
403     connect(m_userInfoPanel, SIGNAL(refreshUserData()),
404             this, SIGNAL(refreshUserData()));
405
406     connect(m_userInfoPanel, SIGNAL(notificateUpdateFailing(QString, bool)),
407             this, SLOT(buildInformationBox(QString, bool)));
408 }
409
410 void MainWindow::buildWebView()
411 {
412     qDebug() << __PRETTY_FUNCTION__;
413
414     if(!m_webView) {
415         m_webView = new QWebView;
416
417         if(!m_cookieJar)
418             m_cookieJar = new NetworkCookieJar(new QNetworkCookieJar(this));
419
420         m_webView->page()->networkAccessManager()->setCookieJar(m_cookieJar);
421
422         connect(m_webView->page()->networkAccessManager(), SIGNAL(finished(QNetworkReply*)),
423                 this, SLOT(webViewRequestFinished(QNetworkReply*)));
424         connect(m_webView, SIGNAL(urlChanged(const QUrl &)),
425                 this, SIGNAL(updateCredentials(QUrl)));
426         connect(m_webView, SIGNAL(loadFinished(bool)),
427                 this, SLOT(loadDone(bool)));
428
429         m_webView->hide();
430     }
431 }
432
433 void MainWindow::buildZoomButtonPanel()
434 {
435     qDebug() << __PRETTY_FUNCTION__;
436
437     m_zoomButtonPanel = new ZoomButtonPanel(this);
438
439     connect(m_zoomButtonPanel->zoomInButton(), SIGNAL(clicked()),
440             this, SIGNAL(zoomIn()));
441
442     connect(m_zoomButtonPanel->zoomOutButton(), SIGNAL(clicked()),
443             this, SIGNAL(zoomOut()));
444
445     connect(this, SIGNAL(zoomLevelChanged(int)),
446             m_zoomButtonPanel, SLOT(resetButtons()));
447
448     connect(this, SIGNAL(maxZoomLevelReached()),
449             m_zoomButtonPanel, SLOT(disableZoomInButton()));
450
451     connect(this, SIGNAL(minZoomLevelReached()),
452             m_zoomButtonPanel, SLOT(disableZoomOutButton()));
453
454     connect(m_mapView, SIGNAL(viewResized(QSize)),
455             m_zoomButtonPanel, SLOT(screenResized(QSize)));
456
457     connect(m_zoomButtonPanel, SIGNAL(draggingModeTriggered()),
458             this, SIGNAL(draggingModeTriggered()));
459 }
460
461 void MainWindow::clearCookieJar()
462 {
463     qDebug() << __PRETTY_FUNCTION__;
464
465     buildWebView();
466
467     m_webView->stop();
468
469     if(!m_cookieJar) {
470         m_cookieJar = new NetworkCookieJar(new QNetworkCookieJar(this));
471     }
472     QList<QNetworkCookie> emptyList;
473     emptyList.clear();
474
475     m_cookieJar->setAllCookies(emptyList);
476     m_webView->page()->networkAccessManager()->setCookieJar(m_cookieJar);
477 }
478
479 void MainWindow::createMenus()
480 {
481     qDebug() << __PRETTY_FUNCTION__;
482
483     // login/logout
484     m_loginAct = new QAction(tr("Login"), this);
485     connect(m_loginAct, SIGNAL(triggered()),
486             this, SIGNAL(loginActionPressed()));
487
488     // settings
489     m_toSettingsAct = new QAction(tr("Settings"), this);
490     connect(m_toSettingsAct, SIGNAL(triggered()),
491         this, SLOT(openSettingsDialog()));
492
493     // GPS
494     m_gpsToggleAct = new QAction(tr("GPS"), this);
495     m_gpsToggleAct->setCheckable(true);
496
497     connect(m_gpsToggleAct, SIGNAL(triggered(bool)),
498             this, SIGNAL(gpsTriggered(bool)));
499
500     // build the actual menu
501     m_viewMenu = menuBar()->addMenu(tr("Main"));
502     m_viewMenu->addAction(m_loginAct);
503     m_viewMenu->addAction(m_toSettingsAct);
504     m_viewMenu->addAction(m_gpsToggleAct);
505     m_viewMenu->setObjectName(tr("Menu"));
506 }
507
508 void MainWindow::dialogFinished(int status)
509 {
510     qDebug() << __PRETTY_FUNCTION__;
511
512     QDialog *dialog = m_queue.takeFirst();
513     LoginDialog *loginDialog = qobject_cast<LoginDialog *>(dialog);
514     SearchDialog *searchDialog = qobject_cast<SearchDialog *>(dialog);
515     if(loginDialog) {
516         if(status != 0) {
517             buildWebView();
518             loginDialog->userInput(m_email, m_password);
519
520             QStringList urlParts;
521             urlParts.append(FACEBOOK_LOGINBASE);
522             urlParts.append(SITUARE_PUBLIC_FACEBOOKAPI_KEY);
523             urlParts.append(INTERVAL1);
524             urlParts.append(SITUARE_LOGIN_SUCCESS);
525             urlParts.append(INTERVAL2);
526             urlParts.append(SITUARE_LOGIN_FAILURE);
527             urlParts.append(FACEBOOK_LOGIN_ENDING);
528
529             emit saveUsername(m_email);
530             m_refresh = true;
531             m_webView->load(QUrl(urlParts.join(EMPTY)));
532             toggleProgressIndicator(true);
533         } else {
534             emit cancelLoginProcess();
535         }
536     } else if(searchDialog) {
537         if(status != 0) {
538             emit searchForLocation(searchDialog->input());
539         }
540     }
541
542     dialog->deleteLater();
543
544     if(!m_error_queue.isEmpty() && m_errorShown == false) {
545         showErrorInformationBox();
546     } else {
547         if(!m_queue.isEmpty()) {
548             showInformationBox();
549         }
550     }
551 }
552
553 void MainWindow::drawFullScreenButton(const QSize &size)
554 {
555     qDebug() << __PRETTY_FUNCTION__ << size.width() << "x" << size.height();
556
557     if (m_fullScreenButton) {
558         m_fullScreenButton->move(size.width() - m_fullScreenButton->size().width(),
559                                  size.height() - m_fullScreenButton->size().height());
560     }
561 }
562
563 void MainWindow::drawMapScale(const QSize &size)
564 {
565     qDebug() << __PRETTY_FUNCTION__;
566
567     const int LEFT_SCALE_MARGIN = 10;
568     const int BOTTOM_SCALE_MARGIN = 2;
569
570     m_mapScale->move(LEFT_SCALE_MARGIN,
571                      size.height() - m_mapScale->size().height() - BOTTOM_SCALE_MARGIN);
572 }
573
574 void MainWindow::drawOsmLicense(const QSize &size)
575 {
576     qDebug() << __PRETTY_FUNCTION__ << size.width() << "x" << size.height();
577
578     m_osmLicense->move(size.width() - m_osmLicense->fontMetrics().width(OSM_LICENSE)
579                        - PANEL_BAR_WIDTH,
580                        size.height() - m_osmLicense->fontMetrics().height());
581 }
582
583 void MainWindow::errorDialogFinished(int status)
584 {
585     qDebug() << __PRETTY_FUNCTION__;
586
587     qDebug() << status;
588     QDialog *dialog = m_error_queue.takeFirst();
589
590     dialog->deleteLater();
591     m_errorShown = false;
592
593     if(!m_error_queue.isEmpty())
594         showErrorInformationBox();
595     else if(!m_queue.isEmpty())
596         showInformationBox();
597 }
598
599 void MainWindow::gpsTimeout()
600 {
601     qDebug() << __PRETTY_FUNCTION__;
602
603     buildInformationBox(tr("GPS timeout"));
604 }
605
606 void MainWindow::grabZoomKeys(bool grab)
607 {
608     qDebug() << __PRETTY_FUNCTION__;
609
610 #ifdef Q_WS_MAEMO_5
611     // Can't grab keys unless we have a window id
612     if (!winId())
613         return;
614
615     unsigned long val = (grab) ? 1 : 0;
616     Atom atom = XInternAtom(QX11Info::display(), "_HILDON_ZOOM_KEY_ATOM", False);
617     if (!atom)
618         return;
619
620     XChangeProperty (QX11Info::display(),
621                      winId(),
622                      atom,
623                      XA_INTEGER,
624                      32,
625                      PropModeReplace,
626                      reinterpret_cast<unsigned char *>(&val),
627                      1);
628 #else
629     Q_UNUSED(grab);
630 #endif // Q_WS_MAEMO_5
631 }
632
633 void MainWindow::keyPressEvent(QKeyEvent* event)
634 {
635     qDebug() << __PRETTY_FUNCTION__;
636
637     switch (event->key()) {
638     case Qt::Key_F7:
639         event->accept();
640         emit zoomIn();
641         break;
642
643     case Qt::Key_F8:
644         event->accept();
645         emit zoomOut();
646         break;
647     }
648     QWidget::keyPressEvent(event);
649 }
650
651 void MainWindow::loadCookies()
652 {
653     qDebug() << __PRETTY_FUNCTION__;
654
655     QSettings settings(DIRECTORY_NAME, FILE_NAME);
656
657     QStringList list = settings.value(COOKIES, EMPTY).toStringList();
658
659     if(!list.isEmpty()) {
660         QList<QNetworkCookie> cookieList;
661         for(int i=0;i<list.count();i++) {
662             cookieList.append(QNetworkCookie::parseCookies(list.at(i).toAscii()));
663         }
664
665         if(!m_cookieJar)
666                m_cookieJar = new NetworkCookieJar(new QNetworkCookieJar(this));
667
668         m_cookieJar->setAllCookies(cookieList);
669         m_webView->page()->networkAccessManager()->setCookieJar(m_cookieJar);
670     }
671 }
672
673 void MainWindow::loadDone(bool done)
674 {
675     qDebug() << __PRETTY_FUNCTION__;
676
677     // for the first time the login page is opened, we need to refresh it to get cookies working
678     if(m_refresh) {
679         m_webView->reload();
680         m_refresh = false;
681     }
682
683     if (done)
684     {
685         QWebFrame* frame = m_webView->page()->currentFrame();
686         if (frame!=NULL)
687         {
688             // set email box
689             QWebElementCollection emailCollection = frame->findAllElements("input[name=email]");
690
691             foreach (QWebElement element, emailCollection) {
692                 element.setAttribute("value", m_email.toAscii());
693             }
694             // set password box
695             QWebElementCollection passwordCollection = frame->findAllElements("input[name=pass]");
696             foreach (QWebElement element, passwordCollection) {
697                 element.setAttribute("value", m_password.toAscii());
698             }
699             // find connect button
700             QWebElementCollection buttonCollection = frame->findAllElements("input[name=login]");
701             foreach (QWebElement element, buttonCollection)
702             {
703                 QPoint pos(element.geometry().center());
704
705                 // send a mouse click event to the web page
706                 QMouseEvent event0(QEvent::MouseButtonPress, pos, Qt::LeftButton, Qt::LeftButton,
707                                    Qt::NoModifier);
708                 QApplication::sendEvent(m_webView->page(), &event0);
709                 QMouseEvent event1(QEvent::MouseButtonRelease, pos, Qt::LeftButton, Qt::LeftButton,
710                                    Qt::NoModifier);
711                 QApplication::sendEvent(m_webView->page(), &event1);
712             }
713         }
714     }
715 }
716
717 void MainWindow::loggedIn(bool logged)
718 {
719     qDebug() << __PRETTY_FUNCTION__;
720
721     m_loggedIn = logged;
722
723     if(logged) {
724         m_loginAct->setText(tr("Logout"));
725     } else {
726         clearCookieJar();
727         m_email.clear();
728         m_password.clear();
729
730         m_loginAct->setText(tr("Login"));
731     }
732     updateItemVisibility();
733 }
734
735 void MainWindow::loginFailed()
736 {
737     qDebug() << __PRETTY_FUNCTION__;
738
739     clearCookieJar();
740     startLoginProcess();
741 }
742
743 bool MainWindow::loginState()
744 {
745     qDebug() << __PRETTY_FUNCTION__;
746
747     return m_loggedIn;
748 }
749
750 void MainWindow::loginUsingCookies()
751 {
752     qDebug() << __PRETTY_FUNCTION__;
753
754     toggleProgressIndicator(true);
755
756     buildWebView();
757     loadCookies();
758
759     QStringList urlParts;
760     urlParts.append(FACEBOOK_LOGINBASE);
761     urlParts.append(SITUARE_PUBLIC_FACEBOOKAPI_KEY);
762     urlParts.append(INTERVAL1);
763     urlParts.append(SITUARE_LOGIN_SUCCESS);
764     urlParts.append(INTERVAL2);
765     urlParts.append(SITUARE_LOGIN_FAILURE);
766     urlParts.append(FACEBOOK_LOGIN_ENDING);
767
768     m_webView->load(QUrl(urlParts.join(EMPTY)));
769
770 }
771
772 void MainWindow::mapCenterHorizontalShiftingChanged(int shifting)
773 {
774     m_mapCenterHorizontalShifting = shifting;
775     moveCrosshair();
776 }
777
778 void MainWindow::moveCrosshair()
779 {
780     qDebug() << __PRETTY_FUNCTION__;
781
782     if (m_crosshair) {
783         int mapHeight = m_mapView->size().height();
784         int mapWidth = m_mapView->size().width();
785         m_crosshair->move(mapWidth / 2 - m_crosshair->pixmap()->width() / 2
786                           - m_mapCenterHorizontalShifting,
787                           mapHeight / 2 - m_crosshair->pixmap()->height() / 2);
788     }
789 }
790
791 void MainWindow::openSettingsDialog()
792 {
793     qDebug() << __PRETTY_FUNCTION__;
794
795     SettingsDialog *settingsDialog = new SettingsDialog(this);
796     settingsDialog->enableSituareSettings((m_loggedIn && m_gpsToggleAct->isChecked()));
797     connect(settingsDialog, SIGNAL(accepted()), this, SLOT(settingsDialogAccepted()));
798
799     settingsDialog->show();
800 }
801
802 void MainWindow::queueDialog(QDialog *dialog)
803 {
804     qDebug() << __PRETTY_FUNCTION__;
805
806     // check is dialog is modal, for now all modal dialogs have hihger priority i.e. errors
807     if(dialog->isModal()) {
808         m_error_queue.append(dialog);
809     } else {
810         m_queue.append(dialog);
811     }
812
813     // show error dialog if there is only one error dialog in the queue and no error dialog is shown
814     if(m_error_queue.count() == 1 && m_errorShown == false)
815         showErrorInformationBox();
816     else if(m_queue.count() == 1 && m_errorShown == false)
817         showInformationBox();
818 }
819
820 void MainWindow::readAutomaticLocationUpdateSettings()
821 {
822     qDebug() << __PRETTY_FUNCTION__;
823
824     QSettings settings(DIRECTORY_NAME, FILE_NAME);
825     bool automaticUpdateEnabled = settings.value(SETTINGS_AUTOMATIC_UPDATE_ENABLED, false).toBool();
826     QTime automaticUpdateInterval = settings.value(SETTINGS_AUTOMATIC_UPDATE_INTERVAL, QTime())
827                                       .toTime();
828
829     if (automaticUpdateEnabled && automaticUpdateInterval.isValid()) {
830         QTime time;
831         emit enableAutomaticLocationUpdate(true, time.msecsTo(automaticUpdateInterval));
832     } else {
833         emit enableAutomaticLocationUpdate(false);
834     }
835 }
836
837 void MainWindow::saveCookies()
838 {
839     qDebug() << __PRETTY_FUNCTION__;
840
841     if(!m_cookieJar)
842         m_cookieJar = new NetworkCookieJar(new QNetworkCookieJar(this));
843
844     QList<QNetworkCookie> cookieList = m_cookieJar->allCookies();
845     QStringList list;
846
847     for(int i=0;i<cookieList.count();i++) {
848         QNetworkCookie cookie = cookieList.at(i);
849         QByteArray byteArray = cookie.toRawForm(QNetworkCookie::Full);
850         list.append(QString(byteArray));
851     }
852     list.removeDuplicates();
853
854     QSettings settings(DIRECTORY_NAME, FILE_NAME);
855     settings.setValue(COOKIES, list);
856 }
857
858 void MainWindow::setCrosshairVisibility(bool visibility)
859 {
860     qDebug() << __PRETTY_FUNCTION__;
861
862     if (visibility) {
863         m_crosshair->show();
864         moveCrosshair();
865     } else {
866         m_crosshair->hide();
867     }
868 }
869
870 void MainWindow::setGPSButtonEnabled(bool enabled)
871 {
872     qDebug() << __PRETTY_FUNCTION__;
873
874     m_gpsToggleAct->setChecked(enabled);
875 }
876
877 void MainWindow::setIndicatorButtonEnabled(bool enabled)
878 {
879     qDebug() << __PRETTY_FUNCTION__;
880
881     m_indicatorButtonPanel->setIndicatorButtonEnabled(enabled);
882 }
883
884 void MainWindow::setMapViewScene(QGraphicsScene *scene)
885 {
886     qDebug() << __PRETTY_FUNCTION__;
887
888     m_mapView->setScene(scene);
889 }
890
891 void MainWindow::settingsDialogAccepted()
892 {
893     qDebug() << __PRETTY_FUNCTION__;
894
895     readAutomaticLocationUpdateSettings();
896 }
897
898 void MainWindow::setUsername(const QString &username)
899 {
900     qDebug() << __PRETTY_FUNCTION__;
901
902     m_email = username;
903 }
904
905 void MainWindow::showEnableAutomaticUpdateLocationDialog(const QString &text)
906 {
907     qDebug() << __PRETTY_FUNCTION__;
908
909     m_automaticUpdateLocationDialog = new QMessageBox(QMessageBox::Question,
910                                                       tr("Automatic location update"), text,
911                                                       QMessageBox::Yes | QMessageBox::No |
912                                                       QMessageBox::Cancel, this);
913     connect(m_automaticUpdateLocationDialog, SIGNAL(finished(int)),
914             this, SLOT(automaticUpdateDialogFinished(int)));
915
916     m_automaticUpdateLocationDialog->show();
917 }
918
919 void MainWindow::showErrorInformationBox()
920 {
921     qDebug() << __PRETTY_FUNCTION__;
922
923     if(m_error_queue.count()) {
924         m_errorShown = true;
925         QDialog *dialog = m_error_queue.first();
926         connect(dialog, SIGNAL(finished(int)),
927                 this, SLOT(errorDialogFinished(int)));
928         dialog->show();
929     }
930 }
931
932 void MainWindow::showInformationBox()
933 {
934     qDebug() << __PRETTY_FUNCTION__;
935
936     if(m_queue.count()) {
937         QDialog *dialog = m_queue.first();
938         connect(dialog, SIGNAL(finished(int)),
939                 this, SLOT(dialogFinished(int)));
940         dialog->show();
941     }
942 }
943
944 void MainWindow::showPanels()
945 {
946     qDebug() << __PRETTY_FUNCTION__;
947
948 ///< @todo check how this is called and can this method be removed
949
950 //    if(m_loggedIn) {
951 //        if(!m_friendsListPanel->isVisible()) {
952 //            m_friendsListPanel->show();
953 //            m_friendsListPanelSidebar->show();
954 //        }
955
956 //        if(!m_userPanel->isVisible()) {
957 //            m_userPanel->show();
958 //            m_userPanelSidebar->show();
959 //        }
960 //    }
961 }
962
963 void MainWindow::startLocationSearch()
964 {
965     qDebug() << __PRETTY_FUNCTION__;
966
967     SearchDialog *searchDialog = new SearchDialog();
968     queueDialog(searchDialog);
969 }
970
971 void MainWindow::startLoginProcess()
972 {
973     qDebug() << __PRETTY_FUNCTION__;
974
975     LoginDialog *loginDialog = new LoginDialog();
976
977     emit fetchUsernameFromSettings();
978
979     loginDialog->clearTextFields();
980
981     if(!m_email.isEmpty())
982         loginDialog->setEmailField(m_email);
983
984     queueDialog(loginDialog);
985 }
986
987 void MainWindow::toggleFullScreen()
988 {
989     qDebug() << __PRETTY_FUNCTION__;
990
991     if(windowState() == Qt::WindowNoState)
992         showFullScreen();
993     else
994         showNormal();
995 }
996
997 void MainWindow::toggleProgressIndicator(bool value)
998 {
999     qDebug() << __PRETTY_FUNCTION__;
1000
1001 #ifdef Q_WS_MAEMO_5
1002     if(value) {
1003         m_progressIndicatorCount++;
1004         setAttribute(Qt::WA_Maemo5ShowProgressIndicator, true);
1005     } else {
1006         if(m_progressIndicatorCount > 0)
1007             m_progressIndicatorCount--;
1008
1009         if(m_progressIndicatorCount == 0)
1010             setAttribute(Qt::WA_Maemo5ShowProgressIndicator, false);
1011     }
1012 #else
1013     Q_UNUSED(value);
1014 #endif // Q_WS_MAEMO_5
1015 }
1016
1017 void MainWindow::updateItemVisibility()
1018 {
1019     qDebug() << __PRETTY_FUNCTION__;
1020
1021 ///< @todo can this be removed?
1022
1023 //    if(!m_loggedIn) {
1024 //        m_friendsListPanel->closePanel();
1025 //        m_friendsListPanel->hide();
1026 //        m_friendsListPanelSidebar->hide();
1027
1028 //        m_userPanel->closePanel();
1029 //        m_userPanel->hide();
1030 //        m_userPanelSidebar->hide();
1031 //    }
1032 }
1033
1034 const QString MainWindow::username()
1035 {
1036     qDebug() << __PRETTY_FUNCTION__;
1037
1038     return m_email;
1039 }
1040
1041 void MainWindow::webViewRequestFinished(QNetworkReply *reply)
1042 {
1043     qDebug() << __PRETTY_FUNCTION__;
1044
1045     // omit QNetworkReply::OperationCanceledError due to it's nature to be called when ever
1046     // qwebview starts to load a new page while the current page loading is not finished
1047     if(reply->error() != QNetworkReply::OperationCanceledError &&
1048        reply->error() != QNetworkReply::NoError) {
1049         emit error(ErrorContext::NETWORK, reply->error());
1050     }
1051 }