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