Fixed map jumping when starting a drag
[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_progressIndicatorCount(0),
69       m_ownLocationCrosshair(0),
70       m_email(), ///< @todo WTF?!?!?!?
71       m_password(),
72       m_webView(0),
73       m_fullScreenButton(0),
74       m_indicatorButtonPanel(0),
75       m_mapScale(0),
76       m_cookieJar(0)
77 {
78     qDebug() << __PRETTY_FUNCTION__;
79
80     buildMap();
81
82     // map view is the only widget which size & location is handled automatically by the system
83     // default functionality
84     setCentralWidget(m_mapView);
85
86     buildPanels();
87
88     createMenus();
89     setWindowTitle(tr("Situare"));
90
91     // set stacking order of widgets (from top to bottom)
92     // if the fullscreen button exists, then it is the topmost one, otherwise the tabbed panel is
93     if (m_fullScreenButton) {
94         m_tabbedPanel->stackUnder(m_fullScreenButton);
95     }
96     m_ownLocationCrosshair->stackUnder(m_tabbedPanel);
97     m_zoomButtonPanel->stackUnder(m_ownLocationCrosshair);
98     m_indicatorButtonPanel->stackUnder(m_zoomButtonPanel);
99     m_osmLicense->stackUnder(m_indicatorButtonPanel);
100     m_mapScale->stackUnder(m_osmLicense);
101     m_mapView->stackUnder(m_mapScale);
102
103     grabZoomKeys(true);
104
105     // Set default screen size
106     resize(DEFAULT_SCREEN_WIDTH, DEFAULT_SCREEN_HEIGHT);
107 #ifdef Q_WS_MAEMO_5
108     setAttribute(Qt::WA_Maemo5StackedWindow);
109 #endif
110 }
111
112 MainWindow::~MainWindow()
113 {
114     qDebug() << __PRETTY_FUNCTION__;
115
116     grabZoomKeys(false);
117
118     if(m_webView)
119         delete m_webView;
120
121     qDeleteAll(m_queue.begin(), m_queue.end());
122     m_queue.clear();
123
124     qDeleteAll(m_error_queue.begin(), m_error_queue.end());
125     m_error_queue.clear();
126 }
127
128 void MainWindow::automaticUpdateDialogFinished(int result)
129 {
130     qDebug() << __PRETTY_FUNCTION__;
131
132     if (result == QMessageBox::Yes) {
133         readAutomaticLocationUpdateSettings();
134     } else {
135         QSettings settings(DIRECTORY_NAME, FILE_NAME);
136         settings.setValue(SETTINGS_AUTOMATIC_UPDATE_ENABLED, false);
137         readAutomaticLocationUpdateSettings();
138     }
139
140     m_automaticUpdateLocationDialog->deleteLater();
141 }
142
143 void MainWindow::buildFullScreenButton()
144 {
145     qDebug() << __PRETTY_FUNCTION__;
146
147 #ifdef Q_WS_MAEMO_5
148     m_fullScreenButton = new FullScreenButton(this);
149
150     if (m_fullScreenButton) {
151         connect(m_fullScreenButton, SIGNAL(clicked()),
152                 this, SLOT(toggleFullScreen()));
153
154         connect(qApp, SIGNAL(showFullScreenButton()),
155                 m_fullScreenButton, SLOT(invoke()));
156     }
157 #endif // Q_WS_MAEMO_5
158 }
159
160 void MainWindow::buildFriendListPanel()
161 {
162     qDebug() << __PRETTY_FUNCTION__;
163
164     m_friendsListPanel = new FriendListPanel(this);
165
166     connect(this, SIGNAL(friendsLocationsReady(QList<User*>&)),
167             m_friendsListPanel, SLOT(friendInfoReceived(QList<User*>&)));
168
169     connect(this, SIGNAL(locationItemClicked(QList<QString>)),
170             m_friendsListPanel, SLOT(showFriendsInList(QList<QString>)));
171
172     connect(m_friendsListPanel, SIGNAL(findFriend(GeoCoordinate)),
173             this, SIGNAL(centerToCoordinates(GeoCoordinate)));
174
175     connect(this, SIGNAL(friendImageReady(User*)),
176             m_friendsListPanel, SLOT(friendImageReady(User*)));
177
178     connect(m_friendsListPanel, SIGNAL(routeToFriend(const GeoCoordinate&)),
179             this, SIGNAL(routeTo(const GeoCoordinate&)));
180 }
181
182 void MainWindow::buildIndicatorButtonPanel()
183 {
184     qDebug() << __PRETTY_FUNCTION__;
185
186     m_indicatorButtonPanel = new IndicatorButtonPanel(this);
187
188     connect(m_indicatorButtonPanel, SIGNAL(autoCenteringTriggered(bool)),
189         this, SIGNAL(autoCenteringTriggered(bool)));
190
191     connect(m_mapView, SIGNAL(viewResized(QSize)),
192             m_indicatorButtonPanel, SLOT(screenResized(QSize)));
193
194     connect(this, SIGNAL(directionIndicatorValuesUpdate(qreal, qreal, bool)),
195             m_indicatorButtonPanel, SIGNAL(directionIndicatorValuesUpdate(qreal, qreal, bool)));
196
197     connect(m_indicatorButtonPanel, SIGNAL(draggingModeTriggered()),
198             this, SIGNAL(draggingModeTriggered()));
199 }
200
201 void MainWindow::buildInformationBox(const QString &message, bool modal)
202 {
203     qDebug() << __PRETTY_FUNCTION__;
204
205     QString errorMessage = message;
206
207 #ifdef Q_WS_MAEMO_5
208
209     QMaemo5InformationBox *msgBox = new QMaemo5InformationBox(this);
210
211     if(modal) {
212         msgBox->setTimeout(QMaemo5InformationBox::NoTimeout);
213         // extra line changes are needed to make error notes broader
214         errorMessage.prepend("\n");
215         errorMessage.append("\n");
216     } else {
217         msgBox->setTimeout(QMaemo5InformationBox::DefaultTimeout);
218     }
219     QLabel *label = new QLabel(msgBox);
220     label->setAlignment(Qt::AlignCenter);
221     label->setText(errorMessage);
222     msgBox->setWidget(label);
223 #else
224     QMessageBox *msgBox = new QMessageBox(this);
225     msgBox->button(QMessageBox::Ok);
226     msgBox->setText(errorMessage);
227     msgBox->setModal(modal);
228 #endif
229
230     queueDialog(msgBox);
231 }
232
233 void MainWindow::buildManualLocationCrosshair()
234 {
235     qDebug() << __PRETTY_FUNCTION__;
236
237     m_ownLocationCrosshair = new QLabel(this);
238     QPixmap crosshairImage(":/res/images/sight.png");
239     m_ownLocationCrosshair->setPixmap(crosshairImage);
240     m_ownLocationCrosshair->setFixedSize(crosshairImage.size());
241     m_ownLocationCrosshair->hide();
242     m_ownLocationCrosshair->setAttribute(Qt::WA_TransparentForMouseEvents, true);
243
244     connect(m_mapView, SIGNAL(viewResized(QSize)),
245             this, SLOT(drawOwnLocationCrosshair(QSize)));
246 }
247
248 void MainWindow::buildMap()
249 {
250     qDebug() << __PRETTY_FUNCTION__;
251
252     m_mapView = new MapView(this);
253
254     buildZoomButtonPanel();
255     buildOsmLicense();
256     buildManualLocationCrosshair();
257     buildFullScreenButton();
258     buildIndicatorButtonPanel();
259     buildMapScale();
260
261     connect(m_mapView, SIGNAL(viewScrolled(SceneCoordinate, bool)),
262             this, SIGNAL(mapViewScrolled(SceneCoordinate, bool)));
263
264     connect(this, SIGNAL(centerToSceneCoordinates(SceneCoordinate, bool)),
265             m_mapView, SLOT(centerToSceneCoordinates(SceneCoordinate, bool)));
266
267     connect(m_mapView, SIGNAL(viewResized(QSize)),
268             this, SIGNAL(mapViewResized(QSize)));
269
270     connect(m_mapView, SIGNAL(viewResized(QSize)),
271             this, SLOT(drawFullScreenButton(QSize)));
272
273     connect(m_mapView, SIGNAL(viewResized(QSize)),
274             this, SLOT(drawMapScale(QSize)));
275
276     connect(m_mapView, SIGNAL(viewResized(QSize)),
277              this, SLOT(setViewPortSize(QSize)));
278
279     connect(this, SIGNAL(zoomLevelChanged(int)),
280             m_mapView, SLOT(setZoomLevel(int)));
281
282     connect(m_mapView, SIGNAL(viewZoomFinished()),
283             this, SIGNAL(viewZoomFinished()));
284
285     connect(m_mapView, SIGNAL(zoomIn()),
286             this, SIGNAL(zoomIn()));
287 }
288
289 void MainWindow::buildMapScale()
290 {
291     m_mapScale = new MapScale(this);
292     connect(this, SIGNAL(newMapResolution(qreal)),
293             m_mapScale, SLOT(updateMapResolution(qreal)));
294 }
295
296 void MainWindow::buildOsmLicense()
297 {
298     qDebug() << __PRETTY_FUNCTION__;
299
300     m_osmLicense = new QLabel(this);
301     m_osmLicense->setAttribute(Qt::WA_TranslucentBackground, true);
302     m_osmLicense->setAttribute(Qt::WA_TransparentForMouseEvents, true);
303     m_osmLicense->setText("<font color='black'>" + OSM_LICENSE + "</font>");
304     m_osmLicense->setFont(QFont("Nokia Sans", 9));
305     m_osmLicense->resize(m_osmLicense->fontMetrics().width(OSM_LICENSE),
306                          m_osmLicense->fontMetrics().height());
307
308     connect(m_mapView, SIGNAL(viewResized(QSize)),
309             this, SLOT(drawOsmLicense(QSize)));
310 }
311
312 void MainWindow::buildPanels()
313 {
314     qDebug() << __PRETTY_FUNCTION__;
315
316     buildUserInfoPanel();
317     buildFriendListPanel();
318     buildRoutingPanel();
319
320     m_tabbedPanel = new TabbedPanel(this);
321     m_tabbedPanel->addTab(m_userInfoPanel, QIcon(":/res/images/user_info.png"));
322     m_tabbedPanel->addTab(m_friendsListPanel, QIcon(":/res/images/friend_list.png"));
323     m_tabbedPanel->addTab(m_routingPanel, QIcon(":/res/images/routing.png"));
324
325     connect(m_mapView, SIGNAL(viewResized(QSize)),
326             m_tabbedPanel, SLOT(resizePanel(QSize)));
327
328     connect(m_friendsListPanel, SIGNAL(showPanelRequested(QWidget*)),
329             m_tabbedPanel, SLOT(showPanel(QWidget*)));
330
331     connect(m_routingPanel, SIGNAL(showPanelRequested(QWidget*)),
332             m_tabbedPanel, SLOT(showPanel(QWidget*)));
333
334     connect(m_tabbedPanel, SIGNAL(panelClosed()),
335             m_friendsListPanel, SLOT(anyPanelClosed()));
336
337     connect(m_tabbedPanel, SIGNAL(panelOpened()),
338             m_friendsListPanel, SLOT(anyPanelOpened()));
339
340     connect(m_tabbedPanel, SIGNAL(panelClosed()),
341             m_routingPanel, SLOT(clearListsSelections()));
342
343     connect(m_tabbedPanel, SIGNAL(panelClosed()),
344             m_mapView, SLOT(disableCenterShift()));
345
346     connect(m_tabbedPanel, SIGNAL(panelOpened()),
347             m_mapView, SLOT(enableCenterShift()));
348 }
349
350 void MainWindow::buildRoutingPanel()
351 {
352     qDebug() << __PRETTY_FUNCTION__;
353
354     m_routingPanel = new RoutingPanel(this);
355
356     connect(this, SIGNAL(locationDataParsed(const QList<Location>&)),
357             m_routingPanel, SLOT(populateLocationListView(const QList<Location>&)));
358
359     connect(m_routingPanel,
360             SIGNAL(locationItemClicked(const GeoCoordinate&, const GeoCoordinate&)),
361             this,
362             SIGNAL(locationItemClicked(const GeoCoordinate&, const GeoCoordinate&)));
363
364     connect(m_routingPanel, SIGNAL(routeToLocation(const GeoCoordinate&)),
365             this, SIGNAL(routeTo(const GeoCoordinate&)));
366
367     connect(this, SIGNAL(routeParsed(Route&)),
368             m_routingPanel, SLOT(setRoute(Route&)));
369
370     connect(m_routingPanel, SIGNAL(routeWaypointItemClicked(GeoCoordinate)),
371             this, SIGNAL(centerToCoordinates(GeoCoordinate)));
372
373     connect(m_routingPanel, SIGNAL(requestSearchLocation()),
374             this, SLOT(startLocationSearch()));
375 }
376
377 void MainWindow::buildUserInfoPanel()
378 {
379     qDebug() << __PRETTY_FUNCTION__;
380
381     m_userInfoPanel = new UserInfoPanel(this);
382
383     connect(this, SIGNAL(userLocationReady(User*)),
384             m_userInfoPanel, SLOT(userDataReceived(User*)));
385
386     connect(this, SIGNAL(reverseGeoReady(QString)),
387             m_userInfoPanel, SIGNAL(reverseGeoReady(QString)));
388
389     connect(this, SIGNAL(clearUpdateLocationDialogData()),
390             m_userInfoPanel, SIGNAL(clearUpdateLocationDialogData()));
391
392     connect(m_userInfoPanel, SIGNAL(findUser(GeoCoordinate)),
393             this, SIGNAL(centerToCoordinates(GeoCoordinate)));
394
395     connect(m_userInfoPanel, SIGNAL(requestReverseGeo()),
396             this, SIGNAL(requestReverseGeo()));
397
398     connect(m_userInfoPanel, SIGNAL(statusUpdate(QString,bool)),
399             this, SIGNAL(statusUpdate(QString,bool)));
400
401     connect(m_userInfoPanel, SIGNAL(refreshUserData()),
402             this, SIGNAL(refreshUserData()));
403
404     connect(m_userInfoPanel, SIGNAL(notificateUpdateFailing(QString, bool)),
405             this, SLOT(buildInformationBox(QString, bool)));
406 }
407
408 void MainWindow::buildWebView()
409 {
410     qDebug() << __PRETTY_FUNCTION__;
411
412     if(!m_webView) {
413         m_webView = new QWebView;
414
415         if(!m_cookieJar)
416             m_cookieJar = new NetworkCookieJar(new QNetworkCookieJar(this));
417
418         m_webView->page()->networkAccessManager()->setCookieJar(m_cookieJar);
419
420         connect(m_webView->page()->networkAccessManager(), SIGNAL(finished(QNetworkReply*)),
421                 this, SLOT(webViewRequestFinished(QNetworkReply*)));
422         connect(m_webView, SIGNAL(urlChanged(const QUrl &)),
423                 this, SIGNAL(updateCredentials(QUrl)));
424         connect(m_webView, SIGNAL(loadFinished(bool)),
425                 this, SLOT(loadDone(bool)));
426
427         m_webView->hide();
428     }
429 }
430
431 void MainWindow::buildZoomButtonPanel()
432 {
433     qDebug() << __PRETTY_FUNCTION__;
434
435     m_zoomButtonPanel = new ZoomButtonPanel(this);
436
437     connect(m_zoomButtonPanel->zoomInButton(), SIGNAL(clicked()),
438             this, SIGNAL(zoomIn()));
439
440     connect(m_zoomButtonPanel->zoomOutButton(), SIGNAL(clicked()),
441             this, SIGNAL(zoomOut()));
442
443     connect(this, SIGNAL(zoomLevelChanged(int)),
444             m_zoomButtonPanel, SLOT(resetButtons()));
445
446     connect(this, SIGNAL(maxZoomLevelReached()),
447             m_zoomButtonPanel, SLOT(disableZoomInButton()));
448
449     connect(this, SIGNAL(minZoomLevelReached()),
450             m_zoomButtonPanel, SLOT(disableZoomOutButton()));
451
452     connect(m_mapView, SIGNAL(viewResized(QSize)),
453             m_zoomButtonPanel, SLOT(screenResized(QSize)));
454
455     connect(m_zoomButtonPanel, SIGNAL(draggingModeTriggered()),
456             this, SIGNAL(draggingModeTriggered()));
457 }
458
459 void MainWindow::clearCookieJar()
460 {
461     qDebug() << __PRETTY_FUNCTION__;
462
463     buildWebView();
464
465     m_webView->stop();
466
467     if(!m_cookieJar) {
468         m_cookieJar = new NetworkCookieJar(new QNetworkCookieJar(this));
469     }
470     QList<QNetworkCookie> emptyList;
471     emptyList.clear();
472
473     m_cookieJar->setAllCookies(emptyList);
474     m_webView->page()->networkAccessManager()->setCookieJar(m_cookieJar);
475 }
476
477 void MainWindow::createMenus()
478 {
479     qDebug() << __PRETTY_FUNCTION__;
480
481     // login/logout
482     m_loginAct = new QAction(tr("Login"), this);
483     connect(m_loginAct, SIGNAL(triggered()),
484             this, SIGNAL(loginActionPressed()));
485
486     // settings
487     m_toSettingsAct = new QAction(tr("Settings"), this);
488     connect(m_toSettingsAct, SIGNAL(triggered()),
489         this, SLOT(openSettingsDialog()));
490
491     // GPS
492     m_gpsToggleAct = new QAction(tr("GPS"), this);
493     m_gpsToggleAct->setCheckable(true);
494
495     connect(m_gpsToggleAct, SIGNAL(triggered(bool)),
496             this, SIGNAL(gpsTriggered(bool)));
497
498     // build the actual menu
499     m_viewMenu = menuBar()->addMenu(tr("Main"));
500     m_viewMenu->addAction(m_loginAct);
501     m_viewMenu->addAction(m_toSettingsAct);
502     m_viewMenu->addAction(m_gpsToggleAct);
503     m_viewMenu->setObjectName(tr("Menu"));
504 }
505
506 void MainWindow::dialogFinished(int status)
507 {
508     qDebug() << __PRETTY_FUNCTION__;
509
510     QDialog *dialog = m_queue.takeFirst();
511     LoginDialog *loginDialog = qobject_cast<LoginDialog *>(dialog);
512     SearchDialog *searchDialog = qobject_cast<SearchDialog *>(dialog);
513     if(loginDialog) {
514         if(status != 0) {
515             buildWebView();
516             loginDialog->userInput(m_email, m_password);
517
518             QStringList urlParts;
519             urlParts.append(FACEBOOK_LOGINBASE);
520             urlParts.append(SITUARE_PUBLIC_FACEBOOKAPI_KEY);
521             urlParts.append(INTERVAL1);
522             urlParts.append(SITUARE_LOGIN_SUCCESS);
523             urlParts.append(INTERVAL2);
524             urlParts.append(SITUARE_LOGIN_FAILURE);
525             urlParts.append(FACEBOOK_LOGIN_ENDING);
526
527             emit saveUsername(m_email);
528             m_refresh = true;
529             m_webView->load(QUrl(urlParts.join(EMPTY)));
530             toggleProgressIndicator(true);
531         } else {
532             emit cancelLoginProcess();
533         }
534     } else if(searchDialog) {
535         if(status != 0) {
536             emit searchForLocation(searchDialog->input());
537         }
538     }
539
540     dialog->deleteLater();
541
542     if(!m_error_queue.isEmpty() && m_errorShown == false) {
543         showErrorInformationBox();
544     } else {
545         if(!m_queue.isEmpty()) {
546             showInformationBox();
547         }
548     }
549 }
550
551 void MainWindow::drawFullScreenButton(const QSize &size)
552 {
553     qDebug() << __PRETTY_FUNCTION__ << size.width() << "x" << size.height();
554
555     if (m_fullScreenButton) {
556         m_fullScreenButton->move(size.width() - m_fullScreenButton->size().width(),
557                                  size.height() - m_fullScreenButton->size().height());
558     }
559 }
560
561 void MainWindow::drawMapScale(const QSize &size)
562 {
563     qDebug() << __PRETTY_FUNCTION__;
564
565     const int LEFT_SCALE_MARGIN = 10;
566     const int BOTTOM_SCALE_MARGIN = 2;
567
568     m_mapScale->move(LEFT_SCALE_MARGIN,
569                      size.height() - m_mapScale->size().height() - BOTTOM_SCALE_MARGIN);
570 }
571
572 void MainWindow::drawOsmLicense(const QSize &size)
573 {
574     qDebug() << __PRETTY_FUNCTION__ << size.width() << "x" << size.height();
575
576     m_osmLicense->move(size.width() - m_osmLicense->fontMetrics().width(OSM_LICENSE)
577                        - PANEL_BAR_WIDTH,
578                        size.height() - m_osmLicense->fontMetrics().height());
579 }
580
581 void MainWindow::drawOwnLocationCrosshair(const QSize &size)
582 {
583     qDebug() << __PRETTY_FUNCTION__;
584
585     if (m_ownLocationCrosshair != 0) {
586         m_ownLocationCrosshair->move(size.width()/2 - m_ownLocationCrosshair->pixmap()->width()/2,
587                             size.height()/2 - m_ownLocationCrosshair->pixmap()->height()/2);
588     }
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::openSettingsDialog()
781 {
782     qDebug() << __PRETTY_FUNCTION__;
783
784     SettingsDialog *settingsDialog = new SettingsDialog(this);
785     settingsDialog->enableSituareSettings((m_loggedIn && m_gpsToggleAct->isChecked()));
786     connect(settingsDialog, SIGNAL(accepted()), this, SLOT(settingsDialogAccepted()));
787
788     settingsDialog->show();
789 }
790
791 void MainWindow::readAutomaticLocationUpdateSettings()
792 {
793     qDebug() << __PRETTY_FUNCTION__;
794
795     QSettings settings(DIRECTORY_NAME, FILE_NAME);
796     bool automaticUpdateEnabled = settings.value(SETTINGS_AUTOMATIC_UPDATE_ENABLED, false).toBool();
797     QTime automaticUpdateInterval = settings.value(SETTINGS_AUTOMATIC_UPDATE_INTERVAL, QTime())
798                                       .toTime();
799
800     if (automaticUpdateEnabled && automaticUpdateInterval.isValid()) {
801         QTime time;
802         emit enableAutomaticLocationUpdate(true, time.msecsTo(automaticUpdateInterval));
803     } else {
804         emit enableAutomaticLocationUpdate(false);
805     }
806 }
807
808 void MainWindow::queueDialog(QDialog *dialog)
809 {
810     qDebug() << __PRETTY_FUNCTION__;
811
812     // check is dialog is modal, for now all modal dialogs have hihger priority i.e. errors
813     if(dialog->isModal()) {
814         m_error_queue.append(dialog);
815     } else {
816         m_queue.append(dialog);
817     }
818
819     // show error dialog if there is only one error dialog in the queue and no error dialog is shown
820     if(m_error_queue.count() == 1 && m_errorShown == false)
821         showErrorInformationBox();
822     else if(m_queue.count() == 1 && m_errorShown == false)
823         showInformationBox();
824 }
825
826 void MainWindow::saveCookies()
827 {
828     qDebug() << __PRETTY_FUNCTION__;
829
830     if(!m_cookieJar)
831         m_cookieJar = new NetworkCookieJar(new QNetworkCookieJar(this));
832
833     QList<QNetworkCookie> cookieList = m_cookieJar->allCookies();
834     QStringList list;
835
836     for(int i=0;i<cookieList.count();i++) {
837         QNetworkCookie cookie = cookieList.at(i);
838         QByteArray byteArray = cookie.toRawForm(QNetworkCookie::Full);
839         list.append(QString(byteArray));
840     }
841     list.removeDuplicates();
842
843     QSettings settings(DIRECTORY_NAME, FILE_NAME);
844     settings.setValue(COOKIES, list);
845 }
846
847 void MainWindow::setGPSButtonEnabled(bool enabled)
848 {
849     qDebug() << __PRETTY_FUNCTION__;
850
851     m_gpsToggleAct->setChecked(enabled);
852 }
853
854 void MainWindow::setIndicatorButtonEnabled(bool enabled)
855 {
856     qDebug() << __PRETTY_FUNCTION__;
857
858     m_indicatorButtonPanel->setIndicatorButtonEnabled(enabled);
859 }
860
861 void MainWindow::setMapViewScene(QGraphicsScene *scene)
862 {
863     qDebug() << __PRETTY_FUNCTION__;
864
865     m_mapView->setScene(scene);
866 }
867
868 void MainWindow::setOwnLocationCrosshairVisibility(bool visibility)
869 {
870     qDebug() << __PRETTY_FUNCTION__;
871
872     if (visibility) {
873         m_ownLocationCrosshair->show();
874         drawOwnLocationCrosshair(m_viewPortSize);
875     } else {
876         m_ownLocationCrosshair->hide();
877     }
878 }
879
880 void MainWindow::settingsDialogAccepted()
881 {
882     qDebug() << __PRETTY_FUNCTION__;
883
884     readAutomaticLocationUpdateSettings();
885 }
886
887 void MainWindow::setUsername(const QString &username)
888 {
889     qDebug() << __PRETTY_FUNCTION__;
890
891     m_email = username;
892 }
893
894 void MainWindow::setViewPortSize(const QSize &size)
895 {
896     qDebug() << __PRETTY_FUNCTION__;
897
898     m_viewPortSize = size;
899 }
900
901 void MainWindow::showEnableAutomaticUpdateLocationDialog(const QString &text)
902 {
903     qDebug() << __PRETTY_FUNCTION__;
904
905     m_automaticUpdateLocationDialog = new QMessageBox(QMessageBox::Question,
906                                                       tr("Automatic location update"), text,
907                                                       QMessageBox::Yes | QMessageBox::No |
908                                                       QMessageBox::Cancel, this);
909     connect(m_automaticUpdateLocationDialog, SIGNAL(finished(int)),
910             this, SLOT(automaticUpdateDialogFinished(int)));
911
912     m_automaticUpdateLocationDialog->show();
913 }
914
915 void MainWindow::toggleFullScreen()
916 {
917     qDebug() << __PRETTY_FUNCTION__;
918
919     if(windowState() == Qt::WindowNoState)
920         showFullScreen();
921     else
922         showNormal();
923 }
924
925 void MainWindow::showErrorInformationBox()
926 {
927     qDebug() << __PRETTY_FUNCTION__;
928
929     if(m_error_queue.count()) {
930         m_errorShown = true;
931         QDialog *dialog = m_error_queue.first();
932         connect(dialog, SIGNAL(finished(int)),
933                 this, SLOT(errorDialogFinished(int)));
934         dialog->show();
935     }
936 }
937
938 void MainWindow::showInformationBox()
939 {
940     qDebug() << __PRETTY_FUNCTION__;
941
942     if(m_queue.count()) {
943         QDialog *dialog = m_queue.first();
944         connect(dialog, SIGNAL(finished(int)),
945                 this, SLOT(dialogFinished(int)));
946         dialog->show();
947     }
948 }
949
950 void MainWindow::showPanels()
951 {
952     qDebug() << __PRETTY_FUNCTION__;
953
954 ///< @todo check how this is called and can this method be removed
955
956 //    if(m_loggedIn) {
957 //        if(!m_friendsListPanel->isVisible()) {
958 //            m_friendsListPanel->show();
959 //            m_friendsListPanelSidebar->show();
960 //        }
961
962 //        if(!m_userPanel->isVisible()) {
963 //            m_userPanel->show();
964 //            m_userPanelSidebar->show();
965 //        }
966 //    }
967 }
968
969 void MainWindow::startLocationSearch()
970 {
971     qDebug() << __PRETTY_FUNCTION__;
972
973     SearchDialog *searchDialog = new SearchDialog();
974     queueDialog(searchDialog);
975 }
976
977 void MainWindow::startLoginProcess()
978 {
979     qDebug() << __PRETTY_FUNCTION__;
980
981     LoginDialog *loginDialog = new LoginDialog();
982
983     emit fetchUsernameFromSettings();
984
985     loginDialog->clearTextFields();
986
987     if(!m_email.isEmpty())
988         loginDialog->setEmailField(m_email);
989
990     queueDialog(loginDialog);
991 }
992
993 void MainWindow::toggleProgressIndicator(bool value)
994 {
995     qDebug() << __PRETTY_FUNCTION__;
996
997 #ifdef Q_WS_MAEMO_5
998     if(value) {
999         m_progressIndicatorCount++;
1000         setAttribute(Qt::WA_Maemo5ShowProgressIndicator, true);
1001     } else {
1002         if(m_progressIndicatorCount > 0)
1003             m_progressIndicatorCount--;
1004
1005         if(m_progressIndicatorCount == 0)
1006             setAttribute(Qt::WA_Maemo5ShowProgressIndicator, false);
1007     }
1008 #else
1009     Q_UNUSED(value);
1010 #endif // Q_WS_MAEMO_5
1011 }
1012
1013 void MainWindow::updateItemVisibility()
1014 {
1015     qDebug() << __PRETTY_FUNCTION__;
1016
1017 ///< @todo can this be removed?
1018
1019 //    if(!m_loggedIn) {
1020 //        m_friendsListPanel->closePanel();
1021 //        m_friendsListPanel->hide();
1022 //        m_friendsListPanelSidebar->hide();
1023
1024 //        m_userPanel->closePanel();
1025 //        m_userPanel->hide();
1026 //        m_userPanelSidebar->hide();
1027 //    }
1028 }
1029
1030 const QString MainWindow::username()
1031 {
1032     qDebug() << __PRETTY_FUNCTION__;
1033
1034     return m_email;
1035 }
1036
1037 void MainWindow::webViewRequestFinished(QNetworkReply *reply)
1038 {
1039     qDebug() << __PRETTY_FUNCTION__;
1040
1041     // omit QNetworkReply::OperationCanceledError due to it's nature to be called when ever
1042     // qwebview starts to load a new page while the current page loading is not finished
1043     if(reply->error() != QNetworkReply::OperationCanceledError &&
1044        reply->error() != QNetworkReply::NoError) {
1045         emit error(ErrorContext::NETWORK, reply->error());
1046     }
1047 }