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